refactor: 收口多品牌 API 控制器边界
This commit is contained in:
1 parent
98e66a60de
commit
178ffc2c11
5 files changed
+531
-493
No files matched your search
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
- 任务:多品牌后台与 API 架构收口
|
- 任务:多品牌后台与 API 架构收口
|
||||||
- 形态:epic
|
- 形态:epic
|
||||||
- 进度:1/3
|
- 进度:3/3
|
||||||
- 当前:API Controller 拆分(已完成 session、customer booking、admin booking;继续拆分 public 和 admin config)
|
- 当前:已完成多品牌工作区、API Controller 拆分与全量回归收口
|
||||||
- 真相文件:`SUBTASKS.csv`
|
- 真相文件:`SUBTASKS.csv`
|
||||||
|
|
||||||
## 已完成
|
## 已完成
|
||||||
@@ -19,3 +19,6 @@
|
|||||||
- 新增 `GET /admin/brands` 和 `POST /admin/brands/:brandId/switch`,切换由 membership 服务端校验。
|
- 新增 `GET /admin/brands` 和 `POST /admin/brands/:brandId/switch`,切换由 membership 服务端校验。
|
||||||
- seed 已增加第二个独立品牌 `林境门作`(slug:`linjing-doors`),并绑定同一管理员的独立 membership。
|
- seed 已增加第二个独立品牌 `林境门作`(slug:`linjing-doors`),并绑定同一管理员的独立 membership。
|
||||||
- 修复多品牌出现后 `findFirst()` 导致默认品牌串线的问题,默认公开品牌和客户会话现在使用 `DEFAULT_BRAND_ID`。
|
- 修复多品牌出现后 `findFirst()` 导致默认品牌串线的问题,默认公开品牌和客户会话现在使用 `DEFAULT_BRAND_ID`。
|
||||||
|
- `PublicWorkspaceController` 已迁移到 `modules/public/public-workspace.controller.ts`。
|
||||||
|
- `AdminConfigController` 已迁移到 `modules/admin/admin-config.controller.ts`,并保留 DTO runtime validation。
|
||||||
|
- API 集成测试 27/27 通过;Admin production build、miniapp fixture、visual fixture 全部通过。
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes
|
id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes
|
||||||
1,当前品牌工作区语义,single-full,,DONE,tasks/admin-context,后台明确当前品牌并保持 membership 隔离,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/api test:integration,已完成
|
1,当前品牌工作区语义,single-full,,DONE,tasks/admin-context,后台明确当前品牌并保持 membership 隔离,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/api test:integration,已完成
|
||||||
2,API Controller 拆分,single-full,1,IN_PROGRESS,tasks/api-split,main.ts 仅保留装配和跨模块基础代码,pnpm --filter @personal-brand/api typecheck && pnpm --filter @personal-brand/api test:integration,已拆分 session、customer booking、admin booking;public 和 admin config 仍待拆分
|
2,API Controller 拆分,single-full,1,DONE,tasks/api-split,main.ts 仅保留装配和跨模块基础代码,pnpm --filter @personal-brand/api typecheck && pnpm --filter @personal-brand/api test:integration,已完成 session、booking、public workspace、admin config 等控制器拆分
|
||||||
3,架构回归收口,single-full,2,TODO,tasks/regression,Admin 和 miniapp 回归全部通过,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/miniapp test:fixture,
|
3,架构回归收口,single-full,2,DONE,tasks/regression,Admin 和 miniapp 回归全部通过,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/miniapp test:fixture,API 27/27;Admin build;miniapp fixture 与 visual fixture 全部通过
|
||||||
|
+2
-489
@@ -36,6 +36,8 @@ import {
|
|||||||
visualTemplates,
|
visualTemplates,
|
||||||
} from "@personal-brand/config";
|
} from "@personal-brand/config";
|
||||||
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
|
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 { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||||
import { AdminAccessService } from "./admin-access.service.js";
|
import { AdminAccessService } from "./admin-access.service.js";
|
||||||
import { AdminMembershipGuard } from "./admin-membership.guard.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")
|
@Controller("public/offerings")
|
||||||
export class PublicOfferingController {
|
export class PublicOfferingController {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
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({
|
@Module({
|
||||||
controllers: [
|
controllers: [
|
||||||
HealthController,
|
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";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user