From 98e66a60dea917db82b10eb97ac27b5a893048e4 Mon Sep 17 00:00:00 2001 From: que01 Date: Wed, 23 Sep 2026 12:15:36 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=88=86=E7=A6=BB=20API=20?= =?UTF-8?q?=E5=90=AF=E5=8A=A8=E5=85=A5=E5=8F=A3=E4=B8=8E=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tenant-architecture-epic/PROGRESS.md | 1 + apps/api/src/app.module.ts | 786 ++++++++++++++++++ apps/api/src/main.ts | 785 +---------------- 3 files changed, 790 insertions(+), 782 deletions(-) create mode 100644 apps/api/src/app.module.ts diff --git a/.codex-tasks/tenant-architecture-epic/PROGRESS.md b/.codex-tasks/tenant-architecture-epic/PROGRESS.md index 1af33b5..4a00dd5 100644 --- a/.codex-tasks/tenant-architecture-epic/PROGRESS.md +++ b/.codex-tasks/tenant-architecture-epic/PROGRESS.md @@ -15,6 +15,7 @@ - `AdminBookingController` 已迁移到 `modules/admin/admin-booking.controller.ts`。 - `CustomerBookingController` 已迁移到 `modules/customer/customer-booking.controller.ts`。 - `PublicController`、`PublicTrustContentController`、`PublicTemplateController` 已迁移到 `modules/public/public.controller.ts`。 +- 启动入口已与应用模块分离:`main.ts` 仅保留 bootstrap,`app.module.ts` 负责 Nest 装配。 - 新增 `GET /admin/brands` 和 `POST /admin/brands/:brandId/switch`,切换由 membership 服务端校验。 - seed 已增加第二个独立品牌 `林境门作`(slug:`linjing-doors`),并绑定同一管理员的独立 membership。 - 修复多品牌出现后 `findFirst()` 导致默认品牌串线的问题,默认公开品牌和客户会话现在使用 `DEFAULT_BRAND_ID`。 diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts new file mode 100644 index 0000000..f80970f --- /dev/null +++ b/apps/api/src/app.module.ts @@ -0,0 +1,786 @@ +import "reflect-metadata"; +import { + BadRequestException, + NotFoundException, + UnauthorizedException, + ForbiddenException, + Body, + Controller, + Delete, + Get, + Module, + Param, + Post, + Patch, + Query, + Req, + ValidationPipe, +} from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import type { NestFastifyApplication } from "@nestjs/platform-fastify"; +import { PrismaService } from "./prisma.service.js"; +import { WechatAuthService } from "./wechat-auth.js"; +import { BookingService } from "./booking.service.js"; +import { CreateInquirySubmissionDto } from "./booking.dto.js"; +import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "./admin.dto.js"; +import { AdminAuthService } from "./admin-auth.service.js"; +import type { FastifyRequest } from "fastify"; +import { readIdentity } from "./auth.js"; +import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js"; +import { + brandTemplates, + getBrandTemplate, + getVisualTemplate, + resolveCapabilities, + capabilityPlugins, + visualTemplates, +} from "@personal-brand/config"; +import { AdminWorkspaceController } from "./admin-workspace.controller.js"; +import { TemplateWorkspaceService } from "./template-workspace.service.js"; +import { AdminAccessService } from "./admin-access.service.js"; +import { AdminMembershipGuard } from "./admin-membership.guard.js"; +import { + CustomerSessionController, + AdminSessionController, +} from "./modules/session/session.controller.js"; +import { AdminBookingController } from "./modules/admin/admin-booking.controller.js"; +import { CustomerBookingController } from "./modules/customer/customer-booking.controller.js"; +import { TenantController } from "./modules/tenant/tenant.controller.js"; +import { + PublicController, + PublicTemplateController, + PublicTrustContentController, +} from "./modules/public/public.controller.js"; +import type { + RuntimeInquiryField, + RuntimeOffering, + RuntimeWorkspace, + RuntimeModule, +} from "@personal-brand/types"; + +@Controller("health") +export class HealthController { + @Get() + check(): { status: string; service: string } { + return { status: "ok", service: "personal-brand-api" }; + } +} + +@Controller("public/workspace") +export class PublicWorkspaceController { + constructor(private readonly prisma: PrismaService) {} + private readonly cache = new Map(); + @Get() + async get(@Query("brandSlug") brandSlug?: string): Promise { + 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) + : {}, + })) + : 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) + : {}; + 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 => + 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; + 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; + 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, + 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 { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } + 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) {} + @Get() + async list(): Promise { + const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; + const items = await this.prisma.offering.findMany({ + where: { brandId, isEnabled: true }, + orderBy: { sortOrder: "asc" }, + include: { + inquiryForms: { + where: { isEnabled: true }, + orderBy: { updatedAt: "desc" }, + select: { id: true, name: true, purpose: true, targetType: true, version: true }, + }, + }, + }); + return items.map((item) => this.present(item)); + } + @Get(":id") + async get(@Param("id") id: string): Promise { + const item = await this.prisma.offering.findFirst({ + where: { + id, + brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001", + isEnabled: true, + }, + include: { + inquiryForms: { + where: { isEnabled: true }, + orderBy: { updatedAt: "desc" }, + select: { id: true, name: true, purpose: true, targetType: true, version: true }, + }, + }, + }); + if (!item) throw new BadRequestException("业务提供项不存在"); + return this.present(item); + } + private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown { + const config = (item.config ?? {}) as Record; + return { + ...item, + sections: config.sections ?? [], + media: config.media ?? [], + cta: config.cta ?? null, + }; + } +} + +@Controller("public/inquiry-forms") +export class PublicInquiryFormController { + constructor(private readonly prisma: PrismaService) {} + @Get(":id") + async get(@Param("id") id: string): Promise { + const form = await this.prisma.inquiryForm.findFirst({ + where: { + id, + brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001", + isEnabled: true, + OR: [{ offeringId: null }, { offering: { isEnabled: true } }], + }, + }); + if (!form) throw new BadRequestException("咨询表单不存在"); + return form; + } +} + +@Controller("customer/inquiry-submissions") +export class CustomerInquirySubmissionController { + constructor(private readonly prisma: PrismaService) {} + private present(submission: T) { + const { + customerSubject: _customerSubject, + adminNote: _adminNote, + ...publicSubmission + } = submission; + void _customerSubject; + void _adminNote; + return publicSubmission; + } + private identity(request: FastifyRequest): ReturnType { + const token = request.headers.authorization?.replace(/^Bearer\s+/i, ""); + if (!token) throw new UnauthorizedException("缺少客户登录态"); + try { + const identity = readIdentity(token); + if (identity.role !== "customer") throw new ForbiddenException("无客户权限"); + return identity; + } catch (error) { + if (error instanceof ForbiddenException) throw error; + throw new UnauthorizedException("客户登录态无效或已过期"); + } + } + + @Get() + async list(@Req() request: FastifyRequest): Promise { + const identity = this.identity(request); + const submissions = await this.prisma.inquirySubmission.findMany({ + where: { brandId: identity.brandId, customerSubject: identity.subject }, + orderBy: { createdAt: "desc" }, + include: { + inquiryForm: { select: { name: true, purpose: true } }, + offering: { select: { id: true, name: true } }, + statusHistory: { + select: { fromStatus: true, toStatus: true, createdAt: true }, + orderBy: { createdAt: "asc" }, + }, + }, + }); + return submissions.map((submission) => this.present(submission)); + } + + @Get(":id") + async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise { + const identity = this.identity(request); + const submission = await this.prisma.inquirySubmission.findFirst({ + where: { id, brandId: identity.brandId, customerSubject: identity.subject }, + include: { + inquiryForm: { select: { name: true, purpose: true } }, + offering: { select: { id: true, name: true } }, + statusHistory: { + select: { fromStatus: true, toStatus: true, createdAt: true }, + orderBy: { createdAt: "asc" }, + }, + }, + }); + if (!submission) throw new NotFoundException("咨询记录不存在"); + return this.present(submission); + } + + @Post() + async create( + @Req() request: FastifyRequest, + @Body() body: CreateInquirySubmissionDto, + ): Promise { + const identity = this.identity(request); + const form = await this.prisma.inquiryForm.findFirst({ + where: { + id: body.formId, + brandId: identity.brandId, + isEnabled: true, + OR: [{ offeringId: null }, { offering: { isEnabled: true } }], + }, + }); + if (!form) throw new BadRequestException("咨询表单不存在"); + const capabilityKey = form.purpose === "quote-request" ? "quote-request" : "inquiry"; + const capability = await this.prisma.capabilityInstallation.findUnique({ + where: { + brandId_capabilityKey: { brandId: identity.brandId, capabilityKey }, + }, + }); + if (capability && capability.status !== "enabled") + throw new BadRequestException("当前咨询能力不可用"); + const fields = Array.isArray(form.fieldsSnapshot) + ? (form.fieldsSnapshot as Array>) + : []; + for (const field of fields) { + const key = typeof field.key === "string" ? field.key : ""; + const value = body.values[key]; + const empty = value === undefined || value === null || value === ""; + if (field.required === true && empty) + throw new BadRequestException(`${String(field.label ?? key)}不能为空`); + if (empty) continue; + if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(String(value))) + throw new BadRequestException(`${String(field.label ?? key)}格式不正确`); + if (field.type === "number" && !Number.isFinite(Number(value))) + throw new BadRequestException(`${String(field.label ?? key)}必须是数字`); + } + const allowedKeys = new Set(fields.map((field) => String(field.key))); + const values = Object.fromEntries( + Object.entries(body.values).filter(([key]) => allowedKeys.has(key)), + ); + const submission = await this.prisma.inquirySubmission.create({ + data: { + brandId: identity.brandId, + customerSubject: identity.subject, + inquiryFormId: form.id, + offeringId: form.offeringId, + formVersion: form.version, + fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue, + values: values as Prisma.InputJsonValue, + activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])), + }, + }); + return this.present(submission); + } +} + +@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 { + this.requireAdmin(request); + return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } }); + } + @Patch("brand") + async updateBrand( + @Req() request: FastifyRequest, + @Body() body: UpdateBrandDto, + ): Promise { + 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) + : {}; + 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 { + 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) + : {}; + 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) + : {}; + 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 { + 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 { + 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 { + 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 { + 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, + PublicController, + PublicTrustContentController, + PublicTemplateController, + PublicWorkspaceController, + PublicOfferingController, + PublicInquiryFormController, + CustomerInquirySubmissionController, + AdminWorkspaceController, + CustomerSessionController, + AdminSessionController, + CustomerBookingController, + TenantController, + AdminBookingController, + AdminConfigController, + ], + providers: [ + PrismaService, + WechatAuthService, + BookingService, + AdminAuthService, + TemplateWorkspaceService, + AdminAccessService, + AdminMembershipGuard, + ], + exports: [PrismaService, WechatAuthService], +}) +export class AppModule {} + +export function configureApp(app: NestFastifyApplication): void { + app.useGlobalGuards(app.get(AdminMembershipGuard)); + app.useGlobalPipes( + new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }), + ); + app.useGlobalFilters(new ApiExceptionFilter()); + const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, ""); + if (apiPrefix) app.setGlobalPrefix(apiPrefix); + app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware())); + app.enableCors(); +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 6119543..8dc0d93 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -1,791 +1,12 @@ import "reflect-metadata"; -import { - BadRequestException, - NotFoundException, - UnauthorizedException, - ForbiddenException, - Body, - Controller, - Delete, - Get, - Module, - Param, - Post, - Patch, - Query, - Req, - ValidationPipe, -} from "@nestjs/common"; import { NestFactory } from "@nestjs/core"; -import { Prisma } from "@prisma/client"; -import { FastifyAdapter } from "@nestjs/platform-fastify"; import type { NestFastifyApplication } from "@nestjs/platform-fastify"; -import { PrismaService } from "./prisma.service.js"; -import { WechatAuthService } from "./wechat-auth.js"; -import { BookingService } from "./booking.service.js"; -import { CreateInquirySubmissionDto } from "./booking.dto.js"; -import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "./admin.dto.js"; -import { AdminAuthService } from "./admin-auth.service.js"; -import type { FastifyRequest } from "fastify"; -import { readIdentity } from "./auth.js"; -import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js"; -import { - brandTemplates, - getBrandTemplate, - getVisualTemplate, - resolveCapabilities, - capabilityPlugins, - visualTemplates, -} from "@personal-brand/config"; -import { AdminWorkspaceController } from "./admin-workspace.controller.js"; -import { TemplateWorkspaceService } from "./template-workspace.service.js"; -import { AdminAccessService } from "./admin-access.service.js"; -import { AdminMembershipGuard } from "./admin-membership.guard.js"; -import { - CustomerSessionController, - AdminSessionController, -} from "./modules/session/session.controller.js"; -import { AdminBookingController } from "./modules/admin/admin-booking.controller.js"; -import { CustomerBookingController } from "./modules/customer/customer-booking.controller.js"; -import { TenantController } from "./modules/tenant/tenant.controller.js"; -import { - PublicController, - PublicTemplateController, - PublicTrustContentController, -} from "./modules/public/public.controller.js"; -import type { - RuntimeInquiryField, - RuntimeOffering, - RuntimeWorkspace, - RuntimeModule, -} from "@personal-brand/types"; - -@Controller("health") -export class HealthController { - @Get() - check(): { status: string; service: string } { - return { status: "ok", service: "personal-brand-api" }; - } -} - -@Controller("public/workspace") -export class PublicWorkspaceController { - constructor(private readonly prisma: PrismaService) {} - private readonly cache = new Map(); - @Get() - async get(@Query("brandSlug") brandSlug?: string): Promise { - 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) - : {}, - })) - : 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) - : {}; - 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 => - 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; - 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; - 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, - 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 { - return value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : {}; - } - 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) {} - @Get() - async list(): Promise { - const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; - const items = await this.prisma.offering.findMany({ - where: { brandId, isEnabled: true }, - orderBy: { sortOrder: "asc" }, - include: { - inquiryForms: { - where: { isEnabled: true }, - orderBy: { updatedAt: "desc" }, - select: { id: true, name: true, purpose: true, targetType: true, version: true }, - }, - }, - }); - return items.map((item) => this.present(item)); - } - @Get(":id") - async get(@Param("id") id: string): Promise { - const item = await this.prisma.offering.findFirst({ - where: { - id, - brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001", - isEnabled: true, - }, - include: { - inquiryForms: { - where: { isEnabled: true }, - orderBy: { updatedAt: "desc" }, - select: { id: true, name: true, purpose: true, targetType: true, version: true }, - }, - }, - }); - if (!item) throw new BadRequestException("业务提供项不存在"); - return this.present(item); - } - private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown { - const config = (item.config ?? {}) as Record; - return { - ...item, - sections: config.sections ?? [], - media: config.media ?? [], - cta: config.cta ?? null, - }; - } -} - -@Controller("public/inquiry-forms") -export class PublicInquiryFormController { - constructor(private readonly prisma: PrismaService) {} - @Get(":id") - async get(@Param("id") id: string): Promise { - const form = await this.prisma.inquiryForm.findFirst({ - where: { - id, - brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001", - isEnabled: true, - OR: [{ offeringId: null }, { offering: { isEnabled: true } }], - }, - }); - if (!form) throw new BadRequestException("咨询表单不存在"); - return form; - } -} - -@Controller("customer/inquiry-submissions") -export class CustomerInquirySubmissionController { - constructor(private readonly prisma: PrismaService) {} - private present(submission: T) { - const { - customerSubject: _customerSubject, - adminNote: _adminNote, - ...publicSubmission - } = submission; - void _customerSubject; - void _adminNote; - return publicSubmission; - } - private identity(request: FastifyRequest): ReturnType { - const token = request.headers.authorization?.replace(/^Bearer\s+/i, ""); - if (!token) throw new UnauthorizedException("缺少客户登录态"); - try { - const identity = readIdentity(token); - if (identity.role !== "customer") throw new ForbiddenException("无客户权限"); - return identity; - } catch (error) { - if (error instanceof ForbiddenException) throw error; - throw new UnauthorizedException("客户登录态无效或已过期"); - } - } - - @Get() - async list(@Req() request: FastifyRequest): Promise { - const identity = this.identity(request); - const submissions = await this.prisma.inquirySubmission.findMany({ - where: { brandId: identity.brandId, customerSubject: identity.subject }, - orderBy: { createdAt: "desc" }, - include: { - inquiryForm: { select: { name: true, purpose: true } }, - offering: { select: { id: true, name: true } }, - statusHistory: { - select: { fromStatus: true, toStatus: true, createdAt: true }, - orderBy: { createdAt: "asc" }, - }, - }, - }); - return submissions.map((submission) => this.present(submission)); - } - - @Get(":id") - async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - const identity = this.identity(request); - const submission = await this.prisma.inquirySubmission.findFirst({ - where: { id, brandId: identity.brandId, customerSubject: identity.subject }, - include: { - inquiryForm: { select: { name: true, purpose: true } }, - offering: { select: { id: true, name: true } }, - statusHistory: { - select: { fromStatus: true, toStatus: true, createdAt: true }, - orderBy: { createdAt: "asc" }, - }, - }, - }); - if (!submission) throw new NotFoundException("咨询记录不存在"); - return this.present(submission); - } - - @Post() - async create( - @Req() request: FastifyRequest, - @Body() body: CreateInquirySubmissionDto, - ): Promise { - const identity = this.identity(request); - const form = await this.prisma.inquiryForm.findFirst({ - where: { - id: body.formId, - brandId: identity.brandId, - isEnabled: true, - OR: [{ offeringId: null }, { offering: { isEnabled: true } }], - }, - }); - if (!form) throw new BadRequestException("咨询表单不存在"); - const capabilityKey = form.purpose === "quote-request" ? "quote-request" : "inquiry"; - const capability = await this.prisma.capabilityInstallation.findUnique({ - where: { - brandId_capabilityKey: { brandId: identity.brandId, capabilityKey }, - }, - }); - if (capability && capability.status !== "enabled") - throw new BadRequestException("当前咨询能力不可用"); - const fields = Array.isArray(form.fieldsSnapshot) - ? (form.fieldsSnapshot as Array>) - : []; - for (const field of fields) { - const key = typeof field.key === "string" ? field.key : ""; - const value = body.values[key]; - const empty = value === undefined || value === null || value === ""; - if (field.required === true && empty) - throw new BadRequestException(`${String(field.label ?? key)}不能为空`); - if (empty) continue; - if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(String(value))) - throw new BadRequestException(`${String(field.label ?? key)}格式不正确`); - if (field.type === "number" && !Number.isFinite(Number(value))) - throw new BadRequestException(`${String(field.label ?? key)}必须是数字`); - } - const allowedKeys = new Set(fields.map((field) => String(field.key))); - const values = Object.fromEntries( - Object.entries(body.values).filter(([key]) => allowedKeys.has(key)), - ); - const submission = await this.prisma.inquirySubmission.create({ - data: { - brandId: identity.brandId, - customerSubject: identity.subject, - inquiryFormId: form.id, - offeringId: form.offeringId, - formVersion: form.version, - fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue, - values: values as Prisma.InputJsonValue, - activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])), - }, - }); - return this.present(submission); - } -} - -@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 { - this.requireAdmin(request); - return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } }); - } - @Patch("brand") - async updateBrand( - @Req() request: FastifyRequest, - @Body() body: UpdateBrandDto, - ): Promise { - 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) - : {}; - 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 { - 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) - : {}; - 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) - : {}; - 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 { - 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 { - 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 { - 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 { - 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, - PublicController, - PublicTrustContentController, - PublicTemplateController, - PublicWorkspaceController, - PublicOfferingController, - PublicInquiryFormController, - CustomerInquirySubmissionController, - AdminWorkspaceController, - CustomerSessionController, - AdminSessionController, - CustomerBookingController, - TenantController, - AdminBookingController, - AdminConfigController, - ], - providers: [ - PrismaService, - WechatAuthService, - BookingService, - AdminAuthService, - TemplateWorkspaceService, - AdminAccessService, - AdminMembershipGuard, - ], - exports: [PrismaService, WechatAuthService], -}) -export class AppModule {} +import { FastifyAdapter } from "@nestjs/platform-fastify"; +import { AppModule, configureApp } from "./app.module.js"; export async function createApp(): Promise { const app = await NestFactory.create(AppModule, new FastifyAdapter()); - app.useGlobalGuards(app.get(AdminMembershipGuard)); - app.useGlobalPipes( - new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }), - ); - app.useGlobalFilters(new ApiExceptionFilter()); - const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, ""); - if (apiPrefix) app.setGlobalPrefix(apiPrefix); - app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware())); - app.enableCors(); + configureApp(app); return app; }