refactor: 将数据库访问从控制器下沉到服务层

This commit is contained in:
que01 committed 2026-10-14 17:53:49 +08:00
1 parent f158f906d5
commit 3ae7b462f5
21 files changed
+1046 -857

No files matched your search

@@ -0,0 +1,223 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
defaultVisualTemplateKey,
getBrandTemplate,
getDefaultVisualTemplateKey,
getVisualTemplate,
isVisualTemplateCompatible,
listVisualTemplateKeys,
} from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import type { UpdateBrandDto, UpdateBrandPresentationDto } from "../../admin.dto.js";
@Injectable()
export class AdminBrandConfigService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
getBrand(brandId: string) {
return this.prisma.brandProfile.findUnique({ where: { id: brandId } });
}
async updateBrand(brandId: string, body: UpdateBrandDto) {
const { config, ...fields } = body;
const current = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const currentConfig = this.jsonObject(current?.config);
const nextConfig = {
...currentConfig,
...(config ?? {}),
...(fields.description !== undefined && config?.slogan === undefined
? { slogan: fields.description }
: {}),
};
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const visualTemplate =
typeof config.visualTemplateKey === "string"
? getVisualTemplate(config.visualTemplateKey)
: undefined;
if (
!visualTemplate ||
!getBrandTemplate(templateKey) ||
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配该行业模板");
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
});
if (installation) {
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
previousSnapshots: [
...history,
{
visualTemplateKey:
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: brandId },
data: {
...fields,
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
}
async updatePresentation(brandId: string, body: UpdateBrandPresentationDto) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config = this.jsonObject(brand?.config);
const previous = this.jsonObject(config.visualPresentation);
const nextPresentation = { ...previous };
const identity = body.identity;
const identityFields = ["founder", "title", "slogan", "phone", "wechat", "studioAddress"];
const nextIdentity = identity
? Object.fromEntries(
identityFields
.filter((key) => typeof identity[key] === "string")
.map((key) => [key, identity[key]]),
)
: {};
for (const section of [
"home",
"offerings",
"detail",
"profile",
"inquiry",
"success",
"records",
] as const) {
const input = body[section];
if (!input) continue;
const current = this.jsonObject(previous[section]);
const values = Object.fromEntries(
Object.entries(input).filter(([, value]) => typeof value === "string"),
);
nextPresentation[section] = { ...current, ...values };
}
const updated = await this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
...nextIdentity,
visualPresentation: nextPresentation,
} as Prisma.InputJsonValue,
},
select: { config: true },
});
return {
visualPresentation: this.jsonObject(updated.config).visualPresentation,
};
}
async visualTemplateHistory(brandId: string) {
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
select: { previousSnapshots: true },
});
return {
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
};
}
async rollbackVisualTemplate(brandId: string) {
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config = this.jsonObject(brand?.config);
const history = Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots
: [];
const index = [...history]
.map((item, i) => ({ item, i }))
.reverse()
.find(
({ item }) =>
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
)?.i;
const previous =
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
if (!previous || typeof previous.visualTemplateKey !== "string")
throw new BadRequestException("没有可回滚的视觉模板版本");
await this.prisma.$transaction([
this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
visualTemplateKey: previous.visualTemplateKey,
},
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
}
async visualTemplatePreview(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config = this.jsonObject(brand?.config);
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: defaultVisualTemplateKey;
const current = getVisualTemplate(currentKey);
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: listVisualTemplateKeys(),
};
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}