From 4512d2601db1c112a47a65b611ed8f4283a8bd15 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:29:30 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8F=B0=E4=B8=9A=E5=8A=A1=E6=9C=8D=E5=8A=A1=E8=BE=B9?= =?UTF-8?q?=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/api/src/admin-workspace.controller.ts | 206 ++++-------------- apps/api/src/app.module.ts | 4 + .../workspace/admin-access.identity.ts | 23 ++ .../workspace/admin-offering.service.ts | 94 ++++++++ .../workspace/admin-workspace.service.ts | 65 ++++++ 5 files changed, 228 insertions(+), 164 deletions(-) create mode 100644 apps/api/src/modules/workspace/admin-access.identity.ts create mode 100644 apps/api/src/modules/workspace/admin-offering.service.ts create mode 100644 apps/api/src/modules/workspace/admin-workspace.service.ts diff --git a/apps/api/src/admin-workspace.controller.ts b/apps/api/src/admin-workspace.controller.ts index 162ec4a..1596ceb 100644 --- a/apps/api/src/admin-workspace.controller.ts +++ b/apps/api/src/admin-workspace.controller.ts @@ -1,7 +1,5 @@ import { BadRequestException, - UnauthorizedException, - ForbiddenException, Body, Controller, Delete, @@ -14,7 +12,6 @@ import { import { Prisma } from "@prisma/client"; import type { FastifyRequest } from "fastify"; import { PrismaService } from "./prisma.service.js"; -import { readIdentity } from "./auth.js"; import { InstallTemplateDto, CreateOfferingDto, @@ -27,44 +24,30 @@ import { UpdateCapabilityInstallationDto, } from "./admin.dto.js"; import { + capabilityRegistry, capabilityPlugins, getBrandTemplate, getTemplateSampleContent, - getTemplatePackageManifestForVisualKey, - getDefaultVisualTemplateKey, - resolveCapabilities, } from "@personal-brand/config"; import { TemplateWorkspaceService } from "./template-workspace.service.js"; -import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation"; -import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.js"; +import { validateFieldSnapshot } from "@personal-brand/validation"; +import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js"; +import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js"; +import { requireAdminIdentity } from "./modules/workspace/admin-access.identity.js"; @Controller("admin/workspace") class AdminWorkspaceController { constructor( private readonly prisma: PrismaService, private readonly templateWorkspace: TemplateWorkspaceService, - private readonly publicWorkspace: PublicWorkspaceService, + private readonly offeringService: AdminOfferingService, + private readonly workspaceService: AdminWorkspaceService, ) {} - private brandId(): string { - return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; - } @Get("offerings") - async listOfferings(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; - const items = await this.prisma.offering.findMany({ - where: { brandId }, - orderBy: { sortOrder: "asc" }, - }); - return items.map((item) => { - const config = (item.config ?? {}) as Record; - return { - ...item, - sections: config.sections ?? [], - media: config.media ?? [], - cta: config.cta ?? null, - }; - }); + listOfferings(@Req() request: FastifyRequest): Promise { + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.list(brandId); } @Post("offerings") @@ -72,23 +55,8 @@ class AdminWorkspaceController { @Req() request: FastifyRequest, @Body() body: CreateOfferingDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; - const { config, sections, media, cta, ...fields } = body; - const configValue = { - ...(config ?? {}), - ...(sections === undefined ? {} : { sections }), - ...(media === undefined ? {} : { media }), - ...(cta === undefined ? {} : { cta }), - }; - const configIssues = validateOfferingConfig(configValue); - if (configIssues.length) throw new BadRequestException("业务提供项配置无效"); - return this.prisma.offering.create({ - data: { - ...fields, - brandId, - config: configValue as Prisma.InputJsonValue, - }, - }); + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.create(brandId, body); } @Patch("offerings/:id") @@ -97,134 +65,44 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateOfferingDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; - const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); - if (!item) throw new BadRequestException("业务提供项不存在"); - const { config, sections, media, cta, ...fields } = body; - const configValue = { - ...(config ?? {}), - ...(sections === undefined ? {} : { sections }), - ...(media === undefined ? {} : { media }), - ...(cta === undefined ? {} : { cta }), - }; - if (validateOfferingConfig(configValue).length) - throw new BadRequestException("业务提供项配置无效"); - return this.prisma.offering.update({ - where: { id }, - data: { - ...fields, - ...(config === undefined && - sections === undefined && - media === undefined && - cta === undefined - ? {} - : { - config: configValue as Prisma.InputJsonValue, - }), - }, - }); + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.update(brandId, id, body); } @Delete("offerings/:id") async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - const brandId = this.requireAdmin(request).brandId; - const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); - if (!item) throw new BadRequestException("业务提供项不存在"); - const [forms, bookings, items] = await Promise.all([ - this.prisma.inquiryForm.count({ where: { offeringId: id } }), - this.prisma.booking.count({ where: { offeringId: id } }), - this.prisma.bookingItem.count({ where: { offeringId: id } }), - ]); - if (forms || bookings || items) - throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除"); - await this.prisma.offering.delete({ where: { id } }); - return { deleted: true }; - } - private requireAdmin(request: FastifyRequest): { - subject: string; - brandId: string; - role: "admin"; - } { - 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("无管理员权限"); - return identity as { subject: string; brandId: string; role: "admin" }; + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.delete(brandId, id); } @Get() - async get(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; - const [brand, installations, fields, offerings, forms] = await Promise.all([ - this.prisma.brandProfile.findUnique({ where: { id: brandId } }), - this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }), - this.prisma.brandFieldDefinition.findMany({ - where: { brandId }, - orderBy: { sortOrder: "asc" }, - }), - this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), - this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }), - ]); - const config = this.jsonObject(brand?.config); - const templateKey = - typeof config.visualTemplateKey === "string" - ? config.visualTemplateKey - : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); - const manifest = getTemplatePackageManifestForVisualKey(templateKey); - return { - brand, - installations, - fields, - offerings, - forms, - templateContent: manifest - ? { - displayName: manifest.displayName, - admin: manifest.admin, - navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })), - templateFields: (manifest.templateFields ?? []).map((field) => ({ - ...field, - binding: field.binding ?? `brand.config.templateData.${field.key}`, - })), - assetSlots: manifest.assetSlots, - trustContentTypes: manifest.trustContentTypes ?? [], - } - : null, - }; + get(@Req() request: FastifyRequest): Promise { + const brandId = requireAdminIdentity(request).brandId; + return this.workspaceService.get(brandId); } @Get("preview") async getPreviewWorkspace(@Req() request: FastifyRequest): Promise { - const { brandId } = this.requireAdmin(request); - return this.publicWorkspace.getForBrandId(brandId, true); - } - private jsonObject(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : {}; + const { brandId } = requireAdminIdentity(request); + return this.workspaceService.getPreview(brandId); } @Post("install") async install( @Req() request: FastifyRequest, @Body() body: InstallTemplateDto, ): Promise { - this.requireAdmin(request); - return this.templateWorkspace.install(this.requireAdmin(request).brandId, body.templateKey); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.install(brandId, body.templateKey); } @Get("capabilities") async listCapabilities(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const [templateKey, installations] = await Promise.all([ this.templateWorkspace.getEffectiveTemplateKey(brandId), this.prisma.capabilityInstallation.findMany({ where: { brandId } }), ]); const installed = new Map(installations.map((item) => [item.capabilityKey, item])); const template = getBrandTemplate(templateKey); - return (template ? resolveCapabilities(template.capabilities) : []).map((definition) => { + return (template?.capabilities ?? []).map((key) => capabilityRegistry[key]).map((definition) => { const item = installed.get(definition.key); return { id: item?.id ?? null, @@ -240,7 +118,7 @@ class AdminWorkspaceController { @Get("sample-content/preview") async previewSampleContent(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); const sample = getTemplateSampleContent(templateKey); if (!sample) throw new BadRequestException("模板示例内容不存在"); @@ -265,7 +143,7 @@ class AdminWorkspaceController { @Post("sample-content/import") async importSampleContent(@Req() request: FastifyRequest): Promise { - const identity = this.requireAdmin(request); + const identity = requireAdminIdentity(request); const brandId = identity.brandId; const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); const sample = getTemplateSampleContent(templateKey); @@ -359,7 +237,7 @@ class AdminWorkspaceController { @Param("key") key: string, @Body() body: UpdateCapabilityInstallationDto, ): Promise { - const identity = this.requireAdmin(request); + const identity = requireAdminIdentity(request); const brandId = identity.brandId; const template = getBrandTemplate( await this.templateWorkspace.getEffectiveTemplateKey(brandId), @@ -402,20 +280,20 @@ class AdminWorkspaceController { @Get("template/preview") async previewTemplate(@Req() request: FastifyRequest): Promise { - this.requireAdmin(request); - return this.templateWorkspace.preview(this.requireAdmin(request).brandId); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.preview(brandId); } @Post("template/upgrade") async upgradeTemplate(@Req() request: FastifyRequest): Promise { - this.requireAdmin(request); - return this.templateWorkspace.upgrade(this.requireAdmin(request).brandId); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.upgrade(brandId); } @Post("template/rollback") async rollbackTemplate(@Req() request: FastifyRequest): Promise { - this.requireAdmin(request); - return this.templateWorkspace.rollback(this.requireAdmin(request).brandId); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.rollback(brandId); } @Post("fields") @@ -423,7 +301,7 @@ class AdminWorkspaceController { @Req() request: FastifyRequest, @Body() body: CreateFieldDefinitionDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; return this.prisma.brandFieldDefinition.create({ data: { ...body, @@ -441,7 +319,7 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateFieldDefinitionDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, brandId }, }); @@ -459,7 +337,7 @@ class AdminWorkspaceController { @Delete("fields/:id") async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, brandId, source: "custom" }, }); @@ -470,7 +348,7 @@ class AdminWorkspaceController { @Get("forms") listForms(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; return this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" }, @@ -479,7 +357,7 @@ class AdminWorkspaceController { @Get("submissions") listSubmissions(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; return this.prisma.inquirySubmission.findMany({ where: { brandId }, include: { @@ -496,7 +374,7 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateInquirySubmissionDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.inquirySubmission.findFirst({ where: { id, brandId }, }); @@ -525,7 +403,7 @@ class AdminWorkspaceController { @Post("forms") createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; if (validateFieldSnapshot(body.fieldsSnapshot).length) throw new BadRequestException("咨询表单字段定义无效"); return this.prisma.inquiryForm.create({ @@ -544,7 +422,7 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateInquiryFormDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.inquiryForm.findFirst({ where: { id, brandId }, }); diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index b2bbcea..875f580 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -12,6 +12,8 @@ import { PublicWorkspaceService, } from "./modules/public/public-workspace.controller.js"; import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js"; +import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js"; +import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js"; import { AdminConfigController } from "./modules/admin/admin-config.controller.js"; import { AdminUploadController } from "./modules/admin/admin-upload.controller.js"; import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js"; @@ -78,6 +80,8 @@ export class HealthController { BrandReleaseApiService, PublicBrandContextService, PublicWorkspaceService, + AdminOfferingService, + AdminWorkspaceService, ], exports: [PrismaService, WechatAuthService], }) diff --git a/apps/api/src/modules/workspace/admin-access.identity.ts b/apps/api/src/modules/workspace/admin-access.identity.ts new file mode 100644 index 0000000..dc16b26 --- /dev/null +++ b/apps/api/src/modules/workspace/admin-access.identity.ts @@ -0,0 +1,23 @@ +import { ForbiddenException, UnauthorizedException } from "@nestjs/common"; +import type { FastifyRequest } from "fastify"; +import { readIdentity } from "../../auth.js"; + +export type AdminIdentity = { + subject: string; + brandId: string; + role: "admin"; +}; + +export function requireAdminIdentity(request: FastifyRequest): AdminIdentity { + 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("无管理员权限"); + return identity as AdminIdentity; +} diff --git a/apps/api/src/modules/workspace/admin-offering.service.ts b/apps/api/src/modules/workspace/admin-offering.service.ts new file mode 100644 index 0000000..1d9d33f --- /dev/null +++ b/apps/api/src/modules/workspace/admin-offering.service.ts @@ -0,0 +1,94 @@ +import { BadRequestException, Injectable } from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { PrismaService } from "../../prisma.service.js"; +import type { CreateOfferingDto, UpdateOfferingDto } from "../../admin.dto.js"; +import { validateOfferingConfig } from "@personal-brand/validation"; + +type OfferingConfigInput = { + config?: CreateOfferingDto["config"] | undefined; + sections?: CreateOfferingDto["sections"] | undefined; + media?: CreateOfferingDto["media"] | undefined; + cta?: CreateOfferingDto["cta"] | undefined; +}; + +function buildOfferingConfig(body: OfferingConfigInput): Record { + const { config, sections, media, cta } = body; + return { + ...(config ?? {}), + ...(sections === undefined ? {} : { sections }), + ...(media === undefined ? {} : { media }), + ...(cta === undefined ? {} : { cta }), + }; +} + +@Injectable() +export class AdminOfferingService { + constructor(private readonly prisma: PrismaService) {} + + async list(brandId: string): Promise { + const items = await this.prisma.offering.findMany({ + where: { brandId }, + orderBy: { sortOrder: "asc" }, + }); + return items.map((item) => { + const config = (item.config ?? {}) as Record; + return { + ...item, + sections: config.sections ?? [], + media: config.media ?? [], + cta: config.cta ?? null, + }; + }); + } + + async create(brandId: string, body: CreateOfferingDto): Promise { + const { config, sections, media, cta, ...fields } = body; + const configValue = buildOfferingConfig({ config, sections, media, cta }); + if (validateOfferingConfig(configValue).length) { + throw new BadRequestException("业务提供项配置无效"); + } + return this.prisma.offering.create({ + data: { + ...fields, + brandId, + config: configValue as Prisma.InputJsonValue, + }, + }); + } + + async update(brandId: string, id: string, body: UpdateOfferingDto): Promise { + const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); + if (!item) throw new BadRequestException("业务提供项不存在"); + + const { config, sections, media, cta, ...fields } = body; + const configValue = buildOfferingConfig({ config, sections, media, cta }); + if (validateOfferingConfig(configValue).length) { + throw new BadRequestException("业务提供项配置无效"); + } + const hasConfigInput = + config !== undefined || sections !== undefined || media !== undefined || cta !== undefined; + return this.prisma.offering.update({ + where: { id }, + data: { + ...fields, + ...(hasConfigInput ? { config: configValue as Prisma.InputJsonValue } : {}), + }, + }); + } + + async delete(brandId: string, id: string): Promise { + const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); + if (!item) throw new BadRequestException("业务提供项不存在"); + + const [forms, bookings, items] = await Promise.all([ + this.prisma.inquiryForm.count({ where: { offeringId: id } }), + this.prisma.booking.count({ where: { offeringId: id } }), + this.prisma.bookingItem.count({ where: { offeringId: id } }), + ]); + if (forms || bookings || items) { + throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除"); + } + await this.prisma.offering.delete({ where: { id } }); + return { deleted: true }; + } +} diff --git a/apps/api/src/modules/workspace/admin-workspace.service.ts b/apps/api/src/modules/workspace/admin-workspace.service.ts new file mode 100644 index 0000000..9a93bc7 --- /dev/null +++ b/apps/api/src/modules/workspace/admin-workspace.service.ts @@ -0,0 +1,65 @@ +import { Injectable } from "@nestjs/common"; +import { PrismaService } from "../../prisma.service.js"; +import { + getDefaultVisualTemplateKey, + getTemplatePackageManifestForVisualKey, +} from "@personal-brand/config"; +import { PublicWorkspaceService } from "../public/public-workspace.controller.js"; + +@Injectable() +export class AdminWorkspaceService { + constructor( + private readonly prisma: PrismaService, + private readonly publicWorkspace: PublicWorkspaceService, + ) {} + + async get(brandId: string): Promise { + const [brand, installations, fields, offerings, forms] = await Promise.all([ + this.prisma.brandProfile.findUnique({ where: { id: brandId } }), + this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }), + this.prisma.brandFieldDefinition.findMany({ + where: { brandId }, + orderBy: { sortOrder: "asc" }, + }), + this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), + this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }), + ]); + const config = this.jsonObject(brand?.config); + const templateKey = + typeof config.visualTemplateKey === "string" + ? config.visualTemplateKey + : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); + const manifest = getTemplatePackageManifestForVisualKey(templateKey); + + return { + brand, + installations, + fields, + offerings, + forms, + templateContent: manifest + ? { + displayName: manifest.displayName, + admin: manifest.admin, + navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })), + templateFields: (manifest.templateFields ?? []).map((field) => ({ + ...field, + binding: field.binding ?? `brand.config.templateData.${field.key}`, + })), + assetSlots: manifest.assetSlots, + trustContentTypes: manifest.trustContentTypes ?? [], + } + : null, + }; + } + + getPreview(brandId: string): Promise { + return this.publicWorkspace.getForBrandId(brandId, true); + } + + private jsonObject(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } +}