refactor: 统一模板契约并修复预览版本
This commit is contained in:
1 parent
cd2992c00a
commit
50b87e48de
56 files changed
+7849
-5756
No files matched your search
@@ -17,11 +17,7 @@ function pageContent({ workspace, page }) {
|
||||
}
|
||||
|
||||
export function resolveTemplateRenderer(workspace) {
|
||||
const config = workspace?.brand?.config;
|
||||
const key =
|
||||
config && typeof config === "object" && !Array.isArray(config)
|
||||
? config.visualTemplateKey
|
||||
: undefined;
|
||||
const key = workspace?.visualTemplate?.key;
|
||||
if (typeof key !== "string") return null;
|
||||
if (resolvedRenderers.has(key)) return resolvedRenderers.get(key);
|
||||
const suffix = `/template-${key}/taro/index.tsx`;
|
||||
|
||||
@@ -111,8 +111,6 @@ export function useBrandSaveMutation({
|
||||
return useMutation({
|
||||
mutationFn: (values: PresentationValues) => {
|
||||
const nextConfig = applyPresentationValues(config, sections, values);
|
||||
const contentConfig = { ...nextConfig };
|
||||
delete contentConfig.visualTemplateKey;
|
||||
const standard = applyStandardBrandValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
sections,
|
||||
@@ -124,7 +122,7 @@ export function useBrandSaveMutation({
|
||||
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
|
||||
),
|
||||
);
|
||||
return createApiClient().updateAdminBrand({ ...changed, config: contentConfig });
|
||||
return createApiClient().updateAdminBrand({ ...changed, config: nextConfig });
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSaved();
|
||||
|
||||
@@ -80,7 +80,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
};
|
||||
const mutations = usePublicationMutations({
|
||||
refresh,
|
||||
brandConfig: brand.data?.config,
|
||||
currentTemplatePackageVersionId: workspace.data?.installations[0]?.templatePackageVersionId,
|
||||
onInstallClose: () => setIndustryTarget(null),
|
||||
onPublishClose: () => setConfirmAction(null),
|
||||
onNoteClear: () => setNote(""),
|
||||
@@ -104,16 +104,14 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
workspace.data?.installations[0]?.templateKey ??
|
||||
workspace.data?.brand?.templateKey ??
|
||||
brand.data?.templateKey ??
|
||||
catalog.data?.industries[0]?.key ??
|
||||
null;
|
||||
const visuals = (catalog.data?.visuals ?? []).filter(
|
||||
const selectablePackageVersions = (queries.packages.data?.items ?? []).filter(
|
||||
(item) =>
|
||||
typeof industryKey === "string" && item.supportedIndustryTemplates.includes(industryKey),
|
||||
item.status === "published" &&
|
||||
typeof industryKey === "string" &&
|
||||
item.manifestSummary?.supportedIndustryTemplates.includes(industryKey),
|
||||
);
|
||||
const visualKey =
|
||||
typeof brand.data?.config?.visualTemplateKey === "string"
|
||||
? brand.data.config.visualTemplateKey
|
||||
: (visuals[0]?.key ?? null);
|
||||
const visualKey = workspace.data?.installations[0]?.visualTemplateKey ?? null;
|
||||
const currentRelease = releases.data?.find((item) => item.status === "published");
|
||||
const publishedHistory = (releases.data ?? []).filter(
|
||||
(item) => item.status === "published" || item.status === "superseded",
|
||||
@@ -182,8 +180,11 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
value={visualKey}
|
||||
disabled={!canManageTemplate}
|
||||
loading={selectVisual.isPending}
|
||||
options={visuals.map((item) => ({ value: item.key, label: item.name }))}
|
||||
onChange={(key) => selectVisual.mutate(key)}
|
||||
options={selectablePackageVersions.map((item) => ({
|
||||
value: item.id,
|
||||
label: `${item.displayName} · ${item.version}`,
|
||||
}))}
|
||||
onChange={(versionId) => selectVisual.mutate(versionId)}
|
||||
/>
|
||||
</Space>
|
||||
{industryKey ? (
|
||||
@@ -350,9 +351,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
{sample.data && !sample.data.alreadyImported && (
|
||||
<p className="admin-section-description admin-offset-top-sm">
|
||||
来源:{sample.data.source.packageKey}@{sample.data.source.version}
|
||||
{sample.data.source.contentChecksum
|
||||
? `(checksum ${sample.data.source.contentChecksum.slice(0, 12)})`
|
||||
: "(兼容 registry 来源)"}
|
||||
(checksum {(sample.data.source.contentChecksum ?? "").slice(0, 12)})
|
||||
。将向草稿添加{" "}
|
||||
{Object.entries(sample.data.counts)
|
||||
.map(([key, count]) => `${key} ${count} 项`)
|
||||
@@ -589,7 +588,15 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
title="确认安装行业模板"
|
||||
open={industryTarget !== null}
|
||||
onCancel={() => setIndustryTarget(null)}
|
||||
onOk={() => industryTarget && install.mutate({ key: industryTarget })}
|
||||
okButtonProps={{ disabled: !templatePreview.data?.targetPackageVersionId }}
|
||||
onOk={() =>
|
||||
industryTarget &&
|
||||
templatePreview.data?.targetPackageVersionId &&
|
||||
install.mutate({
|
||||
key: industryTarget,
|
||||
versionId: templatePreview.data.targetPackageVersionId,
|
||||
})
|
||||
}
|
||||
confirmLoading={install.isPending}
|
||||
>
|
||||
模板会更新当前品牌的草稿结构,不会立即改变已发布的小程序。请安装后核对业务内容与视觉模板。
|
||||
|
||||
@@ -7,7 +7,7 @@ const client = createApiClient();
|
||||
|
||||
interface MutationOptions {
|
||||
refresh: () => void;
|
||||
brandConfig: Record<string, unknown> | null | undefined;
|
||||
currentTemplatePackageVersionId: string | null | undefined;
|
||||
onInstallClose: () => void;
|
||||
onPublishClose: () => void;
|
||||
onNoteClear: () => void;
|
||||
@@ -20,11 +20,11 @@ export function usePublicationMutations({
|
||||
onPublishClose,
|
||||
onNoteClear,
|
||||
onRollbackClose,
|
||||
brandConfig,
|
||||
currentTemplatePackageVersionId,
|
||||
}: MutationOptions) {
|
||||
const queryClient = useQueryClient();
|
||||
const install = useMutation({
|
||||
mutationFn: ({ key, versionId }: { key: BrandTemplateKey; versionId?: string }) =>
|
||||
mutationFn: ({ key, versionId }: { key: BrandTemplateKey; versionId: string }) =>
|
||||
client.installAdminTemplate(key, versionId),
|
||||
onSuccess: () => {
|
||||
onInstallClose();
|
||||
@@ -55,12 +55,16 @@ export function usePublicationMutations({
|
||||
},
|
||||
});
|
||||
const selectVisual = useMutation({
|
||||
mutationFn: (key: string) =>
|
||||
client.updateAdminBrand({
|
||||
config: { ...(brandConfig ?? {}), visualTemplateKey: key },
|
||||
mutationFn: (templatePackageVersionId: string) =>
|
||||
client.selectAdminTemplateVersion({
|
||||
templatePackageVersionId,
|
||||
...(currentTemplatePackageVersionId !== undefined
|
||||
? { expectedCurrentPackageVersionId: currentTemplatePackageVersionId }
|
||||
: {}),
|
||||
confirm: true,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已保存到草稿");
|
||||
message.success("模板版本已切换");
|
||||
refresh();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -24,6 +24,10 @@ export function usePublicationQueries(
|
||||
queryKey: ["publication-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const packages = useQuery<Awaited<ReturnType<typeof client.listAdminTemplatePackages>>>({
|
||||
queryKey: ["publication-template-packages"],
|
||||
queryFn: () => client.listAdminTemplatePackages({ page: 1, pageSize: 100 }),
|
||||
});
|
||||
const sample = useQuery<Awaited<ReturnType<typeof client.previewAdminSampleContent>>>({
|
||||
queryKey: ["publication-sample", workspace.data?.installations[0]?.templatePackageVersionId],
|
||||
queryFn: () =>
|
||||
@@ -82,6 +86,7 @@ export function usePublicationQueries(
|
||||
brand,
|
||||
workspace,
|
||||
catalog,
|
||||
packages,
|
||||
readiness,
|
||||
releases,
|
||||
miniAppReleases,
|
||||
@@ -91,6 +96,7 @@ export function usePublicationQueries(
|
||||
brand,
|
||||
workspace,
|
||||
catalog,
|
||||
packages,
|
||||
readiness,
|
||||
releases,
|
||||
miniAppReleases,
|
||||
@@ -100,6 +106,7 @@ export function usePublicationQueries(
|
||||
void brand.refetch();
|
||||
void workspace.refetch();
|
||||
void catalog.refetch();
|
||||
void packages.refetch();
|
||||
void readiness.refetch();
|
||||
void releases.refetch();
|
||||
void miniAppReleases.refetch();
|
||||
@@ -110,6 +117,7 @@ export function usePublicationQueries(
|
||||
brand,
|
||||
workspace,
|
||||
catalog,
|
||||
packages,
|
||||
sample,
|
||||
readiness,
|
||||
releases,
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation"
|
||||
GROUP BY "brandId"
|
||||
HAVING COUNT(*) > 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: a brand has multiple template installations';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
LEFT JOIN "TemplatePackageVersion" package_version
|
||||
ON package_version."id" = installation."templatePackageVersionId"
|
||||
WHERE installation."templatePackageVersionId" IS NULL
|
||||
OR package_version."id" IS NULL
|
||||
OR package_version."status" <> 'published'
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: an installation has no exact package version';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
JOIN "TemplatePackageVersion" package_version
|
||||
ON package_version."id" = installation."templatePackageVersionId"
|
||||
JOIN "BrandProfile" brand ON brand."id" = installation."brandId"
|
||||
WHERE installation."visualTemplateKey" IS DISTINCT FROM package_version."visualTemplateKey"
|
||||
OR package_version."visualTemplateKey" IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'visualTemplateKey' IS DISTINCT FROM package_version."visualTemplateKey"
|
||||
OR package_version."manifestSnapshot"->>'packageKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'version' IS DISTINCT FROM package_version."version"
|
||||
OR NOT COALESCE(package_version."manifestSnapshot"->'supportedIndustryTemplates' ? brand."templateKey", false)
|
||||
OR installation."templateKey" IS DISTINCT FROM brand."templateKey"
|
||||
OR (installation."contentChecksum" IS NOT NULL AND installation."contentChecksum" IS DISTINCT FROM package_version."contentChecksum")
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: installation, brand, package row, or manifest disagree';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandProfile" brand
|
||||
LEFT JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand."id"
|
||||
WHERE installation."id" IS NULL
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: a brand has no explicit template installation';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandProfile" brand
|
||||
JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand."id"
|
||||
JOIN "TemplatePackageVersion" package_version
|
||||
ON package_version."id" = installation."templatePackageVersionId"
|
||||
WHERE brand."config" ? 'visualTemplateKey'
|
||||
AND brand."config"->>'visualTemplateKey' IS DISTINCT FROM package_version."visualTemplateKey"
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: brand config visualTemplateKey conflicts with its installation';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandProfile" brand
|
||||
LEFT JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand."id"
|
||||
WHERE brand."config" ? 'visualTemplateKey'
|
||||
AND installation."id" IS NULL
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: brand config visualTemplateKey has no installation to verify against';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM "TemplatePackageVersion" package_version
|
||||
WHERE package_version."visualTemplateKey" IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'visualTemplateKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'packageKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'version' IS DISTINCT FROM package_version."version"
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: package metadata conflicts with its manifest';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
UPDATE "BrandTemplateInstallation" installation
|
||||
SET "templateVersion" = package_version."version",
|
||||
"contentChecksum" = package_version."contentChecksum"
|
||||
FROM "TemplatePackageVersion" package_version
|
||||
WHERE package_version."id" = installation."templatePackageVersionId";
|
||||
|
||||
UPDATE "BrandProfile"
|
||||
SET "config" = "config" - 'visualTemplateKey'
|
||||
WHERE "config" ? 'visualTemplateKey';
|
||||
|
||||
ALTER TABLE "BrandTemplateInstallation"
|
||||
DROP CONSTRAINT "BrandTemplateInstallation_templatePackageVersionId_fkey",
|
||||
DROP COLUMN "visualTemplateKey",
|
||||
ALTER COLUMN "templatePackageVersionId" SET NOT NULL,
|
||||
ADD CONSTRAINT "BrandTemplateInstallation_templatePackageVersionId_fkey"
|
||||
FOREIGN KEY ("templatePackageVersionId") REFERENCES "TemplatePackageVersion"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "TemplatePackageVersion" DROP COLUMN "visualTemplateKey";
|
||||
|
||||
DROP INDEX "BrandTemplateInstallation_brandId_templateKey_key";
|
||||
CREATE UNIQUE INDEX "BrandTemplateInstallation_brandId_key" ON "BrandTemplateInstallation"("brandId");
|
||||
@@ -223,22 +223,19 @@ model CapabilityAuditLog {
|
||||
}
|
||||
|
||||
model BrandTemplateInstallation {
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(uuid())
|
||||
brandId String @unique
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
templateKey String
|
||||
templateVersion String @default("1.0.0")
|
||||
visualTemplateKey String?
|
||||
templatePackageVersionId String?
|
||||
templatePackageVersion TemplatePackageVersion? @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: SetNull)
|
||||
templateVersion String @default("1.0.0")
|
||||
templatePackageVersionId String
|
||||
templatePackageVersion TemplatePackageVersion @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: Restrict)
|
||||
contentChecksum String?
|
||||
configSnapshot Json
|
||||
previousSnapshots Json @default("[]")
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
previousSnapshots Json @default("[]")
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([brandId, templateKey])
|
||||
@@index([brandId])
|
||||
@@index([templatePackageVersionId])
|
||||
}
|
||||
|
||||
@@ -484,7 +481,6 @@ model TemplatePackageVersion {
|
||||
packageKey String
|
||||
version String
|
||||
displayName String
|
||||
visualTemplateKey String?
|
||||
status TemplatePackageVersionStatus @default(imported)
|
||||
manifestSnapshot Json
|
||||
validationReport Json
|
||||
|
||||
+52
-41
@@ -1,10 +1,5 @@
|
||||
import { PrismaClient, type Prisma } from "@prisma/client";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
getVisualTemplateManifest,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
|
||||
|
||||
@@ -28,6 +23,7 @@ type OfferingKind = "service" | "product" | "package" | "subscription";
|
||||
|
||||
interface RuntimeSeedTemplate {
|
||||
templateKey: "personal" | "food" | "doors";
|
||||
visualTemplateKey: string;
|
||||
brandConfig: Record<string, unknown>;
|
||||
retiredOfferingNames?: string[];
|
||||
offerings: Array<{
|
||||
@@ -52,8 +48,8 @@ interface RuntimeSeedTemplate {
|
||||
const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = {
|
||||
personal: {
|
||||
templateKey: "personal",
|
||||
visualTemplateKey: "linjing-editorial",
|
||||
brandConfig: {
|
||||
visualTemplateKey: "linjing-editorial",
|
||||
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
|
||||
title: "品牌策略顾问",
|
||||
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
|
||||
@@ -166,8 +162,8 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
},
|
||||
food: {
|
||||
templateKey: "food",
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
brandConfig: {
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
founder: "阿成",
|
||||
title: "私房菜主理人",
|
||||
slogan: "认真做好每一顿家常饭。",
|
||||
@@ -293,9 +289,9 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
},
|
||||
doors: {
|
||||
templateKey: "doors",
|
||||
visualTemplateKey: "linjing-editorial",
|
||||
retiredOfferingNames: ["别墅入户大门", "院门与围合系统", "室内户内门系统"],
|
||||
brandConfig: {
|
||||
visualTemplateKey: "linjing-editorial",
|
||||
templateData: { designPhilosophy: "让门与空间建立长期、克制的关系" },
|
||||
founder: "林叙安 (Lin XUAN)",
|
||||
title: "高端门系统建筑研造主理人",
|
||||
@@ -645,11 +641,22 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise<void> {
|
||||
// 这里只初始化明确的开发演示品牌;业务内容统一来自视觉包 sampleContent,
|
||||
// 新增生产模板无需添加 seed 分支,品牌样例内容仍须由管理员显式导入。
|
||||
const visualKey = template.templateKey === "food" ? "acheng-campus-food" : "linjing-editorial";
|
||||
const packageSample =
|
||||
getTemplatePackageManifestForVisualKey(visualKey)?.sampleContent?.[template.templateKey];
|
||||
if (!packageSample)
|
||||
throw new Error(`Development sample is missing for ${visualKey}/${template.templateKey}`);
|
||||
const installation = await prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
const manifest = installation?.templatePackageVersion?.manifestSnapshot as unknown as
|
||||
TemplatePackageManifest | undefined;
|
||||
const packageSample = manifest?.sampleContent?.[template.templateKey];
|
||||
if (
|
||||
!installation?.templatePackageVersion ||
|
||||
manifest?.visualTemplateKey !== template.visualTemplateKey ||
|
||||
manifest.packageKey !== template.visualTemplateKey ||
|
||||
!packageSample
|
||||
)
|
||||
throw new Error(
|
||||
`Development package sample is missing for ${template.visualTemplateKey}/${template.templateKey}`,
|
||||
);
|
||||
const offerings = packageSample.offerings.map((item) => ({
|
||||
name: item.name,
|
||||
summary: item.summary,
|
||||
@@ -787,36 +794,40 @@ async function ensureSeedRelease(brandId: string, actorId: string): Promise<void
|
||||
async function ensureTemplateInstallation(brandId: string): Promise<void> {
|
||||
const brand = await prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true, config: true },
|
||||
select: { templateKey: true },
|
||||
});
|
||||
const template = runtimeSeedTemplates[brand.templateKey as keyof typeof runtimeSeedTemplates];
|
||||
if (!template) throw new Error("Development brand has no explicit template fixture");
|
||||
const visualKey = template.visualTemplateKey;
|
||||
const existing = await prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
const template = getBrandTemplate(brand.templateKey);
|
||||
if (!template) throw new Error("Development brand has an unknown industry template");
|
||||
const config =
|
||||
brand.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const configuredVisual =
|
||||
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined;
|
||||
const visualKey = configuredVisual ?? getDefaultVisualTemplateKey(template.key);
|
||||
if (!getVisualTemplateManifest(visualKey))
|
||||
throw new Error("Development brand has an unknown visual template");
|
||||
const configSnapshot = {
|
||||
schemaVersion: "1.0",
|
||||
version: template.version,
|
||||
industryTemplate: template,
|
||||
visualTemplate: getVisualTemplateManifest(visualKey),
|
||||
capabilities: template.capabilities,
|
||||
} as unknown as Prisma.InputJsonValue;
|
||||
const existing = await prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
|
||||
if (existing) {
|
||||
await prisma.brandTemplateInstallation.update({
|
||||
where: { id: existing.id },
|
||||
data: { templateKey: template.key, templateVersion: template.version, configSnapshot },
|
||||
});
|
||||
if (
|
||||
existing.templateKey !== template.templateKey ||
|
||||
!existing.templatePackageVersionId ||
|
||||
!existing.templatePackageVersion
|
||||
)
|
||||
throw new Error("Development brand installation does not satisfy the template contract");
|
||||
return;
|
||||
}
|
||||
const packageVersion = await prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: visualKey, status: "published" },
|
||||
orderBy: { importedAt: "desc" },
|
||||
});
|
||||
if (!packageVersion)
|
||||
throw new Error(`Development brand requires a published package version: ${visualKey}`);
|
||||
const configSnapshot = packageVersion.manifestSnapshot as Prisma.InputJsonValue;
|
||||
await prisma.brandTemplateInstallation.create({
|
||||
data: { brandId, templateKey: template.key, templateVersion: template.version, configSnapshot },
|
||||
data: {
|
||||
brandId,
|
||||
templateKey: template.templateKey,
|
||||
templateVersion: packageVersion.version,
|
||||
templatePackageVersionId: packageVersion.id,
|
||||
contentChecksum: packageVersion.contentChecksum,
|
||||
configSnapshot,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -846,8 +857,8 @@ async function main(): Promise<void> {
|
||||
},
|
||||
});
|
||||
|
||||
await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food);
|
||||
await ensureTemplateInstallation(brand.id);
|
||||
await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food);
|
||||
|
||||
for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) {
|
||||
await prisma.tag.upsert({
|
||||
@@ -904,8 +915,8 @@ async function main(): Promise<void> {
|
||||
update: { isEnabled: true, role: "owner" },
|
||||
create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" },
|
||||
});
|
||||
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
|
||||
await ensureTemplateInstallation(doorsBrand.id);
|
||||
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
|
||||
await ensureSeedRelease(brand.id, admin.id);
|
||||
await ensureSeedRelease(doorsBrand.id, admin.id);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
|
||||
import { PrismaService } from "../dist/prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../dist/template-workspace.service.js";
|
||||
|
||||
@@ -19,18 +20,12 @@ try {
|
||||
let current = await tx.brandProfile.findUnique({ where: { slug } });
|
||||
if (current) {
|
||||
assert.equal(current.templateKey, "personal", "Existing brand has a different industry");
|
||||
assert.equal(
|
||||
current.config?.visualTemplateKey,
|
||||
"atelier-solopreneur",
|
||||
"Existing brand has a different visual template",
|
||||
);
|
||||
} else {
|
||||
current = await tx.brandProfile.create({
|
||||
data: {
|
||||
slug,
|
||||
name: "独立工坊 · 品牌小程序",
|
||||
templateKey: "personal",
|
||||
config: { visualTemplateKey: "atelier-solopreneur" },
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -41,8 +36,31 @@ try {
|
||||
});
|
||||
return current;
|
||||
});
|
||||
if (!(await prisma.brandTemplateInstallation.findFirst({ where: { brandId: brand.id } }))) {
|
||||
await new TemplateWorkspaceService(prisma).install(brand.id, "personal");
|
||||
const manifest = getTemplatePackageManifestForVisualKey("atelier-solopreneur");
|
||||
if (!manifest) throw new Error("atelier-solopreneur package manifest is unavailable");
|
||||
const version = await prisma.templatePackageVersion.findUnique({
|
||||
where: {
|
||||
templatePackageId_version: {
|
||||
templatePackageId: (
|
||||
await prisma.templatePackage.findUniqueOrThrow({
|
||||
where: { packageKey: "atelier-solopreneur" },
|
||||
select: { id: true },
|
||||
})
|
||||
).id,
|
||||
version: manifest.version,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!version || version.status !== "published")
|
||||
throw new Error(`Published package version not found: atelier-solopreneur@${manifest.version}`);
|
||||
const installation = await prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId: brand.id },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
if (installation) {
|
||||
assert.equal(installation.templatePackageVersionId, version.id);
|
||||
} else {
|
||||
await new TemplateWorkspaceService(prisma).install(brand.id, "personal", version.id);
|
||||
}
|
||||
assert.deepEqual(
|
||||
await prisma.brandProfile.findMany({ where: { slug: { not: slug } }, orderBy: { id: "asc" } }),
|
||||
|
||||
@@ -10,8 +10,14 @@ const prisma = new PrismaClient();
|
||||
const note = "餐饮主理人原型视觉槽位迁移 v1";
|
||||
try {
|
||||
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { slug: "default-brand" } });
|
||||
const config = (brand.config ?? {}) as Record<string, unknown>;
|
||||
if (brand.templateKey !== "food" || config.visualTemplateKey !== "acheng-campus-food")
|
||||
const installation = await prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId: brand.id },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
if (
|
||||
brand.templateKey !== "food" ||
|
||||
installation?.templatePackageVersion?.packageKey !== "acheng-campus-food"
|
||||
)
|
||||
throw new Error("Migration is restricted to the development food brand");
|
||||
const previous = await prisma.brandRelease.findFirst({
|
||||
where: { brandId: brand.id },
|
||||
|
||||
@@ -106,7 +106,13 @@ export class UpdateBookingTagsDto {
|
||||
export class InstallTemplateDto {
|
||||
@IsIn(brandTemplateKeys)
|
||||
templateKey!: BrandTemplateKey;
|
||||
@IsOptional() @IsUUID() templatePackageVersionId?: string;
|
||||
@IsUUID() templatePackageVersionId!: string;
|
||||
}
|
||||
|
||||
export class SelectTemplateVersionDto {
|
||||
@IsUUID() templatePackageVersionId!: string;
|
||||
@IsOptional() @IsUUID() expectedCurrentPackageVersionId?: string | null;
|
||||
@IsBoolean() confirm!: boolean;
|
||||
}
|
||||
|
||||
export class UpgradeTemplateDto {
|
||||
|
||||
@@ -6,12 +6,9 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
validateTemplatePackageManifest,
|
||||
type TemplatePackageManifest,
|
||||
} from "@personal-brand/config";
|
||||
@@ -61,9 +58,8 @@ export class BrandReleaseApiService {
|
||||
where: { id: brandId },
|
||||
select: { name: true, tagline: true, description: true, templateKey: true, config: true },
|
||||
});
|
||||
const installation = await database.brandTemplateInstallation.findFirst({
|
||||
const installation = await database.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
const packageVersion = installation?.templatePackageVersionId
|
||||
? await database.templatePackageVersion.findUnique({
|
||||
@@ -71,36 +67,30 @@ export class BrandReleaseApiService {
|
||||
select: {
|
||||
packageKey: true,
|
||||
version: true,
|
||||
visualTemplateKey: true,
|
||||
status: true,
|
||||
contentChecksum: true,
|
||||
manifestSnapshot: true,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? "");
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
const template = getBrandTemplate(brand?.templateKey ?? "");
|
||||
const storedManifest = packageVersion?.manifestSnapshot as TemplatePackageManifest | undefined;
|
||||
const visualKey = storedManifest?.visualTemplateKey ?? "";
|
||||
const visual = getVisualTemplate(visualKey);
|
||||
const storedManifest = packageVersion?.manifestSnapshot as unknown as
|
||||
TemplatePackageManifest | undefined;
|
||||
const packageManifest = storedManifest ?? getTemplatePackageManifestForVisualKey(visualKey);
|
||||
const packageVersionValid =
|
||||
!installation?.templatePackageVersionId ||
|
||||
Boolean(
|
||||
packageVersion &&
|
||||
packageVersion.status === "published" &&
|
||||
/^[a-f0-9]{64}$/.test(packageVersion.contentChecksum) &&
|
||||
packageVersion.packageKey === (storedManifest?.packageKey ?? "") &&
|
||||
packageVersion.version === (storedManifest?.version ?? "") &&
|
||||
(packageVersion.visualTemplateKey ?? packageVersion.packageKey) ===
|
||||
(storedManifest?.visualTemplateKey ?? packageVersion.packageKey) &&
|
||||
storedManifest?.supportedIndustryTemplates.includes(brand?.templateKey ?? "") &&
|
||||
validateTemplatePackageManifest(storedManifest).length === 0,
|
||||
);
|
||||
const packageManifest = storedManifest;
|
||||
const packageVersionValid = Boolean(
|
||||
installation?.templatePackageVersionId &&
|
||||
packageVersion &&
|
||||
packageVersion.status === "published" &&
|
||||
/^[a-f0-9]{64}$/.test(packageVersion.contentChecksum) &&
|
||||
packageVersion.packageKey === (storedManifest?.packageKey ?? "") &&
|
||||
packageVersion.version === (storedManifest?.version ?? "") &&
|
||||
packageVersion.packageKey === storedManifest?.packageKey &&
|
||||
packageVersion.packageKey === storedManifest?.visualTemplateKey &&
|
||||
storedManifest?.supportedIndustryTemplates.includes(brand?.templateKey ?? "") &&
|
||||
validateTemplatePackageManifest(storedManifest).length === 0,
|
||||
);
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const [offerings, forms, trustItems] = await Promise.all([
|
||||
database.offering.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
@@ -35,9 +32,8 @@ export async function buildBrandReleaseSnapshot(
|
||||
const [brand, installation, fields, offerings, forms, trustContents, capabilities] =
|
||||
await Promise.all([
|
||||
database.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
database.brandTemplateInstallation.findFirst({
|
||||
database.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
include: { templatePackageVersion: true },
|
||||
}),
|
||||
database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
@@ -46,15 +42,14 @@ export async function buildBrandReleaseSnapshot(
|
||||
database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
database.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const templateKey = brand?.templateKey ?? installation?.templateKey ?? defaultBrandTemplateKey;
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
if (!brand) throw new Error("品牌不存在,不能生成发布快照");
|
||||
if (!installation?.templatePackageVersion) throw new Error("品牌安装没有锁定精确视觉模板包版本");
|
||||
const templateKey = brand.templateKey;
|
||||
const packageManifest = installation.templatePackageVersion.manifestSnapshot as unknown as
|
||||
TemplatePackageManifest | undefined;
|
||||
const visualKey = packageManifest?.visualTemplateKey;
|
||||
if (!packageManifest || typeof visualKey !== "string")
|
||||
throw new Error("品牌安装与模板包 manifest 不一致");
|
||||
const jsonObject = (value: object): Record<string, unknown> =>
|
||||
JSON.parse(JSON.stringify(value)) as Record<string, unknown>;
|
||||
return {
|
||||
@@ -64,11 +59,7 @@ export async function buildBrandReleaseSnapshot(
|
||||
templateDefinition: getBrandTemplate(templateKey) ?? null,
|
||||
visualTemplateDefinition: getVisualTemplate(visualKey) ?? null,
|
||||
visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null,
|
||||
templatePackageManifest:
|
||||
(installation?.templatePackageVersion?.manifestSnapshot as unknown as
|
||||
TemplatePackageManifest | undefined) ??
|
||||
getTemplatePackageManifestForVisualKey(visualKey) ??
|
||||
null,
|
||||
templatePackageManifest: packageManifest,
|
||||
brand: brand ? jsonObject(brand) : null,
|
||||
installation: installation ? jsonObject(installation) : null,
|
||||
fields: fields.map((item) => jsonObject(item)),
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
defaultVisualTemplateKey,
|
||||
getBrandTemplate,
|
||||
getDefaultVisualTemplateKey,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
listVisualTemplateKeys,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import type { UpdateBrandDto, UpdateBrandPresentationDto } from "../../admin.dto.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminBrandConfigService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
) {}
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
getBrand(brandId: string) {
|
||||
return this.prisma.brandProfile.findUnique({ where: { id: brandId } });
|
||||
@@ -27,56 +15,28 @@ export class AdminBrandConfigService {
|
||||
const { config, ...fields } = body;
|
||||
const current = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
select: { config: true, templateKey: true },
|
||||
});
|
||||
if (!current) throw new BadRequestException("品牌不存在");
|
||||
const currentConfig = this.jsonObject(current?.config);
|
||||
if (config && Object.hasOwn(config, "visualTemplateKey"))
|
||||
throw new BadRequestException("模板选择必须通过精确模板包版本操作");
|
||||
const configFields = config ?? {};
|
||||
const nextConfig = {
|
||||
...currentConfig,
|
||||
...(config ?? {}),
|
||||
...(fields.description !== undefined && config?.slogan === undefined
|
||||
...configFields,
|
||||
...(fields.description !== undefined && configFields.slogan === undefined
|
||||
? { slogan: fields.description }
|
||||
: {}),
|
||||
};
|
||||
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const visualTemplate =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? getVisualTemplate(config.visualTemplateKey)
|
||||
: undefined;
|
||||
if (
|
||||
!visualTemplate ||
|
||||
!getBrandTemplate(templateKey) ||
|
||||
!isVisualTemplateCompatible(visualTemplate, templateKey)
|
||||
)
|
||||
throw new BadRequestException("当前视觉模板不适配该行业模板");
|
||||
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
return tx.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
...fields,
|
||||
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
|
||||
},
|
||||
});
|
||||
if (installation) {
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
await this.prisma.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
data: {
|
||||
previousSnapshots: [
|
||||
...history,
|
||||
{
|
||||
visualTemplateKey:
|
||||
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
|
||||
savedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return this.prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
...fields,
|
||||
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -130,91 +90,6 @@ export class AdminBrandConfigService {
|
||||
};
|
||||
}
|
||||
|
||||
async visualTemplateHistory(brandId: string) {
|
||||
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
select: { previousSnapshots: true },
|
||||
});
|
||||
return {
|
||||
history: Array.isArray(installation?.previousSnapshots)
|
||||
? installation.previousSnapshots.filter(
|
||||
(item) =>
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
!Array.isArray(item) &&
|
||||
"visualTemplateKey" in item,
|
||||
)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
async rollbackVisualTemplate(brandId: string) {
|
||||
const [brand, installation] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
]);
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const history = Array.isArray(installation?.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
const index = [...history]
|
||||
.map((item, i) => ({ item, i }))
|
||||
.reverse()
|
||||
.find(
|
||||
({ item }) =>
|
||||
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
|
||||
)?.i;
|
||||
const previous =
|
||||
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
|
||||
if (!previous || typeof previous.visualTemplateKey !== "string")
|
||||
throw new BadRequestException("没有可回滚的视觉模板版本");
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
config: {
|
||||
...config,
|
||||
visualTemplateKey: previous.visualTemplateKey,
|
||||
},
|
||||
},
|
||||
}),
|
||||
...(installation
|
||||
? [
|
||||
this.prisma.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
data: { previousSnapshots: history.slice(0, index) },
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
|
||||
}
|
||||
|
||||
async visualTemplatePreview(brandId: string) {
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
});
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const currentKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: defaultVisualTemplateKey;
|
||||
const current = getVisualTemplate(currentKey);
|
||||
return {
|
||||
current: current
|
||||
? {
|
||||
key: current.key,
|
||||
version: current.version,
|
||||
name: current.name,
|
||||
theme: current.theme,
|
||||
variants: current.variants,
|
||||
}
|
||||
: null,
|
||||
available: listVisualTemplateKeys(),
|
||||
};
|
||||
}
|
||||
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
|
||||
@@ -60,10 +60,6 @@ export class AdminConfigController {
|
||||
@Body() body: UpdateBrandDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config } = body;
|
||||
if (config?.visualTemplateKey !== undefined) {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
}
|
||||
return this.brandConfig.updateBrand(this.brandId(request), body);
|
||||
}
|
||||
@Patch("presentation")
|
||||
@@ -75,21 +71,6 @@ export class AdminConfigController {
|
||||
const brandId = this.brandId(request);
|
||||
return this.brandConfig.updatePresentation(brandId, body);
|
||||
}
|
||||
@Get("visual-template/history")
|
||||
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
return this.brandConfig.visualTemplateHistory(this.brandId(request));
|
||||
}
|
||||
@Post("visual-template/rollback")
|
||||
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.brandConfig.rollbackVisualTemplate(this.brandId(request));
|
||||
}
|
||||
@Get("visual-template/preview")
|
||||
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
return this.brandConfig.visualTemplatePreview(this.brandId(request));
|
||||
}
|
||||
@Get("trust-content")
|
||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
|
||||
@@ -26,9 +26,9 @@ type Manifest = {
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
visualTemplateKey?: string;
|
||||
supportedIndustryTemplates?: string[];
|
||||
previewFixture?: Prisma.InputJsonValue;
|
||||
visualTemplateKey: string;
|
||||
supportedIndustryTemplates: string[];
|
||||
previewFixture: Prisma.InputJsonValue;
|
||||
};
|
||||
|
||||
type ChecksumFile = {
|
||||
@@ -146,7 +146,6 @@ export class AdminTemplatePackageService {
|
||||
packageKey: true,
|
||||
version: true,
|
||||
displayName: true,
|
||||
visualTemplateKey: true,
|
||||
status: true,
|
||||
contentChecksum: true,
|
||||
archiveChecksum: true,
|
||||
@@ -302,7 +301,6 @@ export class AdminTemplatePackageService {
|
||||
packageKey,
|
||||
version: manifest.version,
|
||||
displayName: manifest.displayName,
|
||||
visualTemplateKey: manifest.visualTemplateKey ?? null,
|
||||
manifestSnapshot: manifest,
|
||||
validationReport: {
|
||||
formatVersion: "1",
|
||||
@@ -495,7 +493,6 @@ export class AdminTemplatePackageService {
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
visualTemplateKey: string | null;
|
||||
status: string;
|
||||
contentChecksum: string;
|
||||
archiveChecksum: string;
|
||||
@@ -506,7 +503,6 @@ export class AdminTemplatePackageService {
|
||||
packageKey: version.packageKey,
|
||||
version: version.version,
|
||||
displayName: version.displayName,
|
||||
visualTemplateKey: version.visualTemplateKey,
|
||||
status: version.status,
|
||||
contentChecksum: version.contentChecksum,
|
||||
archiveChecksum: version.archiveChecksum,
|
||||
|
||||
@@ -184,22 +184,25 @@ export class AdminTemplatePreviewService {
|
||||
|
||||
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;
|
||||
const visualTemplateKey = rawManifest.visualTemplateKey as string;
|
||||
const manifest = rawManifest as unknown as TemplatePackageManifest;
|
||||
let manifestIssues: string[];
|
||||
try {
|
||||
if (validateTemplatePackageManifest(manifest).length || !hasPreviewStructure(rawManifest)) {
|
||||
throw new Error("Invalid manifest");
|
||||
}
|
||||
manifestIssues = validateTemplatePackageManifest(manifest);
|
||||
} catch {
|
||||
throw new BadRequestException("模板版本的 manifest 不符合预览契约");
|
||||
}
|
||||
if (manifest.packageKey !== packageKey || manifest.version !== version.version)
|
||||
if (manifestIssues.length)
|
||||
throw new BadRequestException(
|
||||
`模板版本的 manifest 不符合预览契约:${manifestIssues.join(";")}`,
|
||||
);
|
||||
if (!hasPreviewStructure(rawManifest))
|
||||
throw new BadRequestException("模板版本的 manifest 不符合预览契约");
|
||||
if (
|
||||
manifest.packageKey !== packageKey ||
|
||||
manifest.version !== version.version ||
|
||||
manifest.packageKey !== manifest.visualTemplateKey
|
||||
)
|
||||
throw new BadRequestException("模板版本与 manifest 元数据不一致");
|
||||
const industryTemplate = getBrandTemplate(industry);
|
||||
const blockers: string[] = [];
|
||||
@@ -235,20 +238,14 @@ export class AdminTemplatePreviewService {
|
||||
}
|
||||
if (blockers.length) throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
|
||||
|
||||
const fixtureDeclared = rawManifest.previewFixture !== undefined;
|
||||
const fixture = record(rawManifest.previewFixture)[industry] as
|
||||
TemplatePreviewFixture | undefined;
|
||||
if (fixtureDeclared) {
|
||||
const issues = validateTemplatePreviewFixture(fixture);
|
||||
if (issues.length)
|
||||
throw new BadRequestException(
|
||||
`模板 previewFixture 不符合预览契约:${issues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
|
||||
);
|
||||
}
|
||||
// 一旦包声明独立 fixture,缺失或无效时禁止偷偷回退到 bootstrap sample。
|
||||
const sample = fixtureDeclared
|
||||
? fixture!.content
|
||||
: (record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined);
|
||||
const fixtureIssues = validateTemplatePreviewFixture(fixture);
|
||||
if (fixtureIssues.length)
|
||||
throw new BadRequestException(
|
||||
`模板 previewFixture 不符合预览契约:${fixtureIssues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
|
||||
);
|
||||
const sample = fixture!.content as TemplateSampleContent;
|
||||
const missingSampleSlots = this.missingSampleSlots(manifest, sample);
|
||||
if (missingSampleSlots.length)
|
||||
blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`);
|
||||
@@ -331,26 +328,13 @@ export class AdminTemplatePreviewService {
|
||||
},
|
||||
preview: {
|
||||
assetFiles: resources.files,
|
||||
fixtureSource: fixtureDeclared
|
||||
? ("previewFixture" as const)
|
||||
: ("legacy-sampleContent" as const),
|
||||
fixtureSource: "previewFixture" as const,
|
||||
safety: {
|
||||
submissions: "disabled" as const,
|
||||
customerRecords: "disabled" as const,
|
||||
contactActions: "disabled" as const,
|
||||
},
|
||||
diagnostics: [
|
||||
...resources.diagnostics,
|
||||
...(fixtureDeclared
|
||||
? []
|
||||
: [
|
||||
{
|
||||
code: "LEGACY_PREVIEW_SAMPLE",
|
||||
severity: "warning" as const,
|
||||
message: "该版本尚未提供独立预览数据,当前兼容使用品牌起始内容。",
|
||||
},
|
||||
]),
|
||||
],
|
||||
diagnostics: resources.diagnostics,
|
||||
pages: Object.keys(manifest.entrypoints).map((page) => ({
|
||||
key: page,
|
||||
modules: manifest.admin.sections
|
||||
@@ -463,7 +447,7 @@ export class AdminTemplatePreviewService {
|
||||
deliveryNote: identity?.deliveryNote ?? "预览模式不会提交咨询或创建客户记录。",
|
||||
contactPhone: null,
|
||||
contactWechat: null,
|
||||
config: { ...brandConfig, visualTemplateKey },
|
||||
config: brandConfig,
|
||||
};
|
||||
const snapshot: BrandReleaseSnapshot = {
|
||||
schemaVersion: "1.0.0",
|
||||
@@ -477,6 +461,7 @@ export class AdminTemplatePreviewService {
|
||||
installation: {
|
||||
templateKey: industryTemplate.key,
|
||||
templateVersion: industryTemplate.version,
|
||||
visualTemplateKey,
|
||||
},
|
||||
fields: [],
|
||||
offerings: sample.offerings.map((item, sortOrder) => ({
|
||||
|
||||
@@ -3,13 +3,7 @@ import type { Prisma } from "@prisma/client";
|
||||
import {
|
||||
capabilityMetadata,
|
||||
capabilityPlugins,
|
||||
defaultBrandTemplateKey,
|
||||
type BrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
resolveCapabilities,
|
||||
} from "@personal-brand/config";
|
||||
import type { RuntimeTrustItem, RuntimeWorkspace } from "@personal-brand/types";
|
||||
@@ -94,12 +88,8 @@ export function assemblePublicWorkspace(input: {
|
||||
(item) => asRecord(item).isPublished === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const installationData = asRecord(releaseSnapshot.installation);
|
||||
const templateKey =
|
||||
asString(brandData.templateKey) ||
|
||||
asString(releaseSnapshot.templateKey) ||
|
||||
asString(installationData.templateKey) ||
|
||||
defaultBrandTemplateKey;
|
||||
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
|
||||
const templateKey = asString(releaseSnapshot.templateKey);
|
||||
const template = releaseSnapshot.templateDefinition;
|
||||
const capabilityData = asArray(releaseSnapshot.capabilities) as Array<Record<string, unknown>>;
|
||||
const capabilityRecord = (item: Record<string, unknown>, fallbackVersion = "1.0.0") => {
|
||||
const key = asString(item.capabilityKey) || asString(item.key);
|
||||
@@ -120,15 +110,19 @@ export function assemblePublicWorkspace(input: {
|
||||
)
|
||||
: [];
|
||||
const brandConfig = asRecord(brandData.config);
|
||||
const visualTemplateKey =
|
||||
asString(brandConfig.visualTemplateKey) || getDefaultVisualTemplateKey(templateKey);
|
||||
const visualTemplate =
|
||||
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
||||
const visualTemplateManifest =
|
||||
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
||||
const templatePackageManifest =
|
||||
releaseSnapshot.templatePackageManifest ??
|
||||
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
||||
const visualTemplate = releaseSnapshot.visualTemplateDefinition;
|
||||
const visualTemplateManifest = releaseSnapshot.visualTemplateManifest;
|
||||
const templatePackageManifest = releaseSnapshot.templatePackageManifest;
|
||||
const visualTemplateKey = asString(templatePackageManifest?.visualTemplateKey);
|
||||
if (
|
||||
!templateKey ||
|
||||
!visualTemplateKey ||
|
||||
!templatePackageManifest ||
|
||||
!template ||
|
||||
!visualTemplate ||
|
||||
!visualTemplateManifest
|
||||
)
|
||||
throw new Error("发布快照缺少统一模板契约字段");
|
||||
const categoryOptions = new Map(
|
||||
(templatePackageManifest?.admin.sections ?? [])
|
||||
.filter((section) => section.target === "offering")
|
||||
@@ -192,10 +186,8 @@ export function assemblePublicWorkspace(input: {
|
||||
status: "enabled" as const,
|
||||
config: capabilities.find((capability) => capability.key === plugin.key)?.config ?? {},
|
||||
})),
|
||||
theme: visualTemplate?.theme ?? {
|
||||
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
|
||||
},
|
||||
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
|
||||
theme: visualTemplate.theme,
|
||||
...(visualTemplate.layout ? { layout: visualTemplate.layout } : {}),
|
||||
};
|
||||
return {
|
||||
...runtimeWorkspace,
|
||||
|
||||
@@ -2,8 +2,6 @@ import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/comm
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
defaultVisualTemplateKey,
|
||||
brandTemplateKeys,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
@@ -82,10 +80,7 @@ export class PublicTemplateController {
|
||||
}
|
||||
|
||||
@Get("preview")
|
||||
preview(
|
||||
@Query("industry") industry = defaultBrandTemplateKey,
|
||||
@Query("visual") visual = defaultVisualTemplateKey,
|
||||
): unknown {
|
||||
preview(@Query("industry") industry: string, @Query("visual") visual: string): unknown {
|
||||
const industryTemplate = getBrandTemplate(industry);
|
||||
const visualTemplate = getVisualTemplate(visual);
|
||||
if (!industryTemplate || !visualTemplate) throw new BadRequestException("模板组合不存在");
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma, type TemplatePackageVersion } from "@prisma/client";
|
||||
import {
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
getTemplateSampleContent,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
validateTemplatePackageManifest,
|
||||
@@ -15,10 +12,10 @@ import { PrismaService } from "../../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
|
||||
type BootstrapSource = {
|
||||
kind: "package_version" | "registry";
|
||||
kind: "package_version";
|
||||
manifest: TemplatePackageManifest;
|
||||
sample: TemplateSampleContent;
|
||||
version?: TemplatePackageVersion;
|
||||
version: TemplatePackageVersion;
|
||||
};
|
||||
|
||||
type Counts = {
|
||||
@@ -111,8 +108,6 @@ export class AdminSampleContentService {
|
||||
throw new BadRequestException("当前只支持 missing_only 导入策略");
|
||||
|
||||
const { brand, source } = await this.resolveSource(brandId, body.templatePackageVersionId);
|
||||
if (!source.version)
|
||||
throw new BadRequestException("品牌尚未安装可追溯的已发布模板包版本,不能导入示例内容");
|
||||
const plan = await this.buildPlan(brandId, brand.config, source);
|
||||
const priorImport = await this.prisma.templateBootstrapImport.findFirst({
|
||||
where: {
|
||||
@@ -263,50 +258,35 @@ export class AdminSampleContentService {
|
||||
select: { templateKey: true, config: true },
|
||||
});
|
||||
if (!brand) throw new NotFoundException("品牌不存在");
|
||||
const config = record(brand.config);
|
||||
const visualTemplateKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand.templateKey);
|
||||
const installation = requestedVersionId
|
||||
? null
|
||||
: await this.prisma.brandTemplateInstallation.findFirst({
|
||||
: await this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { templatePackageVersionId: true },
|
||||
});
|
||||
const versionId = requestedVersionId ?? installation?.templatePackageVersionId ?? undefined;
|
||||
let source: BootstrapSource;
|
||||
if (versionId) {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: versionId },
|
||||
});
|
||||
if (!version) throw new BadRequestException("指定的模板包版本不存在");
|
||||
if (version.status !== "published")
|
||||
throw new BadRequestException("只有已发布的模板包版本可用于 bootstrap");
|
||||
const manifest = version.manifestSnapshot as unknown as TemplatePackageManifest;
|
||||
const issues = validateTemplatePackageManifest(manifest);
|
||||
if (issues.length)
|
||||
throw new BadRequestException(`模板包 manifest 无效:${issues.join(";")}`);
|
||||
if (
|
||||
manifest.packageKey !== version.packageKey ||
|
||||
manifest.version !== version.version ||
|
||||
!/^[a-f0-9]{64}$/.test(version.contentChecksum) ||
|
||||
(version.visualTemplateKey ?? version.packageKey) !==
|
||||
(manifest.visualTemplateKey ?? version.packageKey) ||
|
||||
!manifest.supportedIndustryTemplates.includes(brand.templateKey)
|
||||
)
|
||||
throw new BadRequestException("模板包版本与品牌行业或版本台账不匹配");
|
||||
const sample = manifest.sampleContent?.[brand.templateKey];
|
||||
if (!sample) throw new BadRequestException("该模板包没有当前行业的 bootstrap sampleContent");
|
||||
source = { kind: "package_version", version, manifest, sample };
|
||||
} else {
|
||||
const manifest = getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
||||
const sample = getTemplateSampleContent(brand.templateKey, visualTemplateKey);
|
||||
if (!manifest || !sample || requestedVersionId)
|
||||
throw new BadRequestException("当前模板没有可用的 bootstrap sampleContent");
|
||||
source = { kind: "registry", manifest, sample };
|
||||
}
|
||||
if (!versionId) throw new BadRequestException("品牌没有精确模板包安装版本,必须先完成模板安装");
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: versionId },
|
||||
});
|
||||
if (!version) throw new BadRequestException("指定的模板包版本不存在");
|
||||
if (version.status !== "published")
|
||||
throw new BadRequestException("只有已发布的模板包版本可用于 bootstrap");
|
||||
const manifest = version.manifestSnapshot as unknown as TemplatePackageManifest;
|
||||
const issues = validateTemplatePackageManifest(manifest);
|
||||
if (issues.length) throw new BadRequestException(`模板包 manifest 无效:${issues.join(";")}`);
|
||||
if (
|
||||
manifest.packageKey !== version.packageKey ||
|
||||
manifest.version !== version.version ||
|
||||
manifest.packageKey !== manifest.visualTemplateKey ||
|
||||
!/^[a-f0-9]{64}$/.test(version.contentChecksum) ||
|
||||
!manifest.supportedIndustryTemplates.includes(brand.templateKey)
|
||||
)
|
||||
throw new BadRequestException("模板包版本与品牌行业或版本台账不匹配");
|
||||
const sample = manifest.sampleContent?.[brand.templateKey];
|
||||
if (!sample) throw new BadRequestException("该模板包没有当前行业的 bootstrap sampleContent");
|
||||
const source: BootstrapSource = { kind: "package_version", version, manifest, sample };
|
||||
const visualTemplateKey = manifest.visualTemplateKey;
|
||||
const visual = getVisualTemplate(visualTemplateKey);
|
||||
if (!visual || !isVisualTemplateCompatible(visual, brand.templateKey))
|
||||
throw new BadRequestException("当前视觉模板与品牌行业不兼容");
|
||||
@@ -417,8 +397,8 @@ export class AdminSampleContentService {
|
||||
kind: source.kind,
|
||||
packageKey: source.manifest.packageKey,
|
||||
version: source.manifest.version,
|
||||
contentChecksum: source.version?.contentChecksum ?? null,
|
||||
...(source.version ? { templatePackageVersionId: source.version.id } : {}),
|
||||
contentChecksum: source.version.contentChecksum,
|
||||
templatePackageVersionId: source.version.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { InstallTemplateDto } from "../../admin.dto.js";
|
||||
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "./admin-access.identity.js";
|
||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
@@ -52,6 +52,21 @@ class AdminWorkspacePreviewController {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@Post("template/select-version")
|
||||
async selectVersion(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: SelectTemplateVersionDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
return this.templateWorkspace.selectVersion(
|
||||
identity.brandId,
|
||||
body,
|
||||
identity.subject,
|
||||
requestId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export { AdminWorkspacePreviewController };
|
||||
@@ -1,10 +1,5 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import { PublicWorkspaceService } from "../public/public-workspace.service.js";
|
||||
|
||||
@Injectable()
|
||||
@@ -15,11 +10,11 @@ export class AdminWorkspaceService {
|
||||
) {}
|
||||
|
||||
async get(brandId: string): Promise<unknown> {
|
||||
const [brand, installations, fields, offerings, forms] = await Promise.all([
|
||||
const [brand, installation, fields, offerings, forms] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
this.prisma.brandTemplateInstallation.findMany({
|
||||
this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
include: { templatePackageVersion: true },
|
||||
}),
|
||||
this.prisma.brandFieldDefinition.findMany({
|
||||
where: { brandId },
|
||||
@@ -28,36 +23,50 @@ export class AdminWorkspaceService {
|
||||
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
|
||||
]);
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const templateKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
const manifest = getTemplatePackageManifestForVisualKey(templateKey);
|
||||
if (!installation?.templatePackageVersion)
|
||||
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
||||
const manifest = installation.templatePackageVersion.manifestSnapshot as {
|
||||
visualTemplateKey: string;
|
||||
displayName: string;
|
||||
admin: unknown;
|
||||
navigation: Array<{ key: string; label: string; page: string }>;
|
||||
templateFields?: Array<Record<string, unknown> & { key: string; binding?: string }>;
|
||||
assetSlots: unknown[];
|
||||
trustContentTypes?: unknown[];
|
||||
};
|
||||
|
||||
return {
|
||||
brand,
|
||||
installations,
|
||||
installations: [
|
||||
{
|
||||
...installation,
|
||||
visualTemplateKey: manifest.visualTemplateKey,
|
||||
},
|
||||
],
|
||||
fields,
|
||||
offerings,
|
||||
forms,
|
||||
templateContent: manifest
|
||||
? {
|
||||
displayName: manifest.displayName,
|
||||
admin: manifest.admin,
|
||||
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
|
||||
templateFields: (manifest.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
})),
|
||||
assetSlots: manifest.assetSlots,
|
||||
trustContentTypes: manifest.trustContentTypes ?? [],
|
||||
}
|
||||
: null,
|
||||
templateContent: {
|
||||
displayName: manifest.displayName,
|
||||
admin: manifest.admin,
|
||||
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
|
||||
templateFields: (manifest.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
})),
|
||||
assetSlots: manifest.assetSlots,
|
||||
trustContentTypes: manifest.trustContentTypes ?? [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
getPreview(brandId: string): Promise<unknown> {
|
||||
async getPreview(brandId: string): Promise<unknown> {
|
||||
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
select: { templatePackageVersionId: true },
|
||||
});
|
||||
if (!installation?.templatePackageVersionId)
|
||||
throw new BadRequestException("品牌没有锁定精确模板包版本");
|
||||
return this.publicWorkspace.getForBrandId(brandId, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,45 +1,35 @@
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
import type { TemplatePackageVersion } from "@prisma/client";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
type BrandTemplateKey,
|
||||
defaultBrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
isVisualTemplateCompatible,
|
||||
validateTemplatePackageManifest,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
|
||||
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
@Injectable()
|
||||
export class TemplateWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
async getTrustContentTypes(brandId: string): Promise<string[]> {
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true, config: true },
|
||||
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
return (
|
||||
getTemplatePackageManifestForVisualKey(visualKey)?.trustContentTypes?.map(
|
||||
(item) => item.type,
|
||||
) ?? []
|
||||
);
|
||||
if (!installation?.templatePackageVersion)
|
||||
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
||||
const manifest = record(
|
||||
installation.templatePackageVersion.manifestSnapshot,
|
||||
) as unknown as TemplatePackageManifest;
|
||||
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
|
||||
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
|
||||
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
|
||||
}
|
||||
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
|
||||
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||
@@ -87,28 +77,25 @@ export class TemplateWorkspaceService {
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
this.prisma.brandTemplateInstallation.findFirst({
|
||||
this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
]);
|
||||
// BrandProfile.templateKey 是「品牌使用哪个行业模板」的唯一真相;
|
||||
// 安装记录只是同一模板的版本台账,缺失时不能反过来改写品牌身份。
|
||||
for (const candidate of [brand?.templateKey, installation?.templateKey]) {
|
||||
const template = candidate ? getBrandTemplate(candidate) : undefined;
|
||||
if (template) return template.key;
|
||||
}
|
||||
return defaultBrandTemplateKey;
|
||||
const template = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined;
|
||||
if (!template) throw new BadRequestException("品牌没有有效的行业模型声明");
|
||||
if (installation && installation.templateKey !== template.key)
|
||||
throw new BadRequestException("品牌行业模型与模板安装不一致,请修复安装数据");
|
||||
return template.key;
|
||||
}
|
||||
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId?: string) {
|
||||
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId: string) {
|
||||
const template = getBrandTemplate(templateKey);
|
||||
if (!template) throw new BadRequestException("行业模板不存在");
|
||||
const [existing, brand] = await Promise.all([
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
this.prisma.brandTemplateInstallation.findUnique({ where: { brandId } }),
|
||||
this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true, templateKey: true },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
]);
|
||||
// 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账,
|
||||
@@ -118,20 +105,13 @@ export class TemplateWorkspaceService {
|
||||
throw new BadRequestException(
|
||||
`当前品牌已在使用「${currentTemplate.name}」行业模板,更换行业模板不在本版本范围内`,
|
||||
);
|
||||
if (existing && existing.templateKey === templateKey)
|
||||
throw new BadRequestException("该模板已经安装");
|
||||
const brandConfig =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const configuredVisualTemplateKey =
|
||||
typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey : undefined;
|
||||
const visualTemplateKey =
|
||||
configuredVisualTemplateKey &&
|
||||
getVisualTemplate(configuredVisualTemplateKey) &&
|
||||
isVisualTemplateCompatible(getVisualTemplate(configuredVisualTemplateKey)!, templateKey)
|
||||
? configuredVisualTemplateKey
|
||||
: getDefaultVisualTemplateKey(templateKey);
|
||||
if (existing) throw new BadRequestException("品牌已经安装模板包,请使用明确的升级流程");
|
||||
const packageVersion = await this.resolveInstallablePackageVersion(
|
||||
templateKey,
|
||||
templatePackageVersionId,
|
||||
);
|
||||
const packageManifest = packageVersion.manifestSnapshot as unknown as TemplatePackageManifest;
|
||||
const visualTemplateKey = packageManifest.visualTemplateKey;
|
||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||
const visualTemplate = getVisualTemplate(visualTemplateKey);
|
||||
if (
|
||||
@@ -140,39 +120,19 @@ export class TemplateWorkspaceService {
|
||||
!isVisualTemplateCompatible(visualTemplate, templateKey)
|
||||
)
|
||||
throw new BadRequestException("当前视觉模板不适配行业模板");
|
||||
const templatePackageSnapshot = {
|
||||
schemaVersion: "1.0",
|
||||
version: template.version,
|
||||
industryTemplate: template,
|
||||
visualTemplate: visualManifest,
|
||||
capabilities: template.capabilities,
|
||||
};
|
||||
const packageVersion = await this.resolveInstallablePackageVersion(
|
||||
templateKey,
|
||||
visualTemplateKey,
|
||||
templatePackageVersionId,
|
||||
);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
// 安装记录与品牌身份必须同时落库,否则会出现「品牌在跑 A 模板、台账记的是 B」的漂移。
|
||||
// 已经自定义过视觉模板的品牌,补建台账时保留原选择,只把行业模板身份写回。
|
||||
const nextConfig = (
|
||||
brandConfig.visualTemplateKey === undefined
|
||||
? { ...brandConfig, visualTemplateKey }
|
||||
: brandConfig
|
||||
) as Prisma.InputJsonValue;
|
||||
await tx.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey, config: nextConfig },
|
||||
data: { templateKey },
|
||||
});
|
||||
const installation = await tx.brandTemplateInstallation.create({
|
||||
data: {
|
||||
brandId,
|
||||
templateKey,
|
||||
templateVersion: template.version,
|
||||
visualTemplateKey,
|
||||
templatePackageVersionId: packageVersion?.id ?? null,
|
||||
contentChecksum: packageVersion?.contentChecksum ?? null,
|
||||
configSnapshot: templatePackageSnapshot as unknown as Prisma.InputJsonValue,
|
||||
templatePackageVersionId: packageVersion.id,
|
||||
contentChecksum: packageVersion.contentChecksum,
|
||||
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
await tx.brandFieldDefinition.createMany({
|
||||
@@ -192,42 +152,112 @@ export class TemplateWorkspaceService {
|
||||
}
|
||||
private async resolveInstallablePackageVersion(
|
||||
templateKey: BrandTemplateKey,
|
||||
visualTemplateKey: string,
|
||||
templatePackageVersionId?: string,
|
||||
): Promise<TemplatePackageVersion | null> {
|
||||
const version = templatePackageVersionId
|
||||
? await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: templatePackageVersionId },
|
||||
})
|
||||
: await this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: visualTemplateKey, status: "published" },
|
||||
orderBy: { importedAt: "desc" },
|
||||
});
|
||||
if (!version) {
|
||||
if (templatePackageVersionId) throw new BadRequestException("指定的模板包版本不存在");
|
||||
return null;
|
||||
}
|
||||
templatePackageVersionId: string,
|
||||
): Promise<TemplatePackageVersion> {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: templatePackageVersionId },
|
||||
});
|
||||
if (!version) throw new BadRequestException("指定的模板包版本不存在");
|
||||
if (version.status !== "published")
|
||||
throw new BadRequestException("只有已发布的模板包版本可以安装到品牌");
|
||||
const manifest = record(version.manifestSnapshot);
|
||||
const manifestVisualTemplateKey =
|
||||
typeof manifest.visualTemplateKey === "string"
|
||||
? manifest.visualTemplateKey
|
||||
: version.packageKey;
|
||||
if (
|
||||
manifest.packageKey !== version.packageKey ||
|
||||
manifest.version !== version.version ||
|
||||
manifestVisualTemplateKey !== visualTemplateKey ||
|
||||
typeof manifest.visualTemplateKey !== "string" ||
|
||||
manifest.packageKey !== manifest.visualTemplateKey ||
|
||||
!Array.isArray(manifest.supportedIndustryTemplates) ||
|
||||
!manifest.supportedIndustryTemplates.includes(templateKey)
|
||||
) {
|
||||
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
|
||||
}
|
||||
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
|
||||
throw new BadRequestException("模板包版本不符合统一模板契约");
|
||||
return version;
|
||||
}
|
||||
|
||||
async selectVersion(
|
||||
brandId: string,
|
||||
body: {
|
||||
templatePackageVersionId: string;
|
||||
expectedCurrentPackageVersionId?: string | null;
|
||||
confirm: boolean;
|
||||
},
|
||||
actorId: string,
|
||||
requestId?: string,
|
||||
) {
|
||||
if (!body.confirm) throw new BadRequestException("选择模板版本必须显式确认");
|
||||
const [installation, brand, target] = await Promise.all([
|
||||
this.installation(brandId),
|
||||
this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: body.templatePackageVersionId },
|
||||
}),
|
||||
]);
|
||||
if (!brand) throw new BadRequestException("品牌不存在");
|
||||
if (body.expectedCurrentPackageVersionId !== installation.templatePackageVersionId)
|
||||
throw new ConflictException("当前模板版本已变化,请刷新后重试");
|
||||
if (!target || target.status !== "published")
|
||||
throw new BadRequestException("指定模板包版本不存在或未发布");
|
||||
const manifest = record(target.manifestSnapshot) as unknown as TemplatePackageManifest;
|
||||
if (
|
||||
target.packageKey !== manifest.packageKey ||
|
||||
target.version !== manifest.version ||
|
||||
manifest.packageKey !== manifest.visualTemplateKey ||
|
||||
!manifest.supportedIndustryTemplates?.includes(brand.templateKey) ||
|
||||
validateTemplatePackageManifest(manifest).length
|
||||
)
|
||||
throw new BadRequestException("指定模板包版本不符合当前品牌的统一模板契约");
|
||||
if (target.id === installation.templatePackageVersionId)
|
||||
return { installation, unchanged: true };
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const changed = await tx.brandTemplateInstallation.updateMany({
|
||||
where: {
|
||||
id: installation.id,
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
},
|
||||
data: {
|
||||
templatePackageVersionId: target.id,
|
||||
templateVersion: target.version,
|
||||
contentChecksum: target.contentChecksum,
|
||||
configSnapshot: manifest as unknown as Prisma.InputJsonValue,
|
||||
previousSnapshots: [...history, installation.configSnapshot],
|
||||
},
|
||||
});
|
||||
if (changed.count !== 1) throw new ConflictException("当前模板版本已变化,请刷新后重试");
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: target.id,
|
||||
actorId,
|
||||
action: "brand_template_selected",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
brandId,
|
||||
fromVersionId: installation.templatePackageVersionId,
|
||||
toVersionId: target.id,
|
||||
contentChecksum: target.contentChecksum,
|
||||
},
|
||||
},
|
||||
});
|
||||
return tx.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { id: installation.id },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
});
|
||||
return { installation: updated, unchanged: false };
|
||||
}
|
||||
|
||||
private async installation(brandId: string) {
|
||||
const item = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
|
||||
const item = await this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
if (!item) throw new BadRequestException("尚未安装行业模板");
|
||||
return item;
|
||||
}
|
||||
@@ -235,30 +265,37 @@ export class TemplateWorkspaceService {
|
||||
const templateKey = await this.getEffectiveTemplateKey(brandId);
|
||||
const template = getBrandTemplate(templateKey);
|
||||
if (!template) throw new BadRequestException("当前行业模板不存在");
|
||||
const [installation, brand] = await Promise.all([
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
|
||||
]);
|
||||
// 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。
|
||||
const currentVersion = installation?.templateVersion ?? template.version;
|
||||
const installation = await this.installation(brandId);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
});
|
||||
const config = record(brand?.config);
|
||||
const visualTemplateKey =
|
||||
installation?.visualTemplateKey ??
|
||||
(typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined) ??
|
||||
getDefaultVisualTemplateKey(templateKey);
|
||||
const currentPackage = installation?.templatePackageVersionId
|
||||
? await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: installation.templatePackageVersionId },
|
||||
})
|
||||
: null;
|
||||
const targetPackage = visualTemplateKey
|
||||
? await this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: visualTemplateKey, status: "published" },
|
||||
orderBy: { importedAt: "desc" },
|
||||
})
|
||||
: null;
|
||||
if (!installation.templatePackageVersion || !installation.templatePackageVersionId)
|
||||
throw new BadRequestException("品牌安装没有锁定精确视觉模板包版本");
|
||||
const currentVersion = installation.templateVersion;
|
||||
const visualTemplateKey = record(
|
||||
installation.templatePackageVersion.manifestSnapshot,
|
||||
).visualTemplateKey;
|
||||
if (typeof visualTemplateKey !== "string")
|
||||
throw new BadRequestException("已安装模板版本缺少 visualTemplateKey 声明");
|
||||
const [currentPackage, targetPackage] = await Promise.all([
|
||||
this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: installation.templatePackageVersionId },
|
||||
}),
|
||||
this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: visualTemplateKey, status: "published" },
|
||||
orderBy: { importedAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
if (!currentPackage) throw new BadRequestException("当前安装引用的模板包版本不存在");
|
||||
if (
|
||||
currentPackage.packageKey !== visualTemplateKey ||
|
||||
record(currentPackage.manifestSnapshot).visualTemplateKey !== visualTemplateKey
|
||||
)
|
||||
throw new BadRequestException("品牌安装与模板包视觉声明不一致");
|
||||
const targetManifest = record(targetPackage?.manifestSnapshot);
|
||||
const currentManifest = record(currentPackage?.manifestSnapshot);
|
||||
const currentManifest = record(currentPackage.manifestSnapshot);
|
||||
const currentDeclarations = manifestRecords(currentManifest.templateFields);
|
||||
const targetDeclarations = manifestRecords(targetManifest.templateFields);
|
||||
const currentByKey = new Map(currentDeclarations.map((item) => [String(item.key), item]));
|
||||
@@ -316,12 +353,11 @@ export class TemplateWorkspaceService {
|
||||
templateKey,
|
||||
currentVersion,
|
||||
latestVersion: targetPackage?.version ?? template.version,
|
||||
currentPackageVersionId: currentPackage?.id ?? null,
|
||||
currentContentChecksum:
|
||||
currentPackage?.contentChecksum ?? installation?.contentChecksum ?? null,
|
||||
currentPackageVersionId: currentPackage.id,
|
||||
currentContentChecksum: currentPackage.contentChecksum,
|
||||
targetPackageVersionId: targetPackage?.id ?? null,
|
||||
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
||||
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage?.id),
|
||||
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage.id),
|
||||
canRollback:
|
||||
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
|
||||
changes: {
|
||||
@@ -404,7 +440,8 @@ export class TemplateWorkspaceService {
|
||||
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
|
||||
const manifest = record(target.manifestSnapshot);
|
||||
if (
|
||||
target.packageKey !== installation.visualTemplateKey ||
|
||||
target.packageKey !==
|
||||
record(installation.templatePackageVersion?.manifestSnapshot).visualTemplateKey ||
|
||||
manifest.packageKey !== target.packageKey ||
|
||||
manifest.version !== target.version ||
|
||||
!Array.isArray(manifest.supportedIndustryTemplates) ||
|
||||
@@ -474,12 +511,15 @@ export class TemplateWorkspaceService {
|
||||
where: { packageKey: previousManifest.packageKey, version },
|
||||
})
|
||||
: null;
|
||||
if (!previousPackage)
|
||||
throw new BadRequestException("历史模板包版本不存在,不能回滚到未锁定版本");
|
||||
if (
|
||||
previousPackage &&
|
||||
(previousPackage.packageKey !== installation.visualTemplateKey ||
|
||||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
|
||||
installation.templateKey,
|
||||
))
|
||||
previousPackage.packageKey !==
|
||||
record(installation.templatePackageVersion?.manifestSnapshot).visualTemplateKey ||
|
||||
previousPackage.packageKey !== record(previousPackage.manifestSnapshot).visualTemplateKey ||
|
||||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
|
||||
installation.templateKey,
|
||||
)
|
||||
)
|
||||
throw new BadRequestException("上一版模板包与当前品牌行业或视觉模板不兼容");
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
@@ -491,8 +531,8 @@ export class TemplateWorkspaceService {
|
||||
},
|
||||
data: {
|
||||
templateVersion: version,
|
||||
templatePackageVersionId: previousPackage?.id ?? null,
|
||||
contentChecksum: previousPackage?.contentChecksum ?? null,
|
||||
templatePackageVersionId: previousPackage.id,
|
||||
contentChecksum: previousPackage.contentChecksum,
|
||||
configSnapshot: previous,
|
||||
previousSnapshots: history.slice(0, -1),
|
||||
},
|
||||
@@ -509,7 +549,7 @@ export class TemplateWorkspaceService {
|
||||
brandId,
|
||||
fromVersionId: installation.templatePackageVersionId,
|
||||
fromVersion: installation.templateVersion,
|
||||
toVersionId: previousPackage?.id ?? null,
|
||||
toVersionId: previousPackage.id,
|
||||
toVersion: version,
|
||||
},
|
||||
},
|
||||
@@ -525,28 +565,9 @@ export class TemplateWorkspaceService {
|
||||
}
|
||||
|
||||
async function readPackageFiles(
|
||||
version: Pick<
|
||||
TemplatePackageVersion,
|
||||
"artifactPath" | "validationReport" | "packageKey" | "version"
|
||||
>,
|
||||
version: Pick<TemplatePackageVersion, "validationReport">,
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const stored = manifestRecords(record(version.validationReport).files);
|
||||
if (stored.length) return stored;
|
||||
const root = `${version.packageKey}-${version.version}`;
|
||||
const checksumEntry = `${root}/checksums.json`;
|
||||
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(version.packageKey) || root.includes("/")) return [];
|
||||
try {
|
||||
const { stdout: entries } = await execFileAsync("tar", ["-tzf", version.artifactPath], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
if (!entries.split("\n").some((entry) => entry === checksumEntry)) return [];
|
||||
const { stdout } = await execFileAsync("tar", ["-xOzf", version.artifactPath, checksumEntry], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
return manifestRecords(record(JSON.parse(stdout)).files);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return manifestRecords(record(version.validationReport).files);
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
|
||||
@@ -20,6 +20,7 @@ const expectedRoutes = new Set([
|
||||
"GET /admin/workspace/template/preview",
|
||||
"POST /admin/workspace/template/upgrade",
|
||||
"POST /admin/workspace/template/rollback",
|
||||
"POST /admin/workspace/template/select-version",
|
||||
"GET /admin/workspace/capabilities",
|
||||
"GET /admin/workspace/sample-content/preview",
|
||||
"POST /admin/workspace/sample-content/import",
|
||||
|
||||
@@ -66,11 +66,22 @@ function createTemplateArchive(template = "acheng-campus-food", mutateManifest)
|
||||
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,
|
||||
@@ -122,16 +133,30 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const empty = await request("/admin/templates", { headers });
|
||||
assert.equal(empty.statusCode, 200);
|
||||
assert.deepEqual(JSON.parse(empty.body).items, []);
|
||||
assert.equal(JSON.parse(empty.body).total, 0);
|
||||
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.5");
|
||||
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();
|
||||
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);
|
||||
assert.equal(imported.statusCode, 201, imported.body);
|
||||
assert.equal(JSON.parse(imported.body).imported, true);
|
||||
const repeated = await request("/admin/templates/import", {
|
||||
method: "POST",
|
||||
@@ -142,9 +167,13 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
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, 1);
|
||||
assert.equal(listedBody.items[0].status, "imported");
|
||||
const versionId = listedBody.items[0].id;
|
||||
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 },
|
||||
});
|
||||
@@ -349,7 +378,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
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(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");
|
||||
@@ -483,10 +512,10 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
},
|
||||
},
|
||||
},
|
||||
/所属行业/,
|
||||
/所属行业|must match its key/,
|
||||
],
|
||||
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
|
||||
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /renderer/],
|
||||
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /元数据/],
|
||||
[{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/],
|
||||
[{ ...stored.manifestSnapshot, dataSlots: [null] }, /契约/],
|
||||
[{ ...stored.manifestSnapshot, navigation: [null] }, /契约/],
|
||||
@@ -508,7 +537,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
where: { id: versionId },
|
||||
data: { archiveChecksum: stored.archiveChecksum },
|
||||
});
|
||||
// 独立演示内容不依赖 bootstrap;旧包则显式标明兼容来源。
|
||||
// 独立演示内容不依赖 bootstrap sampleContent。
|
||||
await prisma.templatePackageVersion.update({
|
||||
where: { id: versionId },
|
||||
data: { manifestSnapshot: { ...stored.manifestSnapshot, sampleContent: {} } },
|
||||
@@ -527,9 +556,8 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
const legacy = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
||||
headers,
|
||||
});
|
||||
assert.equal(legacy.statusCode, 200, legacy.body);
|
||||
assert.equal(JSON.parse(legacy.body).preview.fixtureSource, "legacy-sampleContent");
|
||||
assert.equal(JSON.parse(legacy.body).preview.diagnostics[0].code, "LEGACY_PREVIEW_SAMPLE");
|
||||
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 },
|
||||
@@ -1848,7 +1876,7 @@ test("health and public content are available without authentication", async ()
|
||||
assert.equal(missingSlug.statusCode, 404);
|
||||
});
|
||||
|
||||
test("visual template compatibility is enforced by catalog, preview, and brand switching", async () => {
|
||||
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;
|
||||
@@ -1875,12 +1903,20 @@ test("visual template compatibility is enforced by catalog, preview, and brand s
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const compatibleSwitch = await request("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { config: { visualTemplateKey: "acheng-campus-food" } },
|
||||
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { brandId },
|
||||
});
|
||||
assert.equal(compatibleSwitch.statusCode, 200);
|
||||
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 () => {
|
||||
@@ -1890,11 +1926,16 @@ test("industry template state has a single source of truth", async () => {
|
||||
});
|
||||
assert.ok(brand);
|
||||
const templateKey = brand.templateKey;
|
||||
const visualTemplateKey = brand.config?.visualTemplateKey;
|
||||
const installationBefore = await prisma.brandTemplateInstallation.findFirst({
|
||||
assert.equal(Object.hasOwn(brand.config ?? {}, "visualTemplateKey"), false);
|
||||
const installation = await prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
});
|
||||
const fieldsBefore = await prisma.brandFieldDefinition.findMany({ 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);
|
||||
@@ -1912,22 +1953,24 @@ test("industry template state has a single source of truth", async () => {
|
||||
};
|
||||
|
||||
try {
|
||||
// 品牌身份来自 BrandProfile.templateKey;即使版本台账缺失,预览也必须可用而不是 400。
|
||||
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(installationBefore?.previousSnapshots?.length));
|
||||
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 },
|
||||
payload: {
|
||||
templateKey: otherKey,
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
},
|
||||
});
|
||||
assert.equal(rejected.statusCode, 400);
|
||||
assert.match(errorMessage(rejected.body), /更换行业模板不在本版本范围内/);
|
||||
@@ -1936,58 +1979,17 @@ test("industry template state has a single source of truth", async () => {
|
||||
select: { templateKey: true, config: true },
|
||||
});
|
||||
assert.equal(afterRejected.templateKey, templateKey);
|
||||
assert.equal(afterRejected.config?.visualTemplateKey, visualTemplateKey);
|
||||
assert.equal(Object.hasOwn(afterRejected.config ?? {}, "visualTemplateKey"), false);
|
||||
|
||||
// 台账已存在时重复安装当前模板应被拒绝。
|
||||
if (installationBefore) {
|
||||
const repeated = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { templateKey },
|
||||
});
|
||||
assert.equal(repeated.statusCode, 400);
|
||||
assert.match(errorMessage(repeated.body), /已经安装/);
|
||||
|
||||
// 缺失的版本台账可以由安装补齐,且不改动品牌身份与视觉模板。
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
const repaired = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { templateKey },
|
||||
});
|
||||
assert.equal(repaired.statusCode, 201, repaired.body);
|
||||
const installationAfter = await prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
});
|
||||
assert.equal(installationAfter.templateKey, templateKey);
|
||||
const afterRepair = await prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true, config: true },
|
||||
});
|
||||
assert.equal(afterRepair.templateKey, templateKey);
|
||||
assert.equal(afterRepair.config?.visualTemplateKey, visualTemplateKey);
|
||||
}
|
||||
} finally {
|
||||
const createdFieldIds = (await prisma.brandFieldDefinition.findMany({ where: { brandId } }))
|
||||
.filter((item) => !fieldsBefore.some((current) => current.id === item.id))
|
||||
.map((item) => item.id);
|
||||
if (createdFieldIds.length)
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { id: { in: createdFieldIds } } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
if (installationBefore) {
|
||||
await prisma.brandTemplateInstallation.create({
|
||||
data: {
|
||||
brandId,
|
||||
templateKey: installationBefore.templateKey,
|
||||
templateVersion: installationBefore.templateVersion,
|
||||
configSnapshot: installationBefore.configSnapshot,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey, config: brand.config },
|
||||
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 } });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2158,16 +2160,12 @@ test("editor membership can manage brand content but cannot change system settin
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(capabilities.statusCode, 403);
|
||||
const visualHistory = await request("/admin/config/visual-template/history", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(visualHistory.statusCode, 403);
|
||||
const visualUpdate = await request("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { config: { visualTemplateKey: "unknown-visual" } },
|
||||
});
|
||||
assert.equal(visualUpdate.statusCode, 403);
|
||||
assert.equal(visualUpdate.statusCode, 400);
|
||||
} finally {
|
||||
await prisma.brandMembership.update({
|
||||
where: { id: membership.id },
|
||||
@@ -2352,10 +2350,9 @@ test("admin capability list includes template defaults and brand overrides", asy
|
||||
|
||||
test("installing another industry template is rejected without drifting brand identity", async () => {
|
||||
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: 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 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 },
|
||||
@@ -2367,16 +2364,22 @@ test("installing another industry template is rejected without drifting brand id
|
||||
const installed = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { templateKey: "doors" },
|
||||
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.deepEqual(brandAfter.config, originalBrand.config);
|
||||
assert.equal(await prisma.brandTemplateInstallation.count({ where: { brandId } }), 0);
|
||||
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");
|
||||
@@ -2389,28 +2392,17 @@ test("installing another industry template is rejected without drifting brand id
|
||||
assert.equal(samplePreview.statusCode, 200);
|
||||
assert.equal(JSON.parse(samplePreview.body).templateKey, originalBrand.templateKey);
|
||||
} finally {
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
|
||||
});
|
||||
assert.equal(
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).templateKey,
|
||||
originalBrand.templateKey,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("cross template requests are rejected even when a drifted ledger already exists", async () => {
|
||||
test("cross template requests are rejected without creating a drifted installation", async () => {
|
||||
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: 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 } });
|
||||
await prisma.brandTemplateInstallation.create({
|
||||
data: {
|
||||
brandId,
|
||||
templateKey: "doors",
|
||||
templateVersion: "1.0.0",
|
||||
configSnapshot: { schemaVersion: "1.0" },
|
||||
},
|
||||
const installationBefore = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { brandId },
|
||||
});
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
@@ -2423,36 +2415,44 @@ test("cross template requests are rejected even when a drifted ledger already ex
|
||||
const rejected = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { templateKey: "doors" },
|
||||
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.equal(await prisma.brandTemplateInstallation.count({ where: { brandId } }), 1);
|
||||
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 {
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
|
||||
});
|
||||
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: "示例内容,待品牌主理人完善。" },
|
||||
});
|
||||
await prisma.brandProfile.update({ where: { id: brandId }, data: { templateKey: "doors" } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
assert.equal(originalBrand?.templateKey, "food");
|
||||
const packageVersionId = originalInstallation.templatePackageVersionId;
|
||||
assert.ok(packageVersionId);
|
||||
await prisma.offering.deleteMany({
|
||||
where: {
|
||||
brandId,
|
||||
@@ -2463,53 +2463,23 @@ test("admin can preview and import sample content idempotently", async () => {
|
||||
where: { brandId, content: "示例内容,待品牌主理人完善。" },
|
||||
});
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
|
||||
if (!originalForms.some((item) => item.isEnabled)) {
|
||||
await prisma.inquiryForm.create({
|
||||
data: {
|
||||
brandId,
|
||||
name: "现有客户表单",
|
||||
fieldsSnapshot: [{ key: "phone", label: "联系电话", type: "tel", required: true }],
|
||||
},
|
||||
});
|
||||
}
|
||||
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 archive = createTemplateArchive("acheng-campus-food");
|
||||
const uploaded = multipartArchive(archive);
|
||||
const importedPackage = await request("/admin/templates/import", {
|
||||
method: "POST",
|
||||
headers: { ...headers, ...uploaded.headers },
|
||||
rawPayload: uploaded.payload,
|
||||
});
|
||||
assert.equal(importedPackage.statusCode, 201, importedPackage.body);
|
||||
const packageVersionId = JSON.parse(importedPackage.body).version.id;
|
||||
const publishedPackage = await request(`/admin/templates/${packageVersionId}/publish`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
});
|
||||
assert.equal(publishedPackage.statusCode, 201, publishedPackage.body);
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey: "food", config: { visualTemplateKey: "acheng-campus-food" } },
|
||||
});
|
||||
await prisma.brandTemplateInstallation.create({
|
||||
data: {
|
||||
brandId,
|
||||
templateKey: "food",
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
templatePackageVersionId: packageVersionId,
|
||||
contentChecksum: JSON.parse(importedPackage.body).version.contentChecksum,
|
||||
templateVersion: JSON.parse(importedPackage.body).version.version,
|
||||
configSnapshot: { schemaVersion: "1.0" },
|
||||
},
|
||||
});
|
||||
const preview = await request("/admin/workspace/sample-content/preview", {
|
||||
headers,
|
||||
});
|
||||
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");
|
||||
@@ -2566,6 +2536,7 @@ test("admin can preview and import sample content idempotently", async () => {
|
||||
}
|
||||
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(
|
||||
@@ -2575,12 +2546,10 @@ test("admin can preview and import sample content idempotently", async () => {
|
||||
}
|
||||
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
|
||||
await prisma.templateBootstrapImport.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
await prisma.templatePackageAuditLog.deleteMany({
|
||||
where: { templatePackageVersionId: packageVersionId },
|
||||
});
|
||||
await prisma.templatePackageVersion.delete({ where: { id: packageVersionId } });
|
||||
await prisma.templatePackage.deleteMany({ where: { packageKey: "acheng-campus-food" } });
|
||||
assert.deepEqual(
|
||||
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } }),
|
||||
originalInstallation,
|
||||
);
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey: originalBrand?.templateKey ?? "food", config: originalBrand?.config },
|
||||
@@ -2588,6 +2557,9 @@ test("admin can preview and import sample content idempotently", async () => {
|
||||
});
|
||||
|
||||
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 } });
|
||||
@@ -2611,13 +2583,19 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
const crossTemplate = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { templateKey: currentTemplateKey === "personal" ? "food" : "personal" },
|
||||
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 },
|
||||
payload: {
|
||||
templateKey: currentTemplateKey,
|
||||
templatePackageVersionId: originalInstallation.templatePackageVersionId,
|
||||
},
|
||||
});
|
||||
assert.equal(installed.statusCode, 201, installed.body);
|
||||
assert.equal(JSON.parse(installed.body).template.key, currentTemplateKey);
|
||||
@@ -2627,7 +2605,10 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
|
||||
assert.equal(
|
||||
JSON.parse(installed.body).installation.configSnapshot.packageKey,
|
||||
originalInstallation.configSnapshot.packageKey,
|
||||
);
|
||||
const installedRecord = JSON.parse(installed.body).installation;
|
||||
const createdVersionIds = [];
|
||||
let historicalReleaseId;
|
||||
@@ -2681,7 +2662,10 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
},
|
||||
});
|
||||
historicalSubmissionId = historicalSubmission.id;
|
||||
const packageKey = installedRecord.visualTemplateKey;
|
||||
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({
|
||||
@@ -2689,23 +2673,22 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
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: "集成测试基线包",
|
||||
visualTemplateKey: packageKey,
|
||||
status: "published",
|
||||
manifestSnapshot: {
|
||||
packageKey,
|
||||
version: initialPackageVersion,
|
||||
supportedIndustryTemplates: [currentTemplateKey],
|
||||
requiredCapabilities: ["offerings"],
|
||||
templateFields: [{ key: "founder", binding: "brand.config.founder", label: "主理人" }],
|
||||
entrypoints: { home: "pages/index/index" },
|
||||
assetSlots: [{ key: "brand.logo", binding: "brand.avatarUrl" }],
|
||||
},
|
||||
manifestSnapshot: initialManifest,
|
||||
validationReport: {},
|
||||
contentChecksum: `checksum-${initialPackageVersion}`,
|
||||
archiveChecksum: `archive-${initialPackageVersion}`,
|
||||
@@ -2730,28 +2713,28 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
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: "集成测试升级包",
|
||||
visualTemplateKey: packageKey,
|
||||
status: "published",
|
||||
manifestSnapshot: {
|
||||
packageKey,
|
||||
version: packageVersion,
|
||||
supportedIndustryTemplates: [currentTemplateKey],
|
||||
requiredCapabilities: [],
|
||||
templateFields: [
|
||||
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
|
||||
],
|
||||
entrypoints: { home: "pages/home/index", profile: "pages/profile/index" },
|
||||
assetSlots: [
|
||||
{ key: "brand.logo", binding: "brand.avatarUrl" },
|
||||
{ key: "home.hero", binding: "brand.config.heroImage" },
|
||||
],
|
||||
},
|
||||
manifestSnapshot: targetManifest,
|
||||
validationReport: {},
|
||||
contentChecksum: `checksum-${packageVersion}`,
|
||||
archiveChecksum: `archive-${packageVersion}`,
|
||||
@@ -2913,7 +2896,6 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
assert.equal(operationAudit[0].metadata.brandId, brandId);
|
||||
assert.equal(operationAudit[0].metadata.contentChecksum, packageVersionRecord.contentChecksum);
|
||||
assert.ok(operationAudit[0].requestId);
|
||||
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
|
||||
const workspace = await request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -2964,6 +2946,17 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
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 },
|
||||
@@ -2994,13 +2987,12 @@ test("admin preview workspace is authorized and brand-scoped draft runtime", asy
|
||||
workspace.brand.slug,
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
|
||||
);
|
||||
assert.equal(workspace.brand.visualTemplateKey, "acheng-campus-food");
|
||||
assert.equal(workspace.visualTemplate.key, "acheng-campus-food");
|
||||
const unpublishedBrand = await prisma.brandProfile.create({
|
||||
data: {
|
||||
slug: "unpublished-preview-fixture",
|
||||
name: "未发布预览品牌",
|
||||
templateKey: "personal",
|
||||
config: { visualTemplateKey: "linjing-editorial" },
|
||||
adminMemberships: { create: { adminUserId: user.id, role: "owner" } },
|
||||
},
|
||||
});
|
||||
@@ -3013,9 +3005,7 @@ test("admin preview workspace is authorized and brand-scoped draft runtime", asy
|
||||
const draft = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: `Bearer ${draftToken}` },
|
||||
});
|
||||
assert.equal(draft.statusCode, 200);
|
||||
assert.equal(JSON.parse(draft.body).brand.slug, unpublishedBrand.slug);
|
||||
assert.equal(JSON.parse(draft.body).publication.status, "draft");
|
||||
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);
|
||||
@@ -3026,18 +3016,11 @@ test("admin preview workspace is authorized and brand-scoped draft runtime", asy
|
||||
|
||||
test("admin can customize workspace fields with brand isolation", async () => {
|
||||
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 install = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { templateKey: "food" },
|
||||
});
|
||||
assert.equal(install.statusCode, 201);
|
||||
const workspace = await request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -3074,45 +3057,37 @@ test("admin can customize workspace fields with brand isolation", async () => {
|
||||
assert.equal(deletedField.statusCode, 200);
|
||||
} finally {
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
}
|
||||
});
|
||||
|
||||
test("admin visual template selection is reflected in public runtime workspace", async () => {
|
||||
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 before = await request("/public/workspace");
|
||||
assert.equal(before.statusCode, 200);
|
||||
const updated = await request("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { config: { visualTemplateKey: "acheng-campus-food" } },
|
||||
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { brandId },
|
||||
});
|
||||
assert.equal(updated.statusCode, 200);
|
||||
try {
|
||||
const runtime = await request("/public/workspace");
|
||||
assert.equal(runtime.statusCode, 200);
|
||||
const body = JSON.parse(runtime.body);
|
||||
assert.equal(body.visualTemplate.key, "acheng-campus-food");
|
||||
assert.equal(body.visualTemplate.version, "1.0.0");
|
||||
assert.equal(body.theme.colors.accent, "#E87532");
|
||||
assert.equal(body.visualTemplate.variants.hero, "stall-board");
|
||||
assert.equal(body.visualTemplateManifest.key, "acheng-campus-food");
|
||||
assert.equal(body.visualTemplateManifest.brandFirst, true);
|
||||
assert.deepEqual(
|
||||
body.visualTemplateManifest.pages.map((page) => page.key),
|
||||
["home", "offerings", "detail", "inquiry", "success", "records", "profile"],
|
||||
);
|
||||
} finally {
|
||||
await request("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { config: JSON.parse(before.body).brand?.config ?? {} },
|
||||
});
|
||||
}
|
||||
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 () => {
|
||||
@@ -4445,7 +4420,6 @@ test("atelier template imports selected package and preserves draft publication
|
||||
tagline: "独立开发者 · 品牌小程序构建",
|
||||
description: "专注个人品牌表达、内容管理与咨询承接。",
|
||||
config: {
|
||||
visualTemplateKey: "linjing-editorial",
|
||||
founder: "验收主理人",
|
||||
title: "产品设计 / 全栈开发",
|
||||
visualPresentation: { home: { subtitle: "保留已有品牌说明" } },
|
||||
@@ -4478,11 +4452,20 @@ test("atelier template imports selected package and preserves draft publication
|
||||
403,
|
||||
);
|
||||
}
|
||||
await json("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: { config: { visualTemplateKey: "atelier-solopreneur" } },
|
||||
});
|
||||
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",
|
||||
@@ -4503,6 +4486,18 @@ test("atelier template imports selected package and preserves draft publication
|
||||
});
|
||||
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", {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { createApp } from "../dist/main.js";
|
||||
import { signIdentity } from "../dist/auth.js";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
const packageKeys = ["acheng-campus-food", "linjing-editorial"];
|
||||
|
||||
function run(command, args, options = {}) {
|
||||
const result = spawnSync(command, args, { stdio: "inherit", ...options });
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) throw new Error(`${command} exited with ${result.status}`);
|
||||
}
|
||||
|
||||
function archiveFor(packageKey) {
|
||||
const output = mkdtempSync(path.join(os.tmpdir(), "pb-template-integration-"));
|
||||
const repositoryRoot = path.resolve(process.cwd(), "../..");
|
||||
run(
|
||||
"node",
|
||||
[
|
||||
path.join(repositoryRoot, "scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
packageKey,
|
||||
"--out",
|
||||
output,
|
||||
],
|
||||
{ cwd: repositoryRoot },
|
||||
);
|
||||
const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz"));
|
||||
assert.ok(filename, `template pack did not produce an archive for ${packageKey}`);
|
||||
return {
|
||||
directory: output,
|
||||
filename,
|
||||
content: readFileSync(path.join(output, filename)),
|
||||
};
|
||||
}
|
||||
|
||||
async function importPackage(app, token, archive) {
|
||||
const boundary = `----pb-integration-${Date.now()}`;
|
||||
const payload = Buffer.concat([
|
||||
Buffer.from(
|
||||
`--${boundary}\r\nContent-Disposition: form-data; name="archive"; filename="${archive.filename}"\r\nContent-Type: application/gzip\r\n\r\n`,
|
||||
),
|
||||
archive.content,
|
||||
Buffer.from(`\r\n--${boundary}--\r\n`),
|
||||
]);
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/admin/templates/import",
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
"content-type": `multipart/form-data; boundary=${boundary}`,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
assert.equal(response.statusCode, 201, response.body);
|
||||
const imported = response.json().version;
|
||||
const publish = await app.inject({
|
||||
method: "POST",
|
||||
url: `/admin/templates/${imported.id}/publish`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(publish.statusCode, 201, publish.body);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const actor = await prisma.adminUser.upsert({
|
||||
where: { username: "integration-template-admin" },
|
||||
update: {
|
||||
isEnabled: true,
|
||||
mustChangePassword: false,
|
||||
platformTemplateRole: "template_admin",
|
||||
},
|
||||
create: {
|
||||
username: "integration-template-admin",
|
||||
passwordHash: await bcrypt.hash("integration-only-password", 4),
|
||||
displayName: "Integration Template Admin",
|
||||
platformTemplateRole: "template_admin",
|
||||
},
|
||||
});
|
||||
const token = signIdentity({ subject: actor.id, brandId: "integration", role: "admin" });
|
||||
const app = await createApp();
|
||||
const archives = [];
|
||||
try {
|
||||
await app.init();
|
||||
for (const packageKey of packageKeys) {
|
||||
const archive = archiveFor(packageKey);
|
||||
archives.push(archive.directory);
|
||||
await importPackage(app, token, archive);
|
||||
}
|
||||
} finally {
|
||||
await app.close();
|
||||
for (const directory of archives) rmSync(directory, { recursive: true, force: true });
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -26,6 +26,8 @@ async function main() {
|
||||
await administrator.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
||||
created = true;
|
||||
if (run("pnpm", ["exec", "prisma", "migrate", "deploy"]) !== 0) return status;
|
||||
if (run(process.execPath, ["test/prepare-integration-template-packages.mjs"]) !== 0)
|
||||
return status;
|
||||
if (run("pnpm", ["db:seed"]) !== 0) return status;
|
||||
const initialTrustCount = await fixtureDatabase.trustContent.count();
|
||||
const initialFormCount = await fixtureDatabase.inquiryForm.count();
|
||||
|
||||
@@ -109,6 +109,7 @@ test("template preview matrix keeps every deployed package, industry, and versio
|
||||
packageKey: fixture.manifest.packageKey,
|
||||
version: fixture.manifest.version,
|
||||
displayName: fixture.manifest.displayName,
|
||||
visualTemplateKey: fixture.manifest.visualTemplateKey,
|
||||
status: "imported" as const,
|
||||
manifestSnapshot: fixture.manifest,
|
||||
contentChecksum: fixture.contentChecksum,
|
||||
@@ -148,10 +149,7 @@ test("template preview matrix keeps every deployed package, industry, and versio
|
||||
assert.equal(firstPreview.template.packageKey, fixture.manifest.packageKey);
|
||||
assert.equal(firstPreview.industry.key, industry);
|
||||
assert.equal(firstPreview.workspace.brand.templateKey, industry);
|
||||
assert.equal(
|
||||
firstPreview.compatibility.renderer.key,
|
||||
fixture.manifest.visualTemplateKey ?? fixture.manifest.packageKey,
|
||||
);
|
||||
assert.equal(firstPreview.compatibility.renderer.key, fixture.manifest.visualTemplateKey);
|
||||
assert.equal(firstPreview.preview.safety.submissions, "disabled");
|
||||
assert.ok(firstPreview.workspace.offerings.length > 0);
|
||||
|
||||
@@ -163,16 +161,8 @@ test("template preview matrix keeps every deployed package, industry, and versio
|
||||
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",
|
||||
);
|
||||
assert.deepEqual(firstPreview.preview.diagnostics, []);
|
||||
assert.equal(firstPreview.preview.fixtureSource, "previewFixture");
|
||||
|
||||
// 版本 ID 进入模拟品牌 ID,不同版本不会共享同一模拟品牌身份。
|
||||
assert.match(firstPreview.workspace.brand.id, new RegExp(`^template-preview:${first.id}`));
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
export function resolvePreviewRenderer<T>(
|
||||
modules: Record<string, T>,
|
||||
config: unknown,
|
||||
workspace: unknown,
|
||||
): T | undefined {
|
||||
if (!config || typeof config !== "object" || Array.isArray(config)) return undefined;
|
||||
const key = (config as Record<string, unknown>).visualTemplateKey;
|
||||
if (!workspace || typeof workspace !== "object" || Array.isArray(workspace)) return undefined;
|
||||
const visualTemplate = (workspace as Record<string, unknown>).visualTemplate;
|
||||
if (!visualTemplate || typeof visualTemplate !== "object" || Array.isArray(visualTemplate))
|
||||
return undefined;
|
||||
const key = (visualTemplate as Record<string, unknown>).key;
|
||||
if (typeof key !== "string" || !key) return undefined;
|
||||
const suffix = `/template-${key}/taro/index.tsx`;
|
||||
return Object.entries(modules).find(([path]) => path.endsWith(suffix))?.[1];
|
||||
|
||||
@@ -9,7 +9,7 @@ const renderers = import.meta.glob<{
|
||||
}>("../../../../packages/template-*/taro/index.tsx", { eager: true });
|
||||
|
||||
export function TemplatePage(props: TemplateProps) {
|
||||
const rendererModule = resolvePreviewRenderer(renderers, props.workspace.brand.config);
|
||||
const rendererModule = resolvePreviewRenderer(renderers, props.workspace);
|
||||
if (!rendererModule)
|
||||
return <div className="runtime-state">当前模板没有可用的 H5 预览 renderer</div>;
|
||||
const Renderer = rendererModule.TemplatePage;
|
||||
|
||||
@@ -20,7 +20,6 @@ const brand = {
|
||||
contactPhone: "13800138000",
|
||||
contactWechat: "food-example",
|
||||
config: {
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
founder: "测试主理人",
|
||||
title: "私房菜主理人",
|
||||
heroImage: "",
|
||||
@@ -56,7 +55,11 @@ const runtimeWorkspace = {
|
||||
founder: brand.config.founder,
|
||||
title: brand.config.title,
|
||||
visualPresentation: {},
|
||||
visualTemplateKey: brand.config.visualTemplateKey,
|
||||
},
|
||||
visualTemplate: {
|
||||
key: "acheng-campus-food",
|
||||
version: "1.0.2",
|
||||
name: "阿成校园餐",
|
||||
},
|
||||
templateData: {},
|
||||
navigation: { tabs: [] },
|
||||
|
||||
@@ -15,24 +15,27 @@ const modules = Object.fromEntries(
|
||||
]),
|
||||
);
|
||||
|
||||
test("多模板预览随当前品牌配置切换所有真实模板,重复切换不保留旧 renderer", () => {
|
||||
test("多模板预览随 Runtime 模板声明切换所有真实 renderer", () => {
|
||||
for (const manifest of [...manifests, ...manifests.reverse()]) {
|
||||
assert.equal(
|
||||
resolvePreviewRenderer(modules, { visualTemplateKey: manifest.packageKey })?.key,
|
||||
resolvePreviewRenderer(modules, {
|
||||
visualTemplate: { key: manifest.visualTemplateKey },
|
||||
})?.key,
|
||||
manifest.packageKey,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("缺少或未知模板时不回落到首个模板", () => {
|
||||
for (const config of [
|
||||
test("缺少或未知 Runtime 模板声明时不回落到首个模板", () => {
|
||||
for (const workspace of [
|
||||
undefined,
|
||||
null,
|
||||
[],
|
||||
{},
|
||||
{ visualTemplateKey: "missing" },
|
||||
{ visualTemplateKey: 1 },
|
||||
{ brand: { config: { visualTemplateKey: "acheng-campus-food" } } },
|
||||
{ visualTemplate: { key: "missing" } },
|
||||
{ visualTemplate: { key: 1 } },
|
||||
]) {
|
||||
assert.equal(resolvePreviewRenderer(modules, config), undefined);
|
||||
assert.equal(resolvePreviewRenderer(modules, workspace), undefined);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user