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>)
: {};
}
}
@@ -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);
}
}
@@ -17,7 +17,6 @@ import { resolve } from "node:path";
import { Prisma } from "@prisma/client";
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
import { AdminAccessService } from "../../admin-access.service.js";
import { PrismaService } from "../../prisma.service.js";
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
import { miniappArtifactRoot, miniappProjectPath, REPOSITORY_ROOT } from "./miniapp-artifact.js";
@@ -59,27 +58,19 @@ export class AdminMiniAppReleaseController {
constructor(
private readonly access: AdminAccessService,
private readonly releases: AdminMiniAppReleaseService,
private readonly prisma: PrismaService,
) {}
@Get("latest")
async latest(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
const task = await this.prisma.miniAppReleaseTask.findFirst({
where: { brandId: identity.brandId },
orderBy: { createdAt: "desc" },
});
const task = await this.releases.latest(identity.brandId);
return task ?? null;
}
@Get("settings")
async settings(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
const brand = await this.prisma.brandProfile.findUnique({
where: { id: identity.brandId },
select: { miniAppSettings: true },
});
const settings = this.jsonObject(brand?.miniAppSettings);
const settings = this.jsonObject(await this.releases.settings(identity.brandId));
const buildConfig = this.buildConfigSummary(settings.apiBaseUrl, settings.appId);
return {
appId: "",
@@ -138,11 +129,7 @@ export class AdminMiniAppReleaseController {
`上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`,
);
}
const brand = await this.prisma.brandProfile.findUniqueOrThrow({
where: { id: identity.brandId },
select: { miniAppSettings: true },
});
const current = this.jsonObject(brand.miniAppSettings);
const current = this.jsonObject(await this.releases.settings(identity.brandId));
let apiBaseUrl: string | undefined;
if (body.apiBaseUrl !== undefined) {
const trimmed = body.apiBaseUrl.trim();
@@ -170,10 +157,7 @@ export class AdminMiniAppReleaseController {
...(credential ? { credential } : {}),
templateKey: current.templateKey ?? null,
} satisfies Prisma.InputJsonObject;
await this.prisma.brandProfile.update({
where: { id: identity.brandId },
data: { miniAppSettings: settings },
});
await this.releases.saveSettings(identity.brandId, settings);
return {
appId: settings.appId,
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
@@ -204,19 +188,12 @@ export class AdminMiniAppReleaseController {
@Body() body: UploadMiniAppReleaseDto,
): Promise<unknown> {
const identity = await this.identity(request);
const task = await this.prisma.miniAppReleaseTask.findFirst({
where: { id: taskId, brandId: identity.brandId },
});
if (!task) throw new BadRequestException("小程序发布任务不存在");
const { task, brand } = await this.releases.uploadContext(identity.brandId, taskId);
if (task.status !== "built" && task.status !== "failed")
throw new BadRequestException("当前小程序发布任务不能重复上传");
const staleBuilding = isStaleBuilding(task);
if (task.buildStatus === "building" && !staleBuilding)
throw new ConflictException("小程序构建正在进行中,请稍后");
const brand = await this.prisma.brandProfile.findUniqueOrThrow({
where: { id: identity.brandId },
select: { miniAppSettings: true, templateKey: true },
});
const settings = this.jsonObject(brand.miniAppSettings);
const appid = (() => {
try {
@@ -21,6 +21,40 @@ const transitions: Record<string, string[]> = {
export class AdminMiniAppReleaseService {
constructor(private readonly prisma: PrismaService) {}
async latest(brandId: string) {
return this.prisma.miniAppReleaseTask.findFirst({
where: { brandId },
orderBy: { createdAt: "desc" },
});
}
async settings(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { miniAppSettings: true },
});
return brand?.miniAppSettings ?? null;
}
async uploadContext(brandId: string, taskId: string) {
const [task, brand] = await Promise.all([
this.prisma.miniAppReleaseTask.findFirst({ where: { id: taskId, brandId } }),
this.prisma.brandProfile.findUniqueOrThrow({
where: { id: brandId },
select: { miniAppSettings: true, templateKey: true },
}),
]);
if (!task) throw new BadRequestException("小程序发布任务不存在");
return { task, brand };
}
async saveSettings(brandId: string, settings: Prisma.InputJsonObject) {
await this.prisma.brandProfile.update({
where: { id: brandId },
data: { miniAppSettings: settings },
});
}
async list(brandId: string): Promise<unknown[]> {
return this.prisma.miniAppReleaseTask.findMany({
where: { brandId },