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, CreateFieldDefinitionDto, UpdateFieldDefinitionDto, CreateInquiryFormDto, UpdateInquiryFormDto, UpdateInquirySubmissionDto, UpdateCapabilityInstallationDto, } from "./admin.dto.js"; import { capabilityPlugins, getBrandTemplate, getTemplateSampleContent, getTemplatePackageManifestForVisualKey, getDefaultVisualTemplateKey, resolveCapabilities, } from "@personal-brand/config"; 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 { 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, }; }); } @Post("offerings") createOffering( @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, }, }); } @Patch("offerings/:id") async updateOffering( @Req() request: FastifyRequest, @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, }), }, }); } @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" }; } @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, }; } private jsonObject(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } @Post("install") async install( @Req() request: FastifyRequest, @Body() body: InstallTemplateDto, ): Promise { this.requireAdmin(request); return this.templateWorkspace.install(this.requireAdmin(request).brandId, body.templateKey); } @Get("capabilities") async listCapabilities(@Req() request: FastifyRequest): Promise { const brandId = this.requireAdmin(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) => { const item = installed.get(definition.key); return { id: item?.id ?? null, capabilityKey: definition.key, capabilityVersion: item?.capabilityVersion ?? definition.version, status: item?.status ?? "enabled", config: item?.config ?? {}, source: item ? "brand" : "template", updatedAt: item?.updatedAt ?? null, }; }); } @Get("sample-content/preview") async previewSampleContent(@Req() request: FastifyRequest): Promise { const brandId = this.requireAdmin(request).brandId; const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); const sample = getTemplateSampleContent(templateKey); if (!sample) throw new BadRequestException("模板示例内容不存在"); const [offerings, trustContent, fields] = await Promise.all([ this.prisma.offering.count({ where: { brandId } }), this.prisma.trustContent.count({ where: { brandId } }), this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }), ]); return { templateKey: sample.templateKey, alreadyImported: offerings > 0 || trustContent > 0 || fields > 0, counts: { offerings: sample.offerings.length, trustContent: sample.trustContent.length, fields: sample.fields.length, inquiryForms: 1, }, willCreateInquiryForm: (await this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } })) === 0, }; } @Post("sample-content/import") async importSampleContent(@Req() request: FastifyRequest): Promise { const identity = this.requireAdmin(request); const brandId = identity.brandId; const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); const sample = getTemplateSampleContent(templateKey); if (!sample) throw new BadRequestException("模板示例内容不存在"); const fieldIssues = validateFieldSnapshot(sample.fields); if (fieldIssues.length) throw new BadRequestException("模板咨询表单示例字段无效"); const existing = await this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" }, }); const existingOffering = await this.prisma.offering.count({ where: { brandId, name: "序章·入户门" }, }); if (existing || existingOffering) throw new BadRequestException("示例内容已经导入"); const result = await this.prisma.$transaction(async (tx) => { const offerings = await tx.offering.createMany({ data: sample.offerings.map((item, sortOrder) => ({ brandId, kind: item.kind, name: item.name, summary: item.summary, config: { categoryKey: item.categoryKey }, sortOrder, isEnabled: true, })), }); const trust = await tx.trustContent.createMany({ data: sample.trustContent.map((item, sortOrder) => ({ brandId, type: item.type, title: item.title, content: item.content, ...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}), sortOrder, isPublished: false, })), }); const fields = await tx.brandFieldDefinition.createMany({ data: sample.fields.map((item, sortOrder) => ({ brandId, scope: "inquiry", key: item.key, label: item.label, type: item.type, sortOrder, source: "sample", required: item.required, })), }); const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } }); const inquiryForm = hasEnabledForm ? null : await tx.inquiryForm.create({ data: { brandId, name: sample.inquiryFormName, purpose: "inquiry", targetType: "brand", submissionAction: "create-inquiry", fieldsSnapshot: sample.fields, isEnabled: true, }, }); await tx.capabilityAuditLog.create({ data: { brandId, capabilityKey: sample.capabilityKey, actorId: identity.subject, action: "sample_content_imported", toStatus: "enabled", config: { offerings: offerings.count, trustContent: trust.count, fields: fields.count, inquiryForms: inquiryForm ? 1 : 0, }, }, }); return { offerings: offerings.count, trustContent: trust.count, fields: fields.count, inquiryForms: inquiryForm ? 1 : 0, }; }); return { imported: true, counts: result }; } @Patch("capabilities/:key") async updateCapability( @Req() request: FastifyRequest, @Param("key") key: string, @Body() body: UpdateCapabilityInstallationDto, ): Promise { const identity = this.requireAdmin(request); const brandId = identity.brandId; const template = getBrandTemplate( await this.templateWorkspace.getEffectiveTemplateKey(brandId), ); if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins)) throw new BadRequestException("能力未被当前模板声明"); const existing = await this.prisma.capabilityInstallation.findUnique({ where: { brandId_capabilityKey: { brandId, capabilityKey: key } }, }); return this.prisma.$transaction(async (tx) => { const installation = await tx.capabilityInstallation.upsert({ where: { brandId_capabilityKey: { brandId, capabilityKey: key } }, create: { brandId, capabilityKey: key, capabilityVersion: body.capabilityVersion, status: body.status, config: (body.config ?? {}) as Prisma.InputJsonValue, }, update: { capabilityVersion: body.capabilityVersion, status: body.status, ...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }), }, }); await tx.capabilityAuditLog.create({ data: { brandId, capabilityKey: key, actorId: identity.subject, action: existing ? "updated" : "installed", fromStatus: existing?.status ?? null, toStatus: body.status, config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue, }, }); return installation; }); } @Get("template/preview") async previewTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.templateWorkspace.preview(this.requireAdmin(request).brandId); } @Post("template/upgrade") async upgradeTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.templateWorkspace.upgrade(this.requireAdmin(request).brandId); } @Post("template/rollback") async rollbackTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); return this.templateWorkspace.rollback(this.requireAdmin(request).brandId); } @Post("fields") createField( @Req() request: FastifyRequest, @Body() body: CreateFieldDefinitionDto, ): Promise { const brandId = this.requireAdmin(request).brandId; return this.prisma.brandFieldDefinition.create({ data: { ...body, 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 { const brandId = this.requireAdmin(request).brandId; const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, 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 { const brandId = this.requireAdmin(request).brandId; const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, 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 { const brandId = this.requireAdmin(request).brandId; return this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" }, }); } @Get("submissions") listSubmissions(@Req() request: FastifyRequest): Promise { const brandId = this.requireAdmin(request).brandId; return this.prisma.inquirySubmission.findMany({ where: { 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 { const brandId = this.requireAdmin(request).brandId; const item = await this.prisma.inquirySubmission.findFirst({ where: { id, 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 { const brandId = this.requireAdmin(request).brandId; if (validateFieldSnapshot(body.fieldsSnapshot).length) throw new BadRequestException("咨询表单字段定义无效"); return this.prisma.inquiryForm.create({ data: { ...body, 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 { const brandId = this.requireAdmin(request).brandId; const item = await this.prisma.inquiryForm.findFirst({ where: { id, 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 };