refactor: 拆分工作台业务服务边界

This commit is contained in:
que01 committed 2026-10-12 03:29:30 +08:00
1 parent d0902d6568
commit 4512d2601d
5 files changed
+228 -164

No files matched your search

@@ -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;
}
@@ -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<string, unknown> {
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<unknown> {
const items = await this.prisma.offering.findMany({
where: { 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,
};
});
}
async create(brandId: string, body: CreateOfferingDto): Promise<unknown> {
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<unknown> {
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<unknown> {
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 };
}
}
@@ -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<unknown> {
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<unknown> {
return this.publicWorkspace.getForBrandId(brandId, true);
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}