refactor: 退役运行时视觉模块并泛化模板门禁

This commit is contained in:
que01 committed 2026-09-26 22:30:26 +08:00
1 parent 25d1fe983c
commit e2e2340bfe
56 files changed
+290 -1037

No files matched your search

@@ -0,0 +1 @@
DROP TABLE "BrandModule";
-16
View File
@@ -54,7 +54,6 @@ model BrandProfile {
tags Tag[]
trustContents TrustContent[]
templateInstallations BrandTemplateInstallation[]
modules BrandModule[]
fieldDefinitions BrandFieldDefinition[]
offerings Offering[]
inquiryForms InquiryForm[]
@@ -123,21 +122,6 @@ model BrandTemplateInstallation {
@@index([brandId])
}
model BrandModule {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
type String
title String
isEnabled Boolean @default(true)
sortOrder Int @default(0)
source String @default("core")
config Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([brandId, isEnabled, sortOrder])
}
model BrandFieldDefinition {
id String @id @default(uuid())
brandId String
-20
View File
@@ -702,26 +702,6 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
data: { isEnabled: false },
});
}
const moduleDefinitions = [
["founder-card", "主理人介绍"],
["brand-hero", "品牌首屏"],
["trust-proof", "信任与案例"],
["offering-list", "业务提供项"],
["inquiry", "咨询入口"],
] as const;
for (const [sortOrder, [type, title]] of moduleDefinitions.entries()) {
const existing = await prisma.brandModule.findFirst({ where: { brandId, type } });
if (existing) {
await prisma.brandModule.update({
where: { id: existing.id },
data: { isEnabled: true, sortOrder, title },
});
} else {
await prisma.brandModule.create({
data: { brandId, type, title, sortOrder, source: "seed", isEnabled: true },
});
}
}
const incompleteOfferings = await prisma.offering.findMany({
where: { brandId, isEnabled: true, coverUrl: null },
select: { id: true, name: true },
+1 -1
View File
@@ -12,7 +12,7 @@ export class AdminMembershipGuard implements CanActivate {
if (request.url.startsWith("/admin/session/login")) return Promise.resolve(true);
if (!request.url.startsWith("/admin/")) return Promise.resolve(true);
if (
/^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|modules(?:\/|$)|fields(?:\/|$))/.test(
/^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
request.url,
) ||
/^\/admin\/config\/visual-template(?:\/|$)/.test(request.url)
+1 -25
View File
@@ -19,7 +19,6 @@ import {
InstallTemplateDto,
CreateOfferingDto,
UpdateOfferingDto,
UpdateModuleDto,
CreateFieldDefinitionDto,
UpdateFieldDefinitionDto,
CreateInquiryFormDto,
@@ -158,10 +157,9 @@ class AdminWorkspaceController {
@Get()
async get(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = this.requireAdmin(request).brandId;
const [brand, installations, modules, fields, offerings, forms] = await Promise.all([
const [brand, installations, fields, offerings, forms] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }),
this.prisma.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
this.prisma.brandFieldDefinition.findMany({
where: { brandId },
orderBy: { sortOrder: "asc" },
@@ -178,7 +176,6 @@ class AdminWorkspaceController {
return {
brand,
installations,
modules,
fields,
offerings,
forms,
@@ -378,27 +375,6 @@ class AdminWorkspaceController {
return this.templateWorkspace.rollback(this.requireAdmin(request).brandId);
}
@Patch("modules/:id")
async updateModule(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateModuleDto,
): Promise<unknown> {
const brandId = this.requireAdmin(request).brandId;
const item = await this.prisma.brandModule.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("品牌模块不存在");
const { config, ...fields } = body;
return this.prisma.brandModule.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Post("fields")
createField(
@Req() request: FastifyRequest,
-7
View File
@@ -157,13 +157,6 @@ export class UpdateOfferingDto {
@IsOptional() cta?: { type: string; label: string; config?: Record<string, unknown> };
}
export class UpdateModuleDto {
@IsOptional() @IsString() title?: string;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() config?: Record<string, unknown>;
}
export class CreateFieldDefinitionDto {
@IsIn(["profile", "service", "inquiry"]) scope!: string;
@IsString() @Matches(/^[a-z][a-z0-9_]*$/) key!: string;
+1 -4
View File
@@ -19,7 +19,6 @@ export interface BrandReleaseSnapshot {
templatePackageManifest?: ReturnType<typeof getTemplatePackageManifestForVisualKey> | null;
brand: Record<string, unknown> | null;
installation: Record<string, unknown> | null;
modules: unknown[];
fields: unknown[];
offerings: unknown[];
forms: unknown[];
@@ -31,14 +30,13 @@ export async function buildBrandReleaseSnapshot(
database: Prisma.TransactionClient,
brandId: string,
): Promise<BrandReleaseSnapshot> {
const [brand, installation, modules, fields, offerings, forms, trustContents, capabilities] =
const [brand, installation, fields, offerings, forms, trustContents, capabilities] =
await Promise.all([
database.brandProfile.findUnique({ where: { id: brandId } }),
database.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
}),
database.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
@@ -66,7 +64,6 @@ export async function buildBrandReleaseSnapshot(
templatePackageManifest: getTemplatePackageManifestForVisualKey(visualKey) ?? null,
brand: brand ? jsonObject(brand) : null,
installation: installation ? jsonObject(installation) : null,
modules: modules.map((item) => jsonObject(item)),
fields: fields.map((item) => jsonObject(item)),
offerings: offerings.map((item) => jsonObject(item)),
forms: forms.map((item) => jsonObject(item)),
@@ -12,12 +12,7 @@ import {
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
} from "@personal-brand/config";
import type {
RuntimeInquiryField,
RuntimeOffering,
RuntimeWorkspace,
RuntimeModule,
} from "@personal-brand/types";
import type { RuntimeInquiryField, RuntimeOffering, RuntimeWorkspace } from "@personal-brand/types";
@Controller("public/workspace")
export class PublicWorkspaceController {
@@ -42,7 +37,6 @@ export class PublicWorkspaceController {
brand: null,
template: null,
visualTemplate: null,
modules: [],
offerings: [],
inquiryForms: [],
capabilities: [],
@@ -53,9 +47,6 @@ export class PublicWorkspaceController {
};
}
const brandData = this.jsonObject(releaseSnapshot.brand);
const modulesData = this.jsonArray(releaseSnapshot.modules).filter(
(item) => this.jsonObject(item).isEnabled === true,
) as Array<Record<string, unknown>>;
const offeringsData = this.jsonArray(releaseSnapshot.offerings).filter(
(item) => this.jsonObject(item).isEnabled === true,
) as Array<Record<string, unknown>>;
@@ -120,17 +111,6 @@ export class PublicWorkspaceController {
...brandData,
...brandConfig,
};
const runtimeModules: RuntimeModule[] = modulesData.map((item) => ({
key: this.string(item.type, "custom"),
type: this.moduleType(this.string(item.type, "custom")),
version: "1.0.0",
propsSchema: `module.${this.string(item.type, "custom")}.v1`,
dataSource: this.string(item.type, "custom"),
config: this.jsonObject(item.config),
source:
item.source === "custom" ? "custom" : item.source === "template" ? "template" : "core",
schemaVersion: "1.0",
}));
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
const item = raw;
const config = this.jsonObject(item.config);
@@ -282,7 +262,6 @@ export class PublicWorkspaceController {
page: templatePackageManifest.entrypoints[tab.page] ?? tab.page,
})) ?? [],
},
modules: runtimeModules,
offerings: runtimeOfferings,
inquiryForms: formsData.map((raw) => {
const form = this.jsonObject(raw);
@@ -355,32 +334,6 @@ export class PublicWorkspaceController {
private jsonArray(value: unknown): Prisma.JsonValue[] {
return Array.isArray(value) ? (value as Prisma.JsonValue[]) : [];
}
private moduleType(value: string): RuntimeModule["type"] {
const aliases: Record<string, RuntimeModule["type"]> = {
identity: "brand-hero",
trust: "trust-proof",
offering: "offering-list",
contact: "founder-card",
};
const known: RuntimeModule["type"][] = [
"brand-hero",
"founder-card",
"trust-proof",
"offering-list",
"offering-detail",
"gallery",
"timeline",
"faq",
"contact",
"inquiry",
"records",
"custom",
];
const type = aliases[value] ?? value;
return (
known.includes(type as RuntimeModule["type"]) ? type : "custom"
) as RuntimeModule["type"];
}
private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
const known = ["text", "image-list", "timeline", "faq", "specification"] as const;
return known.includes(value as (typeof known)[number])
@@ -94,12 +94,6 @@ export class PublicTemplateController {
visual: visualTemplate,
runtime: {
schemaVersion: "1.0.0",
modules: industryTemplate.modules.map((module) => ({
key: module.key,
type: module.type,
title: module.title,
variant: visualTemplate.variants[module.type] ?? "default",
})),
capabilities: resolveCapabilities(industryTemplate.capabilities),
theme: visualTemplate.theme,
},
+3 -35
View File
@@ -85,15 +85,6 @@ export class TemplateWorkspaceService {
configSnapshot: templatePackageSnapshot as unknown as Prisma.InputJsonValue,
},
});
await tx.brandModule.createMany({
data: template.modules.map(({ type, title }, sortOrder) => ({
brandId,
type,
title,
sortOrder,
source: "template",
})),
});
await tx.brandFieldDefinition.createMany({
data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({
brandId,
@@ -118,20 +109,13 @@ export class TemplateWorkspaceService {
const installation = await this.installation(brandId);
const template = getBrandTemplate(installation.templateKey);
if (!template) throw new BadRequestException("已安装模板不存在");
const [modules, fields] = await Promise.all([
this.prisma.brandModule.findMany({ where: { brandId } }),
this.prisma.brandFieldDefinition.findMany({ where: { brandId } }),
]);
const fields = await this.prisma.brandFieldDefinition.findMany({ where: { brandId } });
return {
currentVersion: installation.templateVersion,
latestVersion: template.version,
canUpgrade: installation.templateVersion !== template.version,
canRollback:
Array.isArray(installation.previousSnapshots) && installation.previousSnapshots.length > 0,
missingModules: template.modules.filter(
(item) =>
!modules.some((current) => current.type === item.type && current.source === "template"),
),
missingFields: template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
@@ -145,27 +129,11 @@ export class TemplateWorkspaceService {
if (installation.templateVersion === template.version)
throw new BadRequestException("当前模板已经是最新版本");
return this.prisma.$transaction(async (tx) => {
const [modules, fields] = await Promise.all([
tx.brandModule.findMany({ where: { brandId } }),
tx.brandFieldDefinition.findMany({ where: { brandId } }),
]);
const addedModules = template.modules.filter(
(item) =>
!modules.some((current) => current.type === item.type && current.source === "template"),
);
const fields = await tx.brandFieldDefinition.findMany({ where: { brandId } });
const addedFields = template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
);
await tx.brandModule.createMany({
data: addedModules.map(({ type, title }, index) => ({
brandId,
type,
title,
sortOrder: modules.length + index,
source: "template",
})),
});
await tx.brandFieldDefinition.createMany({
data: addedFields.map(({ scope, key, label, type, required }, index) => ({
brandId,
@@ -189,7 +157,7 @@ export class TemplateWorkspaceService {
previousSnapshots: [...history, installation.configSnapshot],
},
});
return { installation: updated, addedModules, addedFields };
return { installation: updated, addedFields };
});
}
async rollback(brandId: string) {
+2 -17
View File
@@ -320,7 +320,6 @@ test("health and public content are available without authentication", async ()
const runtime = JSON.parse(workspace.body);
assert.equal(runtime.schemaVersion, "1.0.0");
assert.ok(Array.isArray(runtime.navigation.tabs));
assert.ok(Array.isArray(runtime.modules));
assert.ok(Array.isArray(runtime.offerings));
assert.ok(Array.isArray(runtime.inquiryForms));
assert.ok(Array.isArray(runtime.capabilities));
@@ -675,7 +674,6 @@ test("admin can install doors industry template through the shared runtime contr
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const login = await request("/admin/session/login", {
method: "POST",
@@ -702,7 +700,6 @@ test("admin can install doors industry template through the shared runtime contr
assert.equal(JSON.parse(samplePreview.body).templateKey, "doors");
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
}
});
@@ -770,7 +767,6 @@ test("admin can install a template and public workspace exposes enabled configur
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const login = await request("/admin/session/login", {
method: "POST",
@@ -839,14 +835,13 @@ test("admin can install a template and public workspace exposes enabled configur
const workspaceBody = JSON.parse(publicWorkspace.body);
assert.equal(workspaceBody.contractVersion, "1.0");
assert.equal(workspaceBody.template.key, "food");
assert.ok(workspaceBody.modules.length > 0);
assert.equal("templateContent" in workspaceBody, false);
assert.equal("runtimeModules" in workspaceBody, false);
assert.equal("runtimeCapabilities" in workspaceBody, false);
assert.equal("fields" in workspaceBody, false);
assert.equal("trustContent" in workspaceBody, false);
assert.equal("inquiryForm" in workspaceBody, false);
assert.equal(workspaceBody.modules[0].schemaVersion, "1.0");
assert.equal("modules" in workspaceBody, false);
assert.ok(workspaceBody.inquiryForms.length > 0);
const conflict = await request("/admin/workspace/install", {
method: "POST",
@@ -856,14 +851,12 @@ test("admin can install a template and public workspace exposes enabled configur
assert.equal(conflict.statusCode, 400);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
}
});
test("admin can customize workspace modules and fields with brand isolation", async () => {
test("admin can customize workspace fields with brand isolation", async () => {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const login = await request("/admin/session/login", {
method: "POST",
@@ -879,19 +872,12 @@ test("admin can customize workspace modules and fields with brand isolation", as
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
const moduleId = JSON.parse(workspace.body).modules[0].id;
const invalidField = await request("/admin/workspace/fields", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { scope: "unknown", key: "Bad-Key", label: "非法字段", type: "text" },
});
assert.equal(invalidField.statusCode, 400);
const updatedModule = await request(`/admin/workspace/modules/${moduleId}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { title: "我的品牌介绍", isEnabled: false },
});
assert.equal(updatedModule.statusCode, 200);
const createdField = await request("/admin/workspace/fields", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -919,7 +905,6 @@ test("admin can customize workspace modules and fields with brand isolation", as
assert.equal(deletedField.statusCode, 200);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
}
});