refactor: 将数据库访问从控制器下沉到服务层
This commit is contained in:
1 parent
f158f906d5
commit
3ae7b462f5
21 files changed
+1046
-857
No files matched your search
@@ -11,9 +11,7 @@ import {
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} 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 {
|
||||
CreateTrustContentDto,
|
||||
@@ -21,23 +19,16 @@ import {
|
||||
UpdateBrandPresentationDto,
|
||||
UpdateTrustContentDto,
|
||||
} from "../../admin.dto.js";
|
||||
import {
|
||||
defaultVisualTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
listVisualTemplateKeys,
|
||||
getDefaultVisualTemplateKey,
|
||||
} from "@personal-brand/config";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly brandConfig: AdminBrandConfigService,
|
||||
) {}
|
||||
private brandId(request?: FastifyRequest): string {
|
||||
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
@@ -61,7 +52,7 @@ export class AdminConfigController {
|
||||
@Get("brand")
|
||||
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } });
|
||||
return this.brandConfig.getBrand(this.brandId(request));
|
||||
}
|
||||
@Patch("brand")
|
||||
async updateBrand(
|
||||
@@ -69,70 +60,11 @@ export class AdminConfigController {
|
||||
@Body() body: UpdateBrandDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, ...fields } = body;
|
||||
const { config } = body;
|
||||
if (config?.visualTemplateKey !== undefined) {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
}
|
||||
const current = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: this.brandId(request) },
|
||||
select: { config: true },
|
||||
});
|
||||
const currentConfig =
|
||||
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
|
||||
? (current.config as Record<string, unknown>)
|
||||
: {};
|
||||
const nextConfig = {
|
||||
...currentConfig,
|
||||
...(config ?? {}),
|
||||
// 兼容旧模板:品牌简介的唯一编辑入口是 BrandProfile.description,
|
||||
// 旧视觉模板仍从 config.slogan 读取,保存时保持两者同步。
|
||||
...(fields.description !== undefined && config?.slogan === undefined
|
||||
? { slogan: fields.description }
|
||||
: {}),
|
||||
};
|
||||
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(
|
||||
this.brandId(request),
|
||||
);
|
||||
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: this.brandId(request) },
|
||||
});
|
||||
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: this.brandId(request) },
|
||||
data: {
|
||||
...fields,
|
||||
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
|
||||
},
|
||||
});
|
||||
return this.brandConfig.updateBrand(this.brandId(request), body);
|
||||
}
|
||||
@Patch("presentation")
|
||||
async updatePresentation(
|
||||
@@ -141,167 +73,27 @@ export class AdminConfigController {
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const brandId = this.brandId(request);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
});
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const previous =
|
||||
config.visualPresentation &&
|
||||
typeof config.visualPresentation === "object" &&
|
||||
!Array.isArray(config.visualPresentation)
|
||||
? (config.visualPresentation as Record<string, unknown>)
|
||||
: {};
|
||||
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 =
|
||||
previous[section] &&
|
||||
typeof previous[section] === "object" &&
|
||||
!Array.isArray(previous[section])
|
||||
? (previous[section] as Record<string, unknown>)
|
||||
: {};
|
||||
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: (updated.config as Record<string, unknown>).visualPresentation,
|
||||
};
|
||||
return this.brandConfig.updatePresentation(brandId, body);
|
||||
}
|
||||
@Get("visual-template/history")
|
||||
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandTemplateInstallation
|
||||
.findFirst({ where: { brandId: this.brandId(request) }, select: { previousSnapshots: true } })
|
||||
.then((installation) => ({
|
||||
history: Array.isArray(installation?.previousSnapshots)
|
||||
? installation.previousSnapshots.filter(
|
||||
(item) =>
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
!Array.isArray(item) &&
|
||||
"visualTemplateKey" in item,
|
||||
)
|
||||
: [],
|
||||
}));
|
||||
return this.brandConfig.visualTemplateHistory(this.brandId(request));
|
||||
}
|
||||
@Post("visual-template/rollback")
|
||||
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const brandId = this.brandId(request);
|
||||
const [brand, installation] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
]);
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
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 };
|
||||
return this.brandConfig.rollbackVisualTemplate(this.brandId(request));
|
||||
}
|
||||
@Get("visual-template/preview")
|
||||
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandProfile
|
||||
.findUnique({ where: { id: this.brandId(request) }, select: { config: true } })
|
||||
.then((brand) => {
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
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(),
|
||||
};
|
||||
});
|
||||
return this.brandConfig.visualTemplatePreview(this.brandId(request));
|
||||
}
|
||||
@Get("trust-content")
|
||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: { brandId: this.brandId(request) },
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
return this.templateWorkspace.listTrustContent(this.brandId(request));
|
||||
}
|
||||
@Post("trust-content")
|
||||
createTrustContent(
|
||||
@@ -327,11 +119,6 @@ export class AdminConfigController {
|
||||
@Param("id") id: string,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const item = await this.prisma.trustContent.findFirst({
|
||||
where: { id, brandId: this.brandId(request) },
|
||||
});
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
await this.prisma.trustContent.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
return this.templateWorkspace.deleteTrustContent(this.brandId(request), id);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user