refactor: 拆分后台工作空间控制器
This commit is contained in:
1 parent
292b398ed7
commit
9e4f2620c6
2 files changed
+447
-407
No files matched your search
@@ -0,0 +1,446 @@
|
||||
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 {
|
||||
CreateServiceDto,
|
||||
CreateTagDto,
|
||||
CreateTrustContentDto,
|
||||
UpdateBookingStatusDto,
|
||||
UpdateBookingTagsDto,
|
||||
UpdateBrandDto,
|
||||
UpdateServiceDto,
|
||||
UpdateTrustContentDto,
|
||||
InstallTemplateDto,
|
||||
CreateOfferingDto,
|
||||
UpdateOfferingDto,
|
||||
UpdateModuleDto,
|
||||
CreateFieldDefinitionDto,
|
||||
UpdateFieldDefinitionDto,
|
||||
CreateInquiryFormDto,
|
||||
UpdateInquiryFormDto,
|
||||
} from "./admin.dto.js";
|
||||
import { PrismaService as _PrismaService } from "./prisma.service.js";
|
||||
import { BookingService } from "./booking.service.js";
|
||||
import { getBrandTemplate } from "@personal-brand/config";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspaceController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
private brandId(): string {
|
||||
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
}
|
||||
|
||||
@Get("offerings")
|
||||
async listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
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<string, unknown>;
|
||||
return {
|
||||
...item,
|
||||
sections: config.sections ?? [],
|
||||
media: config.media ?? [],
|
||||
cta: config.cta ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@Post("offerings")
|
||||
createOffering(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateOfferingDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, sections, media, cta, ...fields } = body;
|
||||
return this.prisma.offering.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId: this.brandId(),
|
||||
config: {
|
||||
...(config ?? {}),
|
||||
...(sections === undefined ? {} : { sections }),
|
||||
...(media === undefined ? {} : { media }),
|
||||
...(cta === undefined ? {} : { cta }),
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@Patch("offerings/:id")
|
||||
async updateOffering(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateOfferingDto,
|
||||
): Promise<unknown> {
|
||||
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;
|
||||
return this.prisma.offering.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined &&
|
||||
sections === undefined &&
|
||||
media === undefined &&
|
||||
cta === undefined
|
||||
? {}
|
||||
: {
|
||||
config: {
|
||||
...(config ?? {}),
|
||||
...(sections === undefined ? {} : { sections }),
|
||||
...(media === undefined ? {} : { media }),
|
||||
...(cta === undefined ? {} : { cta }),
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
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<unknown> {
|
||||
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<unknown> {
|
||||
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 };
|
||||
});
|
||||
}
|
||||
|
||||
@Get("template/preview")
|
||||
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@Post("template/upgrade")
|
||||
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
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 };
|
||||
});
|
||||
}
|
||||
|
||||
@Post("template/rollback")
|
||||
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
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: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。",
|
||||
};
|
||||
}
|
||||
|
||||
@Patch("modules/:id")
|
||||
async updateModule(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateModuleDto,
|
||||
): Promise<unknown> {
|
||||
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<unknown> {
|
||||
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<unknown> {
|
||||
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<unknown> {
|
||||
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<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.inquiryForm.findMany({
|
||||
where: { brandId: this.brandId() },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
@Get("submissions")
|
||||
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId: this.brandId() },
|
||||
include: { inquiryForm: { select: { name: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
@Post("forms")
|
||||
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
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<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const item = await this.prisma.inquiryForm.findFirst({
|
||||
where: { id, brandId: this.brandId() },
|
||||
});
|
||||
if (!item) throw new BadRequestException("咨询表单不存在");
|
||||
const { fieldsSnapshot, ...fields } = body;
|
||||
return this.prisma.inquiryForm.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(fieldsSnapshot === undefined
|
||||
? {}
|
||||
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
|
||||
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { AdminWorkspaceController };
|
||||
Reference in new issue
Block a user