refactor: 收口多品牌 API 控制器边界
This commit is contained in:
1 parent
98e66a60de
commit
178ffc2c11
5 files changed
+531
-493
No files matched your search
@@ -0,0 +1,279 @@
|
||||
import { BadRequestException, Controller, Get, NotFoundException, Query } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
resolveCapabilities,
|
||||
capabilityPlugins,
|
||||
} from "@personal-brand/config";
|
||||
import type {
|
||||
RuntimeInquiryField,
|
||||
RuntimeOffering,
|
||||
RuntimeWorkspace,
|
||||
RuntimeModule,
|
||||
} from "@personal-brand/types";
|
||||
|
||||
export class PublicWorkspaceController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
private readonly cache = new Map<string, { expiresAt: number; value: unknown }>();
|
||||
@Get()
|
||||
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const configuredId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
const selected = brandSlug
|
||||
? await this.prisma.brandProfile.findUnique({
|
||||
where: { slug: brandSlug },
|
||||
select: { id: true },
|
||||
})
|
||||
: null;
|
||||
if (brandSlug && !selected) throw new NotFoundException("品牌不存在");
|
||||
const brandId = selected?.id ?? configuredId;
|
||||
const cached = process.env.NODE_ENV === "test" ? undefined : this.cache.get(brandId);
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
||||
const [
|
||||
brand,
|
||||
modules,
|
||||
fields,
|
||||
offerings,
|
||||
inquiryForms,
|
||||
installation,
|
||||
capabilityInstallations,
|
||||
trustContents,
|
||||
] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
this.prisma.brandModule.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.brandFieldDefinition.findMany({
|
||||
where: { brandId, isVisible: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.offering.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.inquiryForm.findMany({
|
||||
where: {
|
||||
brandId,
|
||||
isEnabled: true,
|
||||
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
}),
|
||||
this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
}),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
this.prisma.trustContent.findMany({
|
||||
where: { brandId, isPublished: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
]);
|
||||
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
|
||||
const template = getBrandTemplate(templateKey);
|
||||
const runtimeCapabilities = capabilityInstallations.length
|
||||
? capabilityInstallations.map((item) => ({
|
||||
key: item.capabilityKey,
|
||||
version: item.capabilityVersion,
|
||||
status: item.status as "enabled" | "disabled" | "degraded",
|
||||
config:
|
||||
item.config && typeof item.config === "object" && !Array.isArray(item.config)
|
||||
? (item.config as Record<string, unknown>)
|
||||
: {},
|
||||
}))
|
||||
: template
|
||||
? resolveCapabilities(template.capabilities).map((item) => ({
|
||||
key: item.key,
|
||||
version: item.version,
|
||||
status: "enabled" as const,
|
||||
config: {},
|
||||
}))
|
||||
: [];
|
||||
const brandConfig =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const visualTemplateKey =
|
||||
typeof brandConfig.visualTemplateKey === "string"
|
||||
? brandConfig.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
const visualTemplate =
|
||||
getVisualTemplate(visualTemplateKey) ?? getVisualTemplate("linjing-editorial");
|
||||
const runtimeModules: RuntimeModule[] = modules.map((module) => ({
|
||||
key: module.type,
|
||||
type: this.moduleType(module.type),
|
||||
version: "1.0.0",
|
||||
propsSchema: `module.${module.type}.v1`,
|
||||
dataSource: module.type,
|
||||
config: this.jsonObject(module.config),
|
||||
source:
|
||||
module.source === "custom" ? "custom" : module.source === "template" ? "template" : "core",
|
||||
schemaVersion: "1.0",
|
||||
}));
|
||||
const runtimeOfferings: RuntimeOffering[] = offerings.map((item) => {
|
||||
const config = this.jsonObject(item.config);
|
||||
const sections = Array.isArray(config.sections) ? config.sections : [];
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
summary: item.summary ?? item.description ?? "",
|
||||
enabled: item.isEnabled,
|
||||
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
|
||||
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
|
||||
sections: sections
|
||||
.filter((section): section is Record<string, unknown> =>
|
||||
Boolean(section && typeof section === "object"),
|
||||
)
|
||||
.map((section) => ({
|
||||
key: typeof section.key === "string" ? section.key : "section",
|
||||
type: this.sectionType(section.type),
|
||||
config: this.jsonObject(section.config),
|
||||
})),
|
||||
};
|
||||
});
|
||||
const toInquiryFields = (snapshot: Prisma.JsonValue): RuntimeInquiryField[] =>
|
||||
this.jsonArray(snapshot).flatMap((field) => {
|
||||
if (!field || typeof field !== "object") return [];
|
||||
const value = field as Record<string, unknown>;
|
||||
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
|
||||
const type = [
|
||||
"text",
|
||||
"tel",
|
||||
"number",
|
||||
"select",
|
||||
"radio",
|
||||
"checkbox",
|
||||
"textarea",
|
||||
"date",
|
||||
].includes(String(value.type))
|
||||
? (value.type as RuntimeInquiryField["type"])
|
||||
: "text";
|
||||
const options = Array.isArray(value.options)
|
||||
? value.options.flatMap((option) => {
|
||||
if (!option || typeof option !== "object") return [];
|
||||
const item = option as Record<string, unknown>;
|
||||
return typeof item.label === "string" && typeof item.value === "string"
|
||||
? [{ label: item.label, value: item.value }]
|
||||
: [];
|
||||
})
|
||||
: undefined;
|
||||
return [
|
||||
{
|
||||
key: value.key,
|
||||
label: value.label,
|
||||
type,
|
||||
required: value.required === true,
|
||||
...(options?.length ? { options } : {}),
|
||||
},
|
||||
];
|
||||
});
|
||||
const inquiryForm = inquiryForms[0] ?? null;
|
||||
const runtimeWorkspace: RuntimeWorkspace = {
|
||||
schemaVersion: "1.0.0",
|
||||
brand: (brand ?? {}) as Record<string, unknown>,
|
||||
navigation: {
|
||||
tabs: [
|
||||
{ key: "home", label: "首页", page: "pages/index/index" },
|
||||
{ key: "offerings", label: "案例与体系", page: "pages/services/index" },
|
||||
{ key: "profile", label: "主理人与我", page: "pages/bookings/index" },
|
||||
],
|
||||
},
|
||||
modules: runtimeModules,
|
||||
offerings: runtimeOfferings,
|
||||
inquiryForms: inquiryForms.map((form) => ({
|
||||
key: form.id,
|
||||
version: String(form.version),
|
||||
purpose: this.formPurpose(form.purpose),
|
||||
target: form.targetType === "offering" ? "offering" : "brand",
|
||||
...(form.offeringId ? { targetId: form.offeringId } : {}),
|
||||
submissionAction: this.submissionAction(form.submissionAction),
|
||||
fields: toInquiryFields(form.fieldsSnapshot),
|
||||
})),
|
||||
capabilities: runtimeCapabilities,
|
||||
plugins: runtimeCapabilities
|
||||
.filter((capability) => capability.status === "enabled")
|
||||
.map((capability) => capability.key)
|
||||
.map((key) => capabilityPlugins[key as keyof typeof capabilityPlugins])
|
||||
.filter(Boolean)
|
||||
.map((plugin) => ({ ...plugin, status: "enabled" as const, config: {} })),
|
||||
theme: visualTemplate?.theme ?? {
|
||||
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
|
||||
},
|
||||
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
|
||||
};
|
||||
const response = {
|
||||
...runtimeWorkspace,
|
||||
contractVersion: "1.0",
|
||||
brand,
|
||||
template: template
|
||||
? {
|
||||
key: template.key,
|
||||
version: installation?.templateVersion ?? template.version,
|
||||
name: template.name,
|
||||
}
|
||||
: null,
|
||||
visualTemplate: visualTemplate
|
||||
? {
|
||||
key: visualTemplate.key,
|
||||
version: visualTemplate.version,
|
||||
name: visualTemplate.name,
|
||||
variants: visualTemplate.variants,
|
||||
}
|
||||
: null,
|
||||
capabilities: runtimeCapabilities,
|
||||
runtimeCapabilities,
|
||||
modules,
|
||||
runtimeModules,
|
||||
fields,
|
||||
offerings,
|
||||
trustContent: trustContents,
|
||||
inquiryForm,
|
||||
};
|
||||
if (process.env.NODE_ENV !== "test")
|
||||
this.cache.set(brandId, { expiresAt: Date.now() + 30_000, value: response });
|
||||
return response;
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
private jsonArray(value: unknown): Prisma.JsonValue[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
private moduleType(value: string): RuntimeModule["type"] {
|
||||
const known: RuntimeModule["type"][] = [
|
||||
"brand-hero",
|
||||
"founder-card",
|
||||
"trust-proof",
|
||||
"offering-list",
|
||||
"offering-detail",
|
||||
"gallery",
|
||||
"timeline",
|
||||
"faq",
|
||||
"contact",
|
||||
"inquiry",
|
||||
"records",
|
||||
"custom",
|
||||
];
|
||||
return (
|
||||
known.includes(value as RuntimeModule["type"]) ? value : "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])
|
||||
? (value as (typeof known)[number])
|
||||
: "text";
|
||||
}
|
||||
private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
|
||||
return value === "booking" || value === "quote-request" ? value : "inquiry";
|
||||
}
|
||||
private submissionAction(
|
||||
value: string,
|
||||
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
|
||||
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user