diff --git a/.codex-tasks/tenant-architecture-epic/PROGRESS.md b/.codex-tasks/tenant-architecture-epic/PROGRESS.md index 4a00dd5..1f22310 100644 --- a/.codex-tasks/tenant-architecture-epic/PROGRESS.md +++ b/.codex-tasks/tenant-architecture-epic/PROGRESS.md @@ -2,8 +2,8 @@ - 任务:多品牌后台与 API 架构收口 - 形态:epic -- 进度:1/3 -- 当前:API Controller 拆分(已完成 session、customer booking、admin booking;继续拆分 public 和 admin config) +- 进度:3/3 +- 当前:已完成多品牌工作区、API Controller 拆分与全量回归收口 - 真相文件:`SUBTASKS.csv` ## 已完成 @@ -19,3 +19,6 @@ - 新增 `GET /admin/brands` 和 `POST /admin/brands/:brandId/switch`,切换由 membership 服务端校验。 - seed 已增加第二个独立品牌 `林境门作`(slug:`linjing-doors`),并绑定同一管理员的独立 membership。 - 修复多品牌出现后 `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 全部通过。 diff --git a/.codex-tasks/tenant-architecture-epic/SUBTASKS.csv b/.codex-tasks/tenant-architecture-epic/SUBTASKS.csv index 62c18c6..507c08f 100644 --- a/.codex-tasks/tenant-architecture-epic/SUBTASKS.csv +++ b/.codex-tasks/tenant-architecture-epic/SUBTASKS.csv @@ -1,4 +1,4 @@ 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,已完成 -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 仍待拆分 -3,架构回归收口,single-full,2,TODO,tasks/regression,Admin 和 miniapp 回归全部通过,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/miniapp test:fixture, +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,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 全部通过 diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index f80970f..4bfff6f 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -36,6 +36,8 @@ import { visualTemplates, } from "@personal-brand/config"; import { AdminWorkspaceController } from "./admin-workspace.controller.js"; +import { PublicWorkspaceController } from "./modules/public/public-workspace.controller.js"; +import { AdminConfigController } from "./modules/admin/admin-config.controller.js"; import { TemplateWorkspaceService } from "./template-workspace.service.js"; import { AdminAccessService } from "./admin-access.service.js"; import { AdminMembershipGuard } from "./admin-membership.guard.js"; @@ -66,271 +68,6 @@ export class HealthController { } } -@Controller("public/workspace") -export class PublicWorkspaceController { - constructor(private readonly prisma: PrismaService) {} - private readonly cache = new Map(); - @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) {} @@ -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 { - 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, diff --git a/apps/api/src/modules/admin/admin-config.controller.ts b/apps/api/src/modules/admin/admin-config.controller.ts new file mode 100644 index 0000000..e8cc429 --- /dev/null +++ b/apps/api/src/modules/admin/admin-config.controller.ts @@ -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 { + 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 }; + } +} diff --git a/apps/api/src/modules/public/public-workspace.controller.ts b/apps/api/src/modules/public/public-workspace.controller.ts new file mode 100644 index 0000000..21bf488 --- /dev/null +++ b/apps/api/src/modules/public/public-workspace.controller.ts @@ -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(); + @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"; + } +}