refactor: 收口多品牌 API 控制器边界

This commit is contained in:
que01 committed 2026-09-23 12:29:20 +08:00
1 parent 98e66a60de
commit 178ffc2c11
5 files changed
+531 -493

No files matched your search

+2 -489
View File
@@ -36,6 +36,8 @@ import {
visualTemplates,
} from "@personal-brand/config";
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
import { PublicWorkspaceController } from "./modules/public/public-workspace.controller.js";
import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { AdminAccessService } from "./admin-access.service.js";
import { AdminMembershipGuard } from "./admin-membership.guard.js";
@@ -66,271 +68,6 @@ export class HealthController {
}
}
@Controller("public/workspace")
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";
}
}
@Controller("public/offerings")
export class PublicOfferingController {
constructor(private readonly prisma: PrismaService) {}
@@ -518,230 +255,6 @@ export class CustomerInquirySubmissionController {
}
}
@Controller("admin/config")
export class AdminConfigController {
constructor(private readonly prisma: PrismaService) {}
private brandId(request?: FastifyRequest): string {
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
return identity.brandId;
}
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
@Get("brand")
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } });
}
@Patch("brand")
async updateBrand(
@Req() request: FastifyRequest,
@Body() body: UpdateBrandDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
const current = await this.prisma.brandProfile.findUnique({
where: { id: this.brandId(request) },
select: { config: true },
});
const currentConfig =
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
? (current.config as Record<string, unknown>)
: {};
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId: this.brandId(request) },
});
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 ?? "linjing-editorial",
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: this.brandId(request) },
data: {
...fields,
...(nextConfig ? { config: nextConfig as Prisma.InputJsonValue } : {}),
},
});
}
@Get("visual-template/history")
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.prisma.brandTemplateInstallation
.findFirst({ where: { brandId: this.brandId(request) }, select: { previousSnapshots: true } })
.then((installation) => ({
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
}));
}
@Post("visual-template/rollback")
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
const brandId = this.brandId(request);
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
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,
} as Prisma.InputJsonValue,
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
}
@Get("visual-template/preview")
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.prisma.brandProfile
.findUnique({ where: { id: this.brandId(request) }, select: { config: true } })
.then((brand) => {
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: "linjing-editorial";
const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial");
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: ["linjing-editorial", "minimal-neutral"],
};
});
}
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.trustContent.findMany({
where: { brandId: this.brandId(request) },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
@Post("trust-content")
createTrustContent(
@Req() request: FastifyRequest,
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId: this.brandId(request),
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Patch("trust-content/:id")
async updateTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Delete("trust-content/:id")
async deleteTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
}
@Module({
controllers: [
HealthController,
@@ -0,0 +1,243 @@
import {
BadRequestException,
Body,
Controller,
Delete,
ForbiddenException,
Get,
Param,
Patch,
Post,
Req,
UnauthorizedException,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { readIdentity } from "../../auth.js";
import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "../../admin.dto.js";
import { getVisualTemplate } from "@personal-brand/config";
@Controller("admin/config")
export class AdminConfigController {
constructor(private readonly prisma: PrismaService) {}
private brandId(request?: FastifyRequest): string {
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
return identity.brandId;
}
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
@Get("brand")
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } });
}
@Patch("brand")
async updateBrand(
@Req() request: FastifyRequest,
@Body() body: UpdateBrandDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
const current = await this.prisma.brandProfile.findUnique({
where: { id: this.brandId(request) },
select: { config: true },
});
const currentConfig =
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
? (current.config as Record<string, unknown>)
: {};
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId: this.brandId(request) },
});
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 ?? "linjing-editorial",
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: this.brandId(request) },
data: {
...fields,
...(nextConfig ? { config: nextConfig as Prisma.InputJsonValue } : {}),
},
});
}
@Get("visual-template/history")
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.prisma.brandTemplateInstallation
.findFirst({ where: { brandId: this.brandId(request) }, select: { previousSnapshots: true } })
.then((installation) => ({
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
}));
}
@Post("visual-template/rollback")
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
const brandId = this.brandId(request);
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
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,
} as Prisma.InputJsonValue,
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
}
@Get("visual-template/preview")
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.prisma.brandProfile
.findUnique({ where: { id: this.brandId(request) }, select: { config: true } })
.then((brand) => {
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: "linjing-editorial";
const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial");
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: ["linjing-editorial", "minimal-neutral"],
};
});
}
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.trustContent.findMany({
where: { brandId: this.brandId(request) },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
@Post("trust-content")
createTrustContent(
@Req() request: FastifyRequest,
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId: this.brandId(request),
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Patch("trust-content/:id")
async updateTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Delete("trust-content/:id")
async deleteTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
}
@@ -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";
}
}