diff --git a/apps/api/src/admin-workspace.controller.ts b/apps/api/src/admin-workspace.controller.ts index 3f3aa32..da50b42 100644 --- a/apps/api/src/admin-workspace.controller.ts +++ b/apps/api/src/admin-workspace.controller.ts @@ -36,10 +36,14 @@ import { import { PrismaService as _PrismaService } from "./prisma.service.js"; import { BookingService } from "./booking.service.js"; import { getBrandTemplate } from "@personal-brand/config"; +import { TemplateWorkspaceService } from "./template-workspace.service.js"; @Controller("admin/workspace") class AdminWorkspaceController { - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly templateWorkspace: TemplateWorkspaceService, + ) {} private brandId(): string { return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; } @@ -147,172 +151,25 @@ class AdminWorkspaceController { @Body() body: InstallTemplateDto, ): Promise { this.requireAdmin(request); - const brandId = this.brandId(); - const template = getBrandTemplate(body.templateKey); - if (!template) throw new BadRequestException("行业模板不存在"); - const existing = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }); - if (existing) { - if (existing.templateKey === body.templateKey) - throw new BadRequestException("该模板已经安装"); - throw new BadRequestException("品牌已经安装主模板,请先完成模板切换流程"); - } - return this.prisma.$transaction(async (tx) => { - const installation = await tx.brandTemplateInstallation.create({ - data: { - brandId, - templateKey: body.templateKey, - templateVersion: template.version, - configSnapshot: template as unknown as Prisma.InputJsonValue, - }, - }); - await tx.brandModule.createMany({ - data: template.modules.map(({ type, title }, sortOrder) => ({ - brandId, - type, - title, - sortOrder, - source: "template", - })), - }); - await tx.brandFieldDefinition.createMany({ - data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({ - brandId, - scope, - key, - label, - type, - sortOrder, - source: "core", - required, - })), - }); - return { installation, template }; - }); + return this.templateWorkspace.install(this.brandId(), body.templateKey); } @Get("template/preview") async previewTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); - const installation = await this.prisma.brandTemplateInstallation.findFirst({ - where: { brandId: this.brandId() }, - }); - if (!installation) throw new BadRequestException("尚未安装行业模板"); - const template = getBrandTemplate(installation.templateKey); - if (!template) throw new BadRequestException("已安装模板不存在"); - const [modules, fields] = await Promise.all([ - this.prisma.brandModule.findMany({ where: { brandId: this.brandId() } }), - this.prisma.brandFieldDefinition.findMany({ where: { brandId: this.brandId() } }), - ]); - const missingModules = template.modules.filter( - (item) => - !modules.some((current) => current.type === item.type && current.source === "template"), - ); - const missingFields = template.fields.filter( - (item) => !fields.some((current) => current.scope === item.scope && current.key === item.key), - ); - return { - currentVersion: installation.templateVersion, - latestVersion: template.version, - canUpgrade: installation.templateVersion !== template.version, - canRollback: - Array.isArray(installation.previousSnapshots) && installation.previousSnapshots.length > 0, - missingModules, - missingFields, - }; + return this.templateWorkspace.preview(this.brandId()); } @Post("template/upgrade") async upgradeTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); - const brandId = this.brandId(); - const installation = await this.prisma.brandTemplateInstallation.findFirst({ - where: { brandId }, - }); - if (!installation) throw new BadRequestException("尚未安装行业模板"); - const template = getBrandTemplate(installation.templateKey); - if (!template) throw new BadRequestException("已安装模板不存在"); - if (installation.templateVersion === template.version) - throw new BadRequestException("当前模板已经是最新版本"); - return this.prisma.$transaction(async (tx) => { - const [modules, fields] = await Promise.all([ - tx.brandModule.findMany({ where: { brandId } }), - tx.brandFieldDefinition.findMany({ where: { brandId } }), - ]); - const missingModules = template.modules.filter( - (item) => - !modules.some((current) => current.type === item.type && current.source === "template"), - ); - const missingFields = template.fields.filter( - (item) => - !fields.some((current) => current.scope === item.scope && current.key === item.key), - ); - await tx.brandModule.createMany({ - data: missingModules.map(({ type, title }, index) => ({ - brandId, - type, - title, - sortOrder: modules.length + index, - source: "template", - })), - }); - await tx.brandFieldDefinition.createMany({ - data: missingFields.map(({ scope, key, label, type, required }, index) => ({ - brandId, - scope, - key, - label, - type, - required, - sortOrder: fields.length + index, - source: "template", - })), - }); - const previousSnapshots = Array.isArray(installation.previousSnapshots) - ? installation.previousSnapshots - : []; - const updated = await tx.brandTemplateInstallation.update({ - where: { id: installation.id }, - data: { - templateVersion: template.version, - configSnapshot: template as unknown as Prisma.InputJsonValue, - previousSnapshots: [ - ...previousSnapshots, - installation.configSnapshot, - ] as unknown as Prisma.InputJsonValue, - }, - }); - return { installation: updated, addedModules: missingModules, addedFields: missingFields }; - }); + return this.templateWorkspace.upgrade(this.brandId()); } @Post("template/rollback") async rollbackTemplate(@Req() request: FastifyRequest): Promise { this.requireAdmin(request); - const installation = await this.prisma.brandTemplateInstallation.findFirst({ - where: { brandId: this.brandId() }, - }); - if (!installation) throw new BadRequestException("尚未安装行业模板"); - const history = Array.isArray(installation.previousSnapshots) - ? installation.previousSnapshots - : []; - const previous = history.at(-1); - if (!previous || typeof previous !== "object" || Array.isArray(previous)) - throw new BadRequestException("没有可回滚的模板版本"); - const previousVersion = (previous as { version?: unknown }).version; - if (typeof previousVersion !== "string") throw new BadRequestException("模板快照无效"); - const remaining = history.slice(0, -1); - const updated = await this.prisma.brandTemplateInstallation.update({ - where: { id: installation.id }, - data: { - templateVersion: previousVersion, - configSnapshot: previous as Prisma.InputJsonValue, - previousSnapshots: remaining as Prisma.InputJsonValue, - }, - }); - return { - installation: updated, - note: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。", - }; + return this.templateWorkspace.rollback(this.brandId()); } @Patch("modules/:id") diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index ada9ac3..096a505 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -51,6 +51,7 @@ import { readIdentity, signIdentity } from "./auth.js"; import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js"; import { brandTemplates, getBrandTemplate } from "@personal-brand/config"; import { AdminWorkspaceController } from "./admin-workspace.controller.js"; +import { TemplateWorkspaceService } from "./template-workspace.service.js"; @Controller("health") export class HealthController { @@ -587,7 +588,13 @@ export class AdminConfigController { AdminBookingController, AdminConfigController, ], - providers: [PrismaService, WechatAuthService, BookingService, AdminAuthService], + providers: [ + PrismaService, + WechatAuthService, + BookingService, + AdminAuthService, + TemplateWorkspaceService, + ], exports: [PrismaService, WechatAuthService], }) export class AppModule {} diff --git a/apps/api/src/template-workspace.service.ts b/apps/api/src/template-workspace.service.ts new file mode 100644 index 0000000..7d029a5 --- /dev/null +++ b/apps/api/src/template-workspace.service.ts @@ -0,0 +1,161 @@ +import { BadRequestException, Injectable } from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { getBrandTemplate } from "@personal-brand/config"; +import { PrismaService } from "./prisma.service.js"; + +@Injectable() +export class TemplateWorkspaceService { + constructor(private readonly prisma: PrismaService) {} + async install(brandId: string, templateKey: "personal" | "food") { + const template = getBrandTemplate(templateKey); + if (!template) throw new BadRequestException("行业模板不存在"); + const existing = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }); + if (existing) + throw new BadRequestException( + existing.templateKey === templateKey + ? "该模板已经安装" + : "品牌已经安装主模板,请先完成模板切换流程", + ); + return this.prisma.$transaction(async (tx) => { + const installation = await tx.brandTemplateInstallation.create({ + data: { + brandId, + templateKey, + templateVersion: template.version, + configSnapshot: template as unknown as Prisma.InputJsonValue, + }, + }); + await tx.brandModule.createMany({ + data: template.modules.map(({ type, title }, sortOrder) => ({ + brandId, + type, + title, + sortOrder, + source: "template", + })), + }); + await tx.brandFieldDefinition.createMany({ + data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({ + brandId, + scope, + key, + label, + type, + sortOrder, + source: "core", + required, + })), + }); + return { installation, template }; + }); + } + private async installation(brandId: string) { + const item = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }); + if (!item) throw new BadRequestException("尚未安装行业模板"); + return item; + } + async preview(brandId: string) { + const installation = await this.installation(brandId); + const template = getBrandTemplate(installation.templateKey); + if (!template) throw new BadRequestException("已安装模板不存在"); + const [modules, fields] = await Promise.all([ + this.prisma.brandModule.findMany({ where: { brandId } }), + this.prisma.brandFieldDefinition.findMany({ where: { brandId } }), + ]); + return { + currentVersion: installation.templateVersion, + latestVersion: template.version, + canUpgrade: installation.templateVersion !== template.version, + canRollback: + Array.isArray(installation.previousSnapshots) && installation.previousSnapshots.length > 0, + missingModules: template.modules.filter( + (item) => + !modules.some((current) => current.type === item.type && current.source === "template"), + ), + missingFields: template.fields.filter( + (item) => + !fields.some((current) => current.scope === item.scope && current.key === item.key), + ), + }; + } + async upgrade(brandId: string) { + const installation = await this.installation(brandId); + const template = getBrandTemplate(installation.templateKey); + if (!template) throw new BadRequestException("已安装模板不存在"); + if (installation.templateVersion === template.version) + throw new BadRequestException("当前模板已经是最新版本"); + return this.prisma.$transaction(async (tx) => { + const [modules, fields] = await Promise.all([ + tx.brandModule.findMany({ where: { brandId } }), + tx.brandFieldDefinition.findMany({ where: { brandId } }), + ]); + const addedModules = template.modules.filter( + (item) => + !modules.some((current) => current.type === item.type && current.source === "template"), + ); + const addedFields = template.fields.filter( + (item) => + !fields.some((current) => current.scope === item.scope && current.key === item.key), + ); + await tx.brandModule.createMany({ + data: addedModules.map(({ type, title }, index) => ({ + brandId, + type, + title, + sortOrder: modules.length + index, + source: "template", + })), + }); + await tx.brandFieldDefinition.createMany({ + data: addedFields.map(({ scope, key, label, type, required }, index) => ({ + brandId, + scope, + key, + label, + type, + required, + sortOrder: fields.length + index, + source: "template", + })), + }); + const history = Array.isArray(installation.previousSnapshots) + ? installation.previousSnapshots + : []; + const updated = await tx.brandTemplateInstallation.update({ + where: { id: installation.id }, + data: { + templateVersion: template.version, + configSnapshot: template as unknown as Prisma.InputJsonValue, + previousSnapshots: [ + ...history, + installation.configSnapshot, + ] as unknown as Prisma.InputJsonValue, + }, + }); + return { installation: updated, addedModules, addedFields }; + }); + } + async rollback(brandId: string) { + const installation = await this.installation(brandId); + const history = Array.isArray(installation.previousSnapshots) + ? installation.previousSnapshots + : []; + const previous = history.at(-1); + if (!previous || typeof previous !== "object" || Array.isArray(previous)) + throw new BadRequestException("没有可回滚的模板版本"); + const version = (previous as { version?: unknown }).version; + if (typeof version !== "string") throw new BadRequestException("模板快照无效"); + const updated = await this.prisma.brandTemplateInstallation.update({ + where: { id: installation.id }, + data: { + templateVersion: version, + configSnapshot: previous as Prisma.InputJsonValue, + previousSnapshots: history.slice(0, -1) as Prisma.InputJsonValue, + }, + }); + return { + installation: updated, + note: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。", + }; + } +}