refactor: 将数据库访问从控制器下沉到服务层
This commit is contained in:
1 parent
f158f906d5
commit
3ae7b462f5
21 files changed
+1046
-857
No files matched your search
@@ -1,17 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Req,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import {
|
||||
InstallTemplateDto,
|
||||
CreateOfferingDto,
|
||||
@@ -23,27 +11,23 @@ import {
|
||||
UpdateInquirySubmissionDto,
|
||||
UpdateCapabilityInstallationDto,
|
||||
} from "./admin.dto.js";
|
||||
import {
|
||||
capabilityRegistry,
|
||||
capabilityMetadata,
|
||||
validateCapabilityConfig,
|
||||
capabilityPlugins,
|
||||
getBrandTemplate,
|
||||
getTemplateSampleContent,
|
||||
} from "@personal-brand/config";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
|
||||
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
|
||||
import { AdminWorkspaceCapabilitiesService } from "./modules/workspace/admin-workspace-capabilities.service.js";
|
||||
import { AdminSampleContentService } from "./modules/workspace/admin-sample-content.service.js";
|
||||
import { AdminInquiryService } from "./modules/workspace/admin-inquiry.service.js";
|
||||
import { requireAdminIdentity } from "./modules/workspace/admin-access.identity.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspaceController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly offeringService: AdminOfferingService,
|
||||
private readonly workspaceService: AdminWorkspaceService,
|
||||
private readonly capabilitiesService: AdminWorkspaceCapabilitiesService,
|
||||
private readonly sampleContentService: AdminSampleContentService,
|
||||
private readonly inquiryService: AdminInquiryService,
|
||||
) {}
|
||||
|
||||
@Get("offerings")
|
||||
@@ -98,147 +82,19 @@ class AdminWorkspaceController {
|
||||
@Get("capabilities")
|
||||
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const [templateKey, installations] = await Promise.all([
|
||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||
const template = getBrandTemplate(templateKey);
|
||||
const optionalCapabilityKeys = Object.entries(capabilityRegistry)
|
||||
.filter(([, definition]) => "optional" in definition && definition.optional)
|
||||
.map(([key]) => key);
|
||||
return [...new Set([...(template?.capabilities ?? []), ...optionalCapabilityKeys])]
|
||||
.map((key) => capabilityRegistry[key as keyof typeof capabilityRegistry])
|
||||
.filter(Boolean)
|
||||
.map((definition) => {
|
||||
const item = installed.get(definition.key);
|
||||
const metadata = capabilityMetadata(definition.key);
|
||||
return {
|
||||
id: item?.id ?? null,
|
||||
capabilityKey: definition.key,
|
||||
capabilityVersion: item?.capabilityVersion ?? definition.version,
|
||||
status: item?.status ?? "enabled",
|
||||
config: item?.config ?? {},
|
||||
source: item ? "brand" : "template",
|
||||
...(metadata ?? {}),
|
||||
updatedAt: item?.updatedAt ?? null,
|
||||
};
|
||||
});
|
||||
return this.capabilitiesService.list(brandId);
|
||||
}
|
||||
|
||||
@Get("sample-content/preview")
|
||||
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
const [offerings, trustContent, fields] = await Promise.all([
|
||||
this.prisma.offering.count({ where: { brandId } }),
|
||||
this.prisma.trustContent.count({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
|
||||
]);
|
||||
return {
|
||||
templateKey: sample.templateKey,
|
||||
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
|
||||
counts: {
|
||||
offerings: sample.offerings.length,
|
||||
trustContent: sample.trustContent.length,
|
||||
fields: sample.fields.length,
|
||||
inquiryForms: 1,
|
||||
},
|
||||
willCreateInquiryForm:
|
||||
(await this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } })) === 0,
|
||||
};
|
||||
return this.sampleContentService.preview(brandId);
|
||||
}
|
||||
|
||||
@Post("sample-content/import")
|
||||
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const brandId = identity.brandId;
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
const fieldIssues = validateFieldSnapshot(sample.fields);
|
||||
if (fieldIssues.length) throw new BadRequestException("模板咨询表单示例字段无效");
|
||||
const existing = await this.prisma.brandFieldDefinition.count({
|
||||
where: { brandId, source: "sample" },
|
||||
});
|
||||
const existingOffering = await this.prisma.offering.count({
|
||||
where: { brandId, name: { in: sample.offerings.map((item) => item.name) } },
|
||||
});
|
||||
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
|
||||
const result = await this.prisma.$transaction(async (tx) => {
|
||||
const offerings = await tx.offering.createMany({
|
||||
data: sample.offerings.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary,
|
||||
config: { categoryKey: item.categoryKey },
|
||||
sortOrder,
|
||||
isEnabled: true,
|
||||
})),
|
||||
});
|
||||
const trust = await tx.trustContent.createMany({
|
||||
data: sample.trustContent.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
|
||||
sortOrder,
|
||||
isPublished: false,
|
||||
})),
|
||||
});
|
||||
const fields = await tx.brandFieldDefinition.createMany({
|
||||
data: sample.fields.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
scope: "inquiry",
|
||||
key: item.key,
|
||||
label: item.label,
|
||||
type: item.type,
|
||||
sortOrder,
|
||||
source: "sample",
|
||||
required: item.required,
|
||||
})),
|
||||
});
|
||||
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
|
||||
const inquiryForm = hasEnabledForm
|
||||
? null
|
||||
: await tx.inquiryForm.create({
|
||||
data: {
|
||||
brandId,
|
||||
name: sample.inquiryFormName,
|
||||
purpose: "inquiry",
|
||||
targetType: "brand",
|
||||
submissionAction: "create-inquiry",
|
||||
fieldsSnapshot: sample.fields,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
await tx.capabilityAuditLog.create({
|
||||
data: {
|
||||
brandId,
|
||||
capabilityKey: sample.capabilityKey,
|
||||
actorId: identity.subject,
|
||||
action: "sample_content_imported",
|
||||
toStatus: "enabled",
|
||||
config: {
|
||||
offerings: offerings.count,
|
||||
trustContent: trust.count,
|
||||
fields: fields.count,
|
||||
inquiryForms: inquiryForm ? 1 : 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
offerings: offerings.count,
|
||||
trustContent: trust.count,
|
||||
fields: fields.count,
|
||||
inquiryForms: inquiryForm ? 1 : 0,
|
||||
};
|
||||
});
|
||||
return { imported: true, counts: result };
|
||||
return this.sampleContentService.import(identity.brandId, identity.subject);
|
||||
}
|
||||
|
||||
@Patch("capabilities/:key")
|
||||
@@ -248,51 +104,7 @@ class AdminWorkspaceController {
|
||||
@Body() body: UpdateCapabilityInstallationDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const brandId = identity.brandId;
|
||||
const template = getBrandTemplate(
|
||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
);
|
||||
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
||||
throw new BadRequestException("能力未被当前模板声明");
|
||||
const existing = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
||||
});
|
||||
const definition = capabilityRegistry[key as keyof typeof capabilityRegistry];
|
||||
if (definition && "disablePolicy" in definition && definition.disablePolicy === "disabled")
|
||||
throw new BadRequestException("核心能力不可移除");
|
||||
const configErrors = validateCapabilityConfig(key as never, body.config);
|
||||
if (configErrors === null) throw new BadRequestException("能力配置字段无效");
|
||||
if (Object.keys(configErrors).length)
|
||||
throw new BadRequestException({ message: "能力配置字段无效", errors: configErrors });
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const installation = await tx.capabilityInstallation.upsert({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
||||
create: {
|
||||
brandId,
|
||||
capabilityKey: key,
|
||||
capabilityVersion: definition?.version ?? "1.0.0",
|
||||
status: body.status,
|
||||
config: (body.config ?? {}) as Prisma.InputJsonValue,
|
||||
},
|
||||
update: {
|
||||
...(definition ? { capabilityVersion: definition.version } : {}),
|
||||
status: body.status,
|
||||
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
await tx.capabilityAuditLog.create({
|
||||
data: {
|
||||
brandId,
|
||||
capabilityKey: key,
|
||||
actorId: identity.subject,
|
||||
action: existing ? "updated" : "installed",
|
||||
fromStatus: existing?.status ?? null,
|
||||
toStatus: body.status,
|
||||
config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return installation;
|
||||
});
|
||||
return this.capabilitiesService.update(identity.brandId, identity.subject, key, body);
|
||||
}
|
||||
|
||||
@Get("template/preview")
|
||||
@@ -319,15 +131,7 @@ class AdminWorkspaceController {
|
||||
@Body() body: CreateFieldDefinitionDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.prisma.brandFieldDefinition.create({
|
||||
data: {
|
||||
...body,
|
||||
brandId,
|
||||
source: "custom",
|
||||
options: body.options as Prisma.InputJsonValue,
|
||||
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return this.inquiryService.createField(brandId, body);
|
||||
}
|
||||
|
||||
@Patch("fields/:id")
|
||||
@@ -337,52 +141,25 @@ class AdminWorkspaceController {
|
||||
@Body() body: UpdateFieldDefinitionDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||
where: { id, 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 }),
|
||||
},
|
||||
});
|
||||
return this.inquiryService.updateField(brandId, id, body);
|
||||
}
|
||||
|
||||
@Delete("fields/:id")
|
||||
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||
where: { id, brandId, source: "custom" },
|
||||
});
|
||||
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
|
||||
await this.prisma.brandFieldDefinition.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
return this.inquiryService.deleteField(brandId, id);
|
||||
}
|
||||
|
||||
@Get("forms")
|
||||
listForms(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.prisma.inquiryForm.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
return this.inquiryService.listForms(brandId);
|
||||
}
|
||||
|
||||
@Get("submissions")
|
||||
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return this.inquiryService.listSubmissions(brandId);
|
||||
}
|
||||
|
||||
@Patch("submissions/:id")
|
||||
@@ -392,30 +169,7 @@ class AdminWorkspaceController {
|
||||
@Body() body: UpdateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.inquirySubmission.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
if (!item) throw new BadRequestException("咨询记录不存在");
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const updated = await tx.inquirySubmission.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: body.status,
|
||||
...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }),
|
||||
},
|
||||
});
|
||||
if (item.status !== body.status || body.adminNote !== undefined) {
|
||||
await tx.inquirySubmissionStatusHistory.create({
|
||||
data: {
|
||||
submissionId: id,
|
||||
fromStatus: item.status,
|
||||
toStatus: body.status,
|
||||
adminNote: body.adminNote ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
return this.inquiryService.updateSubmission(brandId, id, body);
|
||||
}
|
||||
|
||||
@Post("forms")
|
||||
@@ -424,20 +178,7 @@ class AdminWorkspaceController {
|
||||
@Body() body: CreateInquiryFormDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
if (validateFieldSnapshot(body.fieldsSnapshot).length)
|
||||
throw new BadRequestException("咨询表单字段定义无效");
|
||||
const { offeringId, ...fields } = body;
|
||||
const targetType = await this.resolveFormTarget(brandId, offeringId);
|
||||
return this.prisma.inquiryForm.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId,
|
||||
targetType,
|
||||
offeringId: offeringId ?? null,
|
||||
version: 1,
|
||||
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return this.inquiryService.createForm(brandId, body);
|
||||
}
|
||||
|
||||
@Patch("forms/:id")
|
||||
@@ -447,46 +188,7 @@ class AdminWorkspaceController {
|
||||
@Body() body: UpdateInquiryFormDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.inquiryForm.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
if (!item) throw new BadRequestException("咨询表单不存在");
|
||||
const { fieldsSnapshot, offeringId, ...fields } = body;
|
||||
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
|
||||
throw new BadRequestException("咨询表单字段定义无效");
|
||||
// offeringId 由用户输入决定表单入口,必须和 targetType 一起改写,避免出现「targetType 是品牌、却挂着业务 id」的漂移。
|
||||
const target =
|
||||
offeringId === undefined
|
||||
? {}
|
||||
: { offeringId, targetType: await this.resolveFormTarget(brandId, offeringId) };
|
||||
return this.prisma.inquiryForm.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...target,
|
||||
...(fieldsSnapshot === undefined
|
||||
? {}
|
||||
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
|
||||
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单可以挂在品牌上,也可以只服务某一个业务提供项。关联的业务必须存在且属于当前品牌,
|
||||
* 否则直接拒绝,不能让数据库外键错误(或跨品牌 id)落库。
|
||||
*/
|
||||
private async resolveFormTarget(
|
||||
brandId: string,
|
||||
offeringId: string | null | undefined,
|
||||
): Promise<"brand" | "offering"> {
|
||||
if (offeringId === undefined || offeringId === null) return "brand";
|
||||
const offering = await this.prisma.offering.findFirst({
|
||||
where: { id: offeringId, brandId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!offering) throw new BadRequestException("关联的业务提供项不存在或不属于当前品牌");
|
||||
return "offering";
|
||||
return this.inquiryService.updateForm(brandId, id, body);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,19 +8,22 @@ import { BookingService } from "./booking.service.js";
|
||||
import { AdminAuthService } from "./admin-auth.service.js";
|
||||
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
|
||||
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
|
||||
import {
|
||||
PublicWorkspaceController,
|
||||
PublicWorkspaceService,
|
||||
} from "./modules/public/public-workspace.controller.js";
|
||||
import { PublicWorkspaceController } from "./modules/public/public-workspace.controller.js";
|
||||
import { PublicWorkspaceService } from "./modules/public/public-workspace.service.js";
|
||||
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js";
|
||||
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
|
||||
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
|
||||
import { AdminWorkspaceCapabilitiesService } from "./modules/workspace/admin-workspace-capabilities.service.js";
|
||||
import { AdminSampleContentService } from "./modules/workspace/admin-sample-content.service.js";
|
||||
import { AdminInquiryService } from "./modules/workspace/admin-inquiry.service.js";
|
||||
import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
|
||||
import { AdminBrandConfigService } from "./modules/admin/admin-brand-config.service.js";
|
||||
import { AdminUploadController } from "./modules/admin/admin-upload.controller.js";
|
||||
import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js";
|
||||
import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
|
||||
import { PublicInquiryFormController } from "./modules/public/public-inquiry-form.controller.js";
|
||||
import { CustomerInquirySubmissionController } from "./modules/customer/customer-inquiry-submission.controller.js";
|
||||
import { CustomerInquirySubmissionService } from "./modules/customer/customer-inquiry-submission.service.js";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
import { AdminMembershipGuard } from "./admin-membership.guard.js";
|
||||
@@ -33,9 +36,11 @@ import {
|
||||
CustomerSessionController,
|
||||
AdminSessionController,
|
||||
} from "./modules/session/session.controller.js";
|
||||
import { CustomerSessionService } from "./modules/session/customer-session.service.js";
|
||||
import { AdminBookingController } from "./modules/admin/admin-booking.controller.js";
|
||||
import { CustomerBookingController } from "./modules/customer/customer-booking.controller.js";
|
||||
import { TenantController } from "./modules/tenant/tenant.controller.js";
|
||||
import { TenantService } from "./modules/tenant/tenant.service.js";
|
||||
import {
|
||||
PublicController,
|
||||
PublicTemplateController,
|
||||
@@ -78,16 +83,23 @@ export class HealthController {
|
||||
WechatAuthService,
|
||||
BookingService,
|
||||
AdminAuthService,
|
||||
CustomerSessionService,
|
||||
TemplateWorkspaceService,
|
||||
AdminAccessService,
|
||||
AdminMembershipGuard,
|
||||
BrandReleaseService,
|
||||
BrandReleaseApiService,
|
||||
AdminMiniAppReleaseService,
|
||||
AdminBrandConfigService,
|
||||
TenantService,
|
||||
CustomerInquirySubmissionService,
|
||||
PublicBrandContextService,
|
||||
PublicWorkspaceService,
|
||||
AdminOfferingService,
|
||||
AdminWorkspaceService,
|
||||
AdminWorkspaceCapabilitiesService,
|
||||
AdminSampleContentService,
|
||||
AdminInquiryService,
|
||||
],
|
||||
exports: [PrismaService, WechatAuthService],
|
||||
})
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface CreateBookingInput {
|
||||
items?: Array<{ offeringId: string; quantity: number }>;
|
||||
}
|
||||
|
||||
export type CustomerIdentity = { brandId: string; openid: string };
|
||||
|
||||
@Injectable()
|
||||
export class BookingService {
|
||||
constructor(
|
||||
@@ -29,6 +31,15 @@ export class BookingService {
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
|
||||
async requireCustomer(identity: CustomerIdentity): Promise<string> {
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return customer.id;
|
||||
}
|
||||
|
||||
async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
|
||||
const snapshot = await this.releases.getPublishedSnapshot(brandId);
|
||||
if (!snapshot) throw new BadRequestException("品牌尚未发布");
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -2,25 +2,18 @@ import { BadRequestException, Body, Controller, Get, Param, Post, Req } from "@n
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { BookingService } from "../../booking.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { CreateBookingDto } from "../../booking.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
@Controller("customer/bookings")
|
||||
export class CustomerBookingController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly bookings: BookingService,
|
||||
) {}
|
||||
constructor(private readonly bookings: BookingService) {}
|
||||
|
||||
@Post()
|
||||
async create(@Req() request: FastifyRequest, @Body() body: CreateBookingDto): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return this.bookings.create(identity.brandId, customer.id, {
|
||||
const customerId = await this.bookings.requireCustomer(identity);
|
||||
return this.bookings.create(identity.brandId, customerId, {
|
||||
...body,
|
||||
extraData: body.extraData as Prisma.InputJsonObject,
|
||||
});
|
||||
@@ -29,21 +22,15 @@ export class CustomerBookingController {
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return this.bookings.listForCustomer(identity.brandId, customer.id);
|
||||
const customerId = await this.bookings.requireCustomer(identity);
|
||||
return this.bookings.listForCustomer(identity.brandId, customerId);
|
||||
}
|
||||
|
||||
@Post(":id/cancel")
|
||||
async cancel(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return this.bookings.cancelForCustomer(identity.brandId, customer.id, id);
|
||||
const customerId = await this.bookings.requireCustomer(identity);
|
||||
return this.bookings.cancelForCustomer(identity.brandId, customerId, id);
|
||||
}
|
||||
|
||||
private identity(request: FastifyRequest): { brandId: string; openid: string } {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
@@ -10,19 +9,14 @@ 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 { CreateInquirySubmissionDto } from "../../booking.dto.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
|
||||
|
||||
@Controller("customer/inquiry-submissions")
|
||||
export class CustomerInquirySubmissionController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
constructor(private readonly submissions: CustomerInquirySubmissionService) {}
|
||||
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
|
||||
const {
|
||||
customerSubject: _customerSubject,
|
||||
@@ -49,36 +43,18 @@ export class CustomerInquirySubmissionController {
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submissions = await this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId: identity.brandId, customerSubject: identity.subject },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true, purpose: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
statusHistory: {
|
||||
select: { fromStatus: true, toStatus: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.subject);
|
||||
return submissions.map((submission) => this.present(submission));
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submission = await this.prisma.inquirySubmission.findFirst({
|
||||
where: { id, brandId: identity.brandId, customerSubject: identity.subject },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true, purpose: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
statusHistory: {
|
||||
select: { fromStatus: true, toStatus: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!submission) throw new NotFoundException("咨询记录不存在");
|
||||
const submission = await this.submissions.getForCustomer(
|
||||
identity.brandId,
|
||||
identity.subject,
|
||||
id,
|
||||
);
|
||||
return this.present(submission);
|
||||
}
|
||||
|
||||
@@ -88,92 +64,7 @@ export class CustomerInquirySubmissionController {
|
||||
@Body() body: CreateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const snapshot = await this.releases.getPublishedSnapshot(identity.brandId);
|
||||
const publishedForm = snapshot && this.releases.publishedForm(snapshot, body.formId);
|
||||
if (!publishedForm) throw new BadRequestException("咨询表单不存在或品牌尚未发布");
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: {
|
||||
id: body.formId,
|
||||
brandId: identity.brandId,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
const offeringId =
|
||||
typeof publishedForm.offeringId === "string" ? publishedForm.offeringId : null;
|
||||
if (offeringId) {
|
||||
const offering = await this.prisma.offering.findFirst({
|
||||
where: { id: offeringId, brandId: identity.brandId, isEnabled: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!offering) throw new BadRequestException("当前业务提供项不可用");
|
||||
}
|
||||
const capabilityKey = publishedForm.purpose === "quote-request" ? "quote-request" : "inquiry";
|
||||
const capability = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: {
|
||||
brandId_capabilityKey: { brandId: identity.brandId, capabilityKey },
|
||||
},
|
||||
});
|
||||
if (capability && capability.status !== "enabled")
|
||||
throw new BadRequestException("当前咨询能力不可用");
|
||||
const fields = Array.isArray(publishedForm.fieldsSnapshot)
|
||||
? (publishedForm.fieldsSnapshot as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
for (const field of fields) {
|
||||
const key = typeof field.key === "string" ? field.key : "";
|
||||
const label = typeof field.label === "string" ? field.label : key;
|
||||
const value = body.values[key];
|
||||
const textValue = typeof value === "string" || typeof value === "number" ? String(value) : "";
|
||||
const empty = value === undefined || value === null || value === "";
|
||||
if (field.required === true && empty) throw new BadRequestException(`${label}不能为空`);
|
||||
if (empty) continue;
|
||||
if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(textValue))
|
||||
throw new BadRequestException(`${label}格式不正确`);
|
||||
if (field.type === "number" && !Number.isFinite(Number(value)))
|
||||
throw new BadRequestException(`${label}必须是数字`);
|
||||
}
|
||||
const visibleFields = fields.filter((field) => this.isVisibleField(field, body.values));
|
||||
const allowedKeys = new Set(visibleFields.map((field) => String(field.key)));
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(body.values).filter(([key]) => allowedKeys.has(key)),
|
||||
);
|
||||
const submission = await this.prisma.inquirySubmission.create({
|
||||
data: {
|
||||
brandId: identity.brandId,
|
||||
customerSubject: identity.subject,
|
||||
inquiryFormId: form.id,
|
||||
offeringId,
|
||||
formVersion: Number(publishedForm.version),
|
||||
fieldsSnapshot: publishedForm.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
values: values as Prisma.InputJsonValue,
|
||||
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
|
||||
},
|
||||
});
|
||||
const submission = await this.submissions.create(identity.brandId, identity.subject, body);
|
||||
return this.present(submission);
|
||||
}
|
||||
|
||||
private visibilityRuleMatches(rule: unknown, values: Record<string, unknown>): boolean {
|
||||
if (!rule || typeof rule !== "object") return true;
|
||||
const item = rule as Record<string, unknown>;
|
||||
if (typeof item.field !== "string") return true;
|
||||
const value = values[item.field];
|
||||
switch (item.operator) {
|
||||
case "exists":
|
||||
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
||||
case "equals":
|
||||
return value === item.value;
|
||||
case "not-equals":
|
||||
return value !== item.value;
|
||||
case "in":
|
||||
return Array.isArray(item.value) && typeof value === "string" && item.value.includes(value);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private isVisibleField(field: Record<string, unknown>, values: Record<string, unknown>): boolean {
|
||||
return (Array.isArray(field.visibleWhen) ? field.visibleWhen : []).every((rule) =>
|
||||
this.visibilityRuleMatches(rule, values),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
import type { CreateInquirySubmissionDto } from "../../booking.dto.js";
|
||||
|
||||
@Injectable()
|
||||
export class CustomerInquirySubmissionService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
|
||||
listForCustomer(brandId: string, customerSubject: string) {
|
||||
return this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId, customerSubject },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true, purpose: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
statusHistory: {
|
||||
select: { fromStatus: true, toStatus: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getForCustomer(brandId: string, customerSubject: string, id: string) {
|
||||
const submission = await this.prisma.inquirySubmission.findFirst({
|
||||
where: { id, brandId, customerSubject },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true, purpose: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
statusHistory: {
|
||||
select: { fromStatus: true, toStatus: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!submission) throw new NotFoundException("咨询记录不存在");
|
||||
return submission;
|
||||
}
|
||||
|
||||
async create(brandId: string, customerSubject: string, body: CreateInquirySubmissionDto) {
|
||||
const snapshot = await this.releases.getPublishedSnapshot(brandId);
|
||||
const publishedForm = snapshot && this.releases.publishedForm(snapshot, body.formId);
|
||||
if (!publishedForm) throw new BadRequestException("咨询表单不存在或品牌尚未发布");
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: { id: body.formId, brandId, isEnabled: true },
|
||||
});
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
const offeringId =
|
||||
typeof publishedForm.offeringId === "string" ? publishedForm.offeringId : null;
|
||||
if (offeringId) {
|
||||
const offering = await this.prisma.offering.findFirst({
|
||||
where: { id: offeringId, brandId, isEnabled: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!offering) throw new BadRequestException("当前业务提供项不可用");
|
||||
}
|
||||
const capabilityKey = publishedForm.purpose === "quote-request" ? "quote-request" : "inquiry";
|
||||
const capability = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey } },
|
||||
});
|
||||
if (capability && capability.status !== "enabled")
|
||||
throw new BadRequestException("当前咨询能力不可用");
|
||||
const fields = Array.isArray(publishedForm.fieldsSnapshot)
|
||||
? (publishedForm.fieldsSnapshot as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
for (const field of fields) {
|
||||
const key = typeof field.key === "string" ? field.key : "";
|
||||
const label = typeof field.label === "string" ? field.label : key;
|
||||
const value = body.values[key];
|
||||
const textValue = typeof value === "string" || typeof value === "number" ? String(value) : "";
|
||||
const empty = value === undefined || value === null || value === "";
|
||||
if (field.required === true && empty) throw new BadRequestException(`${label}不能为空`);
|
||||
if (empty) continue;
|
||||
if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(textValue))
|
||||
throw new BadRequestException(`${label}格式不正确`);
|
||||
if (field.type === "number" && !Number.isFinite(Number(value)))
|
||||
throw new BadRequestException(`${label}必须是数字`);
|
||||
}
|
||||
const visibleFields = fields.filter((field) => this.isVisibleField(field, body.values));
|
||||
const allowedKeys = new Set(visibleFields.map((field) => String(field.key)));
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(body.values).filter(([key]) => allowedKeys.has(key)),
|
||||
);
|
||||
return this.prisma.inquirySubmission.create({
|
||||
data: {
|
||||
brandId,
|
||||
customerSubject,
|
||||
inquiryFormId: form.id,
|
||||
offeringId,
|
||||
formVersion: Number(publishedForm.version),
|
||||
fieldsSnapshot: publishedForm.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
values: values as Prisma.InputJsonValue,
|
||||
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private visibilityRuleMatches(rule: unknown, values: Record<string, unknown>): boolean {
|
||||
if (!rule || typeof rule !== "object") return true;
|
||||
const item = rule as Record<string, unknown>;
|
||||
if (typeof item.field !== "string") return true;
|
||||
const value = values[item.field];
|
||||
switch (item.operator) {
|
||||
case "exists":
|
||||
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
||||
case "equals":
|
||||
return value === item.value;
|
||||
case "not-equals":
|
||||
return value !== item.value;
|
||||
case "in":
|
||||
return Array.isArray(item.value) && typeof value === "string" && item.value.includes(value);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private isVisibleField(field: Record<string, unknown>, values: Record<string, unknown>): boolean {
|
||||
return (Array.isArray(field.visibleWhen) ? field.visibleWhen : []).every((rule) =>
|
||||
this.visibilityRuleMatches(rule, values),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,6 @@
|
||||
import { Controller, Get, Injectable, Query } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
buildBrandReleaseSnapshot,
|
||||
type BrandReleaseSnapshot,
|
||||
} from "../../brand-release.service.js";
|
||||
import { Controller, Get, Query } from "@nestjs/common";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import {
|
||||
assemblePublicWorkspace,
|
||||
createUnpublishedWorkspace,
|
||||
} from "./public-workspace.snapshot-assembler.js";
|
||||
|
||||
@Injectable()
|
||||
export class PublicWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getForBrandId(brandId: string, draft = false): Promise<unknown> {
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
select: { version: true, createdAt: true, snapshot: true },
|
||||
});
|
||||
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
|
||||
if (!release && !draftSnapshot) return createUnpublishedWorkspace();
|
||||
|
||||
const sourceSnapshot = draftSnapshot ?? (release?.snapshot as BrandReleaseSnapshot | null);
|
||||
const snapshot = sourceSnapshot as BrandReleaseSnapshot;
|
||||
return assemblePublicWorkspace({
|
||||
release: release ? { version: release.version, createdAt: release.createdAt } : null,
|
||||
snapshot,
|
||||
draftSnapshot,
|
||||
});
|
||||
}
|
||||
}
|
||||
import { PublicWorkspaceService } from "./public-workspace.service.js";
|
||||
|
||||
@Controller("public/workspace")
|
||||
export class PublicWorkspaceController {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
buildBrandReleaseSnapshot,
|
||||
type BrandReleaseSnapshot,
|
||||
} from "../../brand-release.service.js";
|
||||
import {
|
||||
assemblePublicWorkspace,
|
||||
createUnpublishedWorkspace,
|
||||
} from "./public-workspace.snapshot-assembler.js";
|
||||
|
||||
@Injectable()
|
||||
export class PublicWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getForBrandId(brandId: string, draft = false): Promise<unknown> {
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
select: { version: true, createdAt: true, snapshot: true },
|
||||
});
|
||||
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
|
||||
if (!release && !draftSnapshot) return createUnpublishedWorkspace();
|
||||
|
||||
const sourceSnapshot = draftSnapshot ?? (release?.snapshot as BrandReleaseSnapshot | null);
|
||||
const snapshot = sourceSnapshot as BrandReleaseSnapshot;
|
||||
return assemblePublicWorkspace({
|
||||
release: release ? { version: release.version, createdAt: release.createdAt } : null,
|
||||
snapshot,
|
||||
draftSnapshot,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { signIdentity } from "../../auth.js";
|
||||
import type { WechatSession } from "../../wechat-auth.js";
|
||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||
|
||||
@Injectable()
|
||||
export class CustomerSessionService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
|
||||
async loginWithWechat(session: WechatSession, brandSlug?: string): Promise<{ token: string }> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||
await this.prisma.customerUser.upsert({
|
||||
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
||||
update: { lastLoginAt: new Date() },
|
||||
create: { brandId: brand.id, openid: session.openid },
|
||||
});
|
||||
return {
|
||||
token: signIdentity({ subject: session.openid, brandId: brand.id, role: "customer" }),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,9 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { Body, Controller, Post, Query, Req, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { WechatAuthService } from "../../wechat-auth.js";
|
||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||
import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js";
|
||||
import { signIdentity } from "../../auth.js";
|
||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||
import { CustomerSessionService } from "./customer-session.service.js";
|
||||
import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
@@ -21,8 +11,7 @@ import { readIdentity } from "../../auth.js";
|
||||
export class CustomerSessionController {
|
||||
constructor(
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
private readonly sessions: CustomerSessionService,
|
||||
) {}
|
||||
|
||||
@Post("wechat")
|
||||
@@ -31,20 +20,7 @@ export class CustomerSessionController {
|
||||
@Query("brandSlug") brandSlug?: string,
|
||||
): Promise<{ token: string }> {
|
||||
const session = await this.wechatAuth.exchangeCode(body.code);
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||
await this.prisma.customerUser.upsert({
|
||||
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
||||
update: { lastLoginAt: new Date() },
|
||||
create: { brandId: brand.id, openid: session.openid },
|
||||
});
|
||||
return {
|
||||
token: signIdentity({ subject: session.openid, brandId: brand.id, role: "customer" }),
|
||||
};
|
||||
return this.sessions.loginWithWechat(session, brandSlug);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import {
|
||||
Controller,
|
||||
BadRequestException,
|
||||
Body,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
@@ -12,30 +10,23 @@ import {
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity, signIdentity } from "../../auth.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { TenantService } from "./tenant.service.js";
|
||||
|
||||
@Controller("admin/brands")
|
||||
export class TenantController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly tenants: TenantService,
|
||||
) {}
|
||||
|
||||
@Get("members")
|
||||
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const current = this.adminIdentity(request);
|
||||
return this.prisma.brandMembership.findMany({
|
||||
where: { brandId: current.brandId },
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
return this.tenants.listMembers(current.brandId);
|
||||
}
|
||||
|
||||
@Post("members")
|
||||
@@ -45,36 +36,7 @@ export class TenantController {
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
const username = body.username.trim();
|
||||
const displayName = body.displayName.trim();
|
||||
if (!username || !displayName) throw new BadRequestException("账号和显示名称不能为空");
|
||||
const existing = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (existing) throw new ConflictException("账号已存在,请使用其他账号");
|
||||
const passwordHash = await bcrypt.hash(body.password, 12);
|
||||
const member = await this.prisma.$transaction(async (tx) => {
|
||||
const adminUser = await tx.adminUser.create({
|
||||
data: {
|
||||
username,
|
||||
displayName,
|
||||
passwordHash,
|
||||
role: "admin",
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
},
|
||||
});
|
||||
return tx.brandMembership.create({
|
||||
data: {
|
||||
adminUserId: adminUser.id,
|
||||
brandId: actor.brandId,
|
||||
role: body.role,
|
||||
isEnabled: true,
|
||||
},
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
return member;
|
||||
return this.tenants.createMember(actor.brandId, body);
|
||||
}
|
||||
|
||||
@Patch("members/:id")
|
||||
@@ -85,43 +47,13 @@ export class TenantController {
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
const membership = await this.prisma.brandMembership.findFirst({
|
||||
where: { id, brandId: actor.brandId },
|
||||
});
|
||||
if (!membership) throw new BadRequestException("成员不存在");
|
||||
if (membership.adminUserId === actor.subject) {
|
||||
if (body.isEnabled === false || (body.role && body.role !== membership.role)) {
|
||||
throw new BadRequestException("不能修改自己的角色或停用自己");
|
||||
}
|
||||
}
|
||||
const nextRole = body.role ?? membership.role;
|
||||
const nextEnabled = body.isEnabled ?? membership.isEnabled;
|
||||
if (membership.role === "owner" && (nextRole !== "owner" || !nextEnabled)) {
|
||||
const ownerCount = await this.prisma.brandMembership.count({
|
||||
where: { brandId: actor.brandId, role: "owner", isEnabled: true },
|
||||
});
|
||||
if (ownerCount <= 1) throw new BadRequestException("品牌至少需要保留一位启用的负责人");
|
||||
}
|
||||
return this.prisma.brandMembership.update({
|
||||
where: { id: membership.id },
|
||||
data: {
|
||||
...(body.role ? { role: body.role } : {}),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
},
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
});
|
||||
return this.tenants.updateMember(actor.brandId, actor.subject, id, body);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.adminIdentity(request);
|
||||
return this.prisma.brandMembership.findMany({
|
||||
where: { adminUserId: identity.subject, isEnabled: true },
|
||||
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
return this.tenants.listMemberships(identity.subject);
|
||||
}
|
||||
|
||||
@Post(":brandId/switch")
|
||||
@@ -130,15 +62,7 @@ export class TenantController {
|
||||
@Param("brandId") brandId: string,
|
||||
): Promise<{ token: string; brand: unknown }> {
|
||||
const identity = this.adminIdentity(request);
|
||||
const membership = await this.prisma.brandMembership.findFirst({
|
||||
where: { adminUserId: identity.subject, brandId, isEnabled: true },
|
||||
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||
});
|
||||
if (!membership) throw new ForbiddenException("没有该品牌的管理权限");
|
||||
return {
|
||||
token: signIdentity({ subject: identity.subject, brandId, role: "admin" }),
|
||||
brand: membership.brand,
|
||||
};
|
||||
return this.tenants.switchBrand(identity, brandId);
|
||||
}
|
||||
|
||||
private adminIdentity(request: FastifyRequest) {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from "@nestjs/common";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity, signIdentity } from "../../auth.js";
|
||||
import type { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
|
||||
|
||||
type AdminIdentity = ReturnType<typeof readIdentity>;
|
||||
|
||||
@Injectable()
|
||||
export class TenantService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
listMembers(brandId: string) {
|
||||
return this.prisma.brandMembership.findMany({
|
||||
where: { brandId },
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
async createMember(brandId: string, body: CreateBrandMemberDto) {
|
||||
const username = body.username.trim();
|
||||
const displayName = body.displayName.trim();
|
||||
if (!username || !displayName) throw new BadRequestException("账号和显示名称不能为空");
|
||||
const existing = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (existing) throw new ConflictException("账号已存在,请使用其他账号");
|
||||
const passwordHash = await bcrypt.hash(body.password, 12);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const adminUser = await tx.adminUser.create({
|
||||
data: {
|
||||
username,
|
||||
displayName,
|
||||
passwordHash,
|
||||
role: "admin",
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
},
|
||||
});
|
||||
return tx.brandMembership.create({
|
||||
data: {
|
||||
adminUserId: adminUser.id,
|
||||
brandId,
|
||||
role: body.role,
|
||||
isEnabled: true,
|
||||
},
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async updateMember(
|
||||
brandId: string,
|
||||
actorSubject: string,
|
||||
id: string,
|
||||
body: UpdateBrandMemberDto,
|
||||
) {
|
||||
const membership = await this.prisma.brandMembership.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
if (!membership) throw new BadRequestException("成员不存在");
|
||||
if (membership.adminUserId === actorSubject) {
|
||||
if (body.isEnabled === false || (body.role && body.role !== membership.role)) {
|
||||
throw new BadRequestException("不能修改自己的角色或停用自己");
|
||||
}
|
||||
}
|
||||
const nextRole = body.role ?? membership.role;
|
||||
const nextEnabled = body.isEnabled ?? membership.isEnabled;
|
||||
if (membership.role === "owner" && (nextRole !== "owner" || !nextEnabled)) {
|
||||
const ownerCount = await this.prisma.brandMembership.count({
|
||||
where: { brandId, role: "owner", isEnabled: true },
|
||||
});
|
||||
if (ownerCount <= 1) throw new BadRequestException("品牌至少需要保留一位启用的负责人");
|
||||
}
|
||||
return this.prisma.brandMembership.update({
|
||||
where: { id: membership.id },
|
||||
data: {
|
||||
...(body.role ? { role: body.role } : {}),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
},
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
listMemberships(subject: string) {
|
||||
return this.prisma.brandMembership.findMany({
|
||||
where: { adminUserId: subject, isEnabled: true },
|
||||
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
async switchBrand(identity: AdminIdentity, brandId: string) {
|
||||
const membership = await this.prisma.brandMembership.findFirst({
|
||||
where: { adminUserId: identity.subject, brandId, isEnabled: true },
|
||||
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||
});
|
||||
if (!membership) throw new ForbiddenException("没有该品牌的管理权限");
|
||||
return {
|
||||
token: signIdentity({ subject: identity.subject, brandId, role: "admin" }),
|
||||
brand: membership.brand,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import type {
|
||||
CreateFieldDefinitionDto,
|
||||
CreateInquiryFormDto,
|
||||
UpdateFieldDefinitionDto,
|
||||
UpdateInquiryFormDto,
|
||||
UpdateInquirySubmissionDto,
|
||||
} from "../../admin.dto.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminInquiryService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
createField(brandId: string, body: CreateFieldDefinitionDto) {
|
||||
return this.prisma.brandFieldDefinition.create({
|
||||
data: {
|
||||
...body,
|
||||
brandId,
|
||||
source: "custom",
|
||||
options: body.options as Prisma.InputJsonValue,
|
||||
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateField(brandId: string, id: string, body: UpdateFieldDefinitionDto) {
|
||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||
where: { id, 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 }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async deleteField(brandId: string, id: string) {
|
||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||
where: { id, brandId, source: "custom" },
|
||||
});
|
||||
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
|
||||
await this.prisma.brandFieldDefinition.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
listForms(brandId: string) {
|
||||
return this.prisma.inquiryForm.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async createForm(brandId: string, body: CreateInquiryFormDto) {
|
||||
if (validateFieldSnapshot(body.fieldsSnapshot).length)
|
||||
throw new BadRequestException("咨询表单字段定义无效");
|
||||
const { offeringId, ...fields } = body;
|
||||
const targetType = await this.resolveFormTarget(brandId, offeringId);
|
||||
return this.prisma.inquiryForm.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId,
|
||||
targetType,
|
||||
offeringId: offeringId ?? null,
|
||||
version: 1,
|
||||
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateForm(brandId: string, id: string, body: UpdateInquiryFormDto) {
|
||||
const item = await this.prisma.inquiryForm.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
if (!item) throw new BadRequestException("咨询表单不存在");
|
||||
const { fieldsSnapshot, offeringId, ...fields } = body;
|
||||
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
|
||||
throw new BadRequestException("咨询表单字段定义无效");
|
||||
const target =
|
||||
offeringId === undefined
|
||||
? {}
|
||||
: { offeringId, targetType: await this.resolveFormTarget(brandId, offeringId) };
|
||||
return this.prisma.inquiryForm.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...target,
|
||||
...(fieldsSnapshot === undefined
|
||||
? {}
|
||||
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
|
||||
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
listSubmissions(brandId: string) {
|
||||
return this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async updateSubmission(brandId: string, id: string, body: UpdateInquirySubmissionDto) {
|
||||
const item = await this.prisma.inquirySubmission.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
if (!item) throw new BadRequestException("咨询记录不存在");
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const updated = await tx.inquirySubmission.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: body.status,
|
||||
...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }),
|
||||
},
|
||||
});
|
||||
if (item.status !== body.status || body.adminNote !== undefined) {
|
||||
await tx.inquirySubmissionStatusHistory.create({
|
||||
data: {
|
||||
submissionId: id,
|
||||
fromStatus: item.status,
|
||||
toStatus: body.status,
|
||||
adminNote: body.adminNote ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
private async resolveFormTarget(
|
||||
brandId: string,
|
||||
offeringId: string | null | undefined,
|
||||
): Promise<"brand" | "offering"> {
|
||||
if (offeringId === undefined || offeringId === null) return "brand";
|
||||
const offering = await this.prisma.offering.findFirst({
|
||||
where: { id: offeringId, brandId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!offering) throw new BadRequestException("关联的业务提供项不存在或不属于当前品牌");
|
||||
return "offering";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { getTemplateSampleContent } from "@personal-brand/config";
|
||||
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminSampleContentService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
) {}
|
||||
|
||||
async preview(brandId: string) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
const [offerings, trustContent, fields, enabledForms] = await Promise.all([
|
||||
this.prisma.offering.count({ where: { brandId } }),
|
||||
this.prisma.trustContent.count({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
|
||||
this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } }),
|
||||
]);
|
||||
return {
|
||||
templateKey: sample.templateKey,
|
||||
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
|
||||
counts: {
|
||||
offerings: sample.offerings.length,
|
||||
trustContent: sample.trustContent.length,
|
||||
fields: sample.fields.length,
|
||||
inquiryForms: 1,
|
||||
},
|
||||
willCreateInquiryForm: enabledForms === 0,
|
||||
};
|
||||
}
|
||||
|
||||
async import(brandId: string, actorId: string) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
if (validateFieldSnapshot(sample.fields).length)
|
||||
throw new BadRequestException("模板咨询表单示例字段无效");
|
||||
const existing = await this.prisma.brandFieldDefinition.count({
|
||||
where: { brandId, source: "sample" },
|
||||
});
|
||||
const existingOffering = await this.prisma.offering.count({
|
||||
where: { brandId, name: { in: sample.offerings.map((item) => item.name) } },
|
||||
});
|
||||
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
|
||||
const result = await this.prisma.$transaction(async (tx) => {
|
||||
const offerings = await tx.offering.createMany({
|
||||
data: sample.offerings.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary,
|
||||
config: { categoryKey: item.categoryKey },
|
||||
sortOrder,
|
||||
isEnabled: true,
|
||||
})),
|
||||
});
|
||||
const trust = await tx.trustContent.createMany({
|
||||
data: sample.trustContent.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
|
||||
sortOrder,
|
||||
isPublished: false,
|
||||
})),
|
||||
});
|
||||
const fields = await tx.brandFieldDefinition.createMany({
|
||||
data: sample.fields.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
scope: "inquiry",
|
||||
key: item.key,
|
||||
label: item.label,
|
||||
type: item.type,
|
||||
sortOrder,
|
||||
source: "sample",
|
||||
required: item.required,
|
||||
})),
|
||||
});
|
||||
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
|
||||
const inquiryForm = hasEnabledForm
|
||||
? null
|
||||
: await tx.inquiryForm.create({
|
||||
data: {
|
||||
brandId,
|
||||
name: sample.inquiryFormName,
|
||||
purpose: "inquiry",
|
||||
targetType: "brand",
|
||||
submissionAction: "create-inquiry",
|
||||
fieldsSnapshot: sample.fields,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
await tx.capabilityAuditLog.create({
|
||||
data: {
|
||||
brandId,
|
||||
capabilityKey: sample.capabilityKey,
|
||||
actorId,
|
||||
action: "sample_content_imported",
|
||||
toStatus: "enabled",
|
||||
config: {
|
||||
offerings: offerings.count,
|
||||
trustContent: trust.count,
|
||||
fields: fields.count,
|
||||
inquiryForms: inquiryForm ? 1 : 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
offerings: offerings.count,
|
||||
trustContent: trust.count,
|
||||
fields: fields.count,
|
||||
inquiryForms: inquiryForm ? 1 : 0,
|
||||
};
|
||||
});
|
||||
return { imported: true, counts: result };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
capabilityMetadata,
|
||||
capabilityPlugins,
|
||||
capabilityRegistry,
|
||||
getBrandTemplate,
|
||||
validateCapabilityConfig,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminWorkspaceCapabilitiesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
) {}
|
||||
|
||||
async list(brandId: string) {
|
||||
const [templateKey, installations] = await Promise.all([
|
||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||
const template = getBrandTemplate(templateKey);
|
||||
const optionalCapabilityKeys = Object.entries(capabilityRegistry)
|
||||
.filter(([, definition]) => "optional" in definition && definition.optional)
|
||||
.map(([key]) => key);
|
||||
return [...new Set([...(template?.capabilities ?? []), ...optionalCapabilityKeys])]
|
||||
.map((key) => capabilityRegistry[key as keyof typeof capabilityRegistry])
|
||||
.filter(Boolean)
|
||||
.map((definition) => {
|
||||
const item = installed.get(definition.key);
|
||||
const metadata = capabilityMetadata(definition.key);
|
||||
return {
|
||||
id: item?.id ?? null,
|
||||
capabilityKey: definition.key,
|
||||
capabilityVersion: item?.capabilityVersion ?? definition.version,
|
||||
status: item?.status ?? "enabled",
|
||||
config: item?.config ?? {},
|
||||
source: item ? "brand" : "template",
|
||||
...(metadata ?? {}),
|
||||
updatedAt: item?.updatedAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async update(
|
||||
brandId: string,
|
||||
actorId: string,
|
||||
key: string,
|
||||
body: UpdateCapabilityInstallationDto,
|
||||
) {
|
||||
const template = getBrandTemplate(
|
||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
);
|
||||
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
||||
throw new BadRequestException("能力未被当前模板声明");
|
||||
const existing = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
||||
});
|
||||
const definition = capabilityRegistry[key as keyof typeof capabilityRegistry];
|
||||
if (definition && "disablePolicy" in definition && definition.disablePolicy === "disabled")
|
||||
throw new BadRequestException("核心能力不可移除");
|
||||
const configErrors = validateCapabilityConfig(key as never, body.config);
|
||||
if (configErrors === null) throw new BadRequestException("能力配置字段无效");
|
||||
if (Object.keys(configErrors).length)
|
||||
throw new BadRequestException({ message: "能力配置字段无效", errors: configErrors });
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const installation = await tx.capabilityInstallation.upsert({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
||||
create: {
|
||||
brandId,
|
||||
capabilityKey: key,
|
||||
capabilityVersion: definition?.version ?? "1.0.0",
|
||||
status: body.status,
|
||||
config: (body.config ?? {}) as Prisma.InputJsonValue,
|
||||
},
|
||||
update: {
|
||||
...(definition ? { capabilityVersion: definition.version } : {}),
|
||||
status: body.status,
|
||||
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
await tx.capabilityAuditLog.create({
|
||||
data: {
|
||||
brandId,
|
||||
capabilityKey: key,
|
||||
actorId,
|
||||
action: existing ? "updated" : "installed",
|
||||
fromStatus: existing?.status ?? null,
|
||||
toStatus: body.status,
|
||||
config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return installation;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import { PublicWorkspaceService } from "../public/public-workspace.controller.js";
|
||||
import { PublicWorkspaceService } from "../public/public-workspace.service.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminWorkspaceService {
|
||||
|
||||
@@ -61,6 +61,20 @@ export class TemplateWorkspaceService {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
listTrustContent(brandId: string) {
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: { brandId },
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
async deleteTrustContent(brandId: string, id: string) {
|
||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
await this.prisma.trustContent.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
||||
const [brand, installation] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({
|
||||
|
||||
Reference in new issue
Block a user