import { BadRequestException, UnauthorizedException, ForbiddenException, Body, Controller, Delete, Get, Param, Patch, Post, Req, } 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 { InstallTemplateDto, CreateOfferingDto, UpdateOfferingDto, UpdateModuleDto, CreateFieldDefinitionDto, UpdateFieldDefinitionDto, CreateInquiryFormDto, UpdateInquiryFormDto, UpdateInquirySubmissionDto, } from "./admin.dto.js"; import { TemplateWorkspaceService } from "./template-workspace.service.js"; import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation"; @Controller("admin/workspace") class AdminWorkspaceController { constructor( private readonly prisma: PrismaService, private readonly templateWorkspace: TemplateWorkspaceService, ) {} private brandId(): string { return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; } @Get("offerings") async listOfferings(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); const items = await this.prisma.offering.findMany({ where: { brandId: this.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, }; }); } @Post("offerings") createOffering( @Req() request: FastifyRequest, @Body() body: CreateOfferingDto, ): Promise { this.requireAdmin(request); 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: this.brandId(), config: configValue as Prisma.InputJsonValue, }, }); } @Patch("offerings/:id") async updateOffering( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateOfferingDto, ): Promise { this.requireAdmin(request); const item = await this.prisma.offering.findFirst({ where: { id, brandId: this.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, }), }, }); } @Delete("offerings/:id") async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise { this.requireAdmin(request); const item = await this.prisma.offering.findFirst({ where: { id, brandId: this.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): 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() async get(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); const brandId = this.brandId(); const [brand, installations, modules, fields, offerings, forms] = await Promise.all([ this.prisma.brandProfile.findUnique({ where: { id: brandId } }), this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }), this.prisma.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), 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" } }), ]); return { brand, installations, modules, fields, offerings, forms }; } @Post("install") async install( @Req() request: FastifyRequest, @Body() body: InstallTemplateDto, ): Promise { this.requireAdmin(request); return this.templateWorkspace.install(this.brandId(), body.templateKey); } @Get("template/preview") async previewTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.templateWorkspace.preview(this.brandId()); } @Post("template/upgrade") async upgradeTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.templateWorkspace.upgrade(this.brandId()); } @Post("template/rollback") async rollbackTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.templateWorkspace.rollback(this.brandId()); } @Patch("modules/:id") async updateModule( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateModuleDto, ): Promise { this.requireAdmin(request); const item = await this.prisma.brandModule.findFirst({ where: { id, brandId: this.brandId() }, }); if (!item) throw new BadRequestException("品牌模块不存在"); const { config, ...fields } = body; return this.prisma.brandModule.update({ where: { id }, data: { ...fields, ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), }, }); } @Post("fields") createField( @Req() request: FastifyRequest, @Body() body: CreateFieldDefinitionDto, ): Promise { this.requireAdmin(request); return this.prisma.brandFieldDefinition.create({ data: { ...body, brandId: this.brandId(), source: "custom", options: body.options as Prisma.InputJsonValue, visibleWhen: body.visibleWhen as Prisma.InputJsonValue, }, }); } @Patch("fields/:id") async updateField( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateFieldDefinitionDto, ): Promise { this.requireAdmin(request); const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, brandId: this.brandId() }, }); if (!item) throw new BadRequestException("品牌字段不存在"); const { options, visibleWhen, ...fields } = body; return this.prisma.brandFieldDefinition.update({ where: { id }, data: { ...fields, ...(options === undefined ? {} : { options: options as Prisma.InputJsonValue }), ...(visibleWhen === undefined ? {} : { visibleWhen: visibleWhen as Prisma.InputJsonValue }), }, }); } @Delete("fields/:id") async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise { this.requireAdmin(request); const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, brandId: this.brandId(), source: "custom" }, }); if (!item) throw new BadRequestException("自定义字段不存在或不可删除"); await this.prisma.brandFieldDefinition.delete({ where: { id } }); return { deleted: true }; } @Get("forms") listForms(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.prisma.inquiryForm.findMany({ where: { brandId: this.brandId() }, orderBy: { updatedAt: "desc" }, }); } @Get("submissions") listSubmissions(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.prisma.inquirySubmission.findMany({ where: { brandId: this.brandId() }, include: { inquiryForm: { select: { name: true } }, offering: { select: { id: true, name: true } }, }, orderBy: { createdAt: "desc" }, }); } @Patch("submissions/:id") async updateSubmission( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateInquirySubmissionDto, ): Promise { this.requireAdmin(request); const item = await this.prisma.inquirySubmission.findFirst({ where: { id, brandId: this.brandId() }, }); if (!item) throw new BadRequestException("咨询记录不存在"); return this.prisma.$transaction(async (tx) => { const updated = await tx.inquirySubmission.update({ where: { id }, data: { status: body.status, ...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }), }, }); if (item.status !== body.status || body.adminNote !== undefined) { await tx.inquirySubmissionStatusHistory.create({ data: { submissionId: id, fromStatus: item.status, toStatus: body.status, adminNote: body.adminNote ?? null, }, }); } return updated; }); } @Post("forms") createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise { this.requireAdmin(request); if (validateFieldSnapshot(body.fieldsSnapshot).length) throw new BadRequestException("咨询表单字段定义无效"); return this.prisma.inquiryForm.create({ data: { ...body, brandId: this.brandId(), version: 1, fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue, }, }); } @Patch("forms/:id") async updateForm( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateInquiryFormDto, ): Promise { this.requireAdmin(request); const item = await this.prisma.inquiryForm.findFirst({ where: { id, brandId: this.brandId() }, }); if (!item) throw new BadRequestException("咨询表单不存在"); const { fieldsSnapshot, ...fields } = body; if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length) throw new BadRequestException("咨询表单字段定义无效"); return this.prisma.inquiryForm.update({ where: { id }, data: { ...fields, ...(fieldsSnapshot === undefined ? {} : { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }), ...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }), }, }); } } export { AdminWorkspaceController };