refactor: 完成公开与客户控制器拆分
This commit is contained in:
1 parent
178ffc2c11
commit
4902a564f0
5 files changed
+214
-223
No files matched your search
+4
-223
@@ -1,43 +1,17 @@
|
||||
import "reflect-metadata";
|
||||
import {
|
||||
BadRequestException,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
ForbiddenException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Module,
|
||||
Param,
|
||||
Post,
|
||||
Patch,
|
||||
Query,
|
||||
Req,
|
||||
ValidationPipe,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Controller, Get, Module, ValidationPipe } from "@nestjs/common";
|
||||
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { WechatAuthService } from "./wechat-auth.js";
|
||||
import { BookingService } from "./booking.service.js";
|
||||
import { CreateInquirySubmissionDto } from "./booking.dto.js";
|
||||
import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "./admin.dto.js";
|
||||
import { AdminAuthService } from "./admin-auth.service.js";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { readIdentity } from "./auth.js";
|
||||
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
|
||||
import {
|
||||
brandTemplates,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
resolveCapabilities,
|
||||
capabilityPlugins,
|
||||
visualTemplates,
|
||||
} from "@personal-brand/config";
|
||||
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
|
||||
import { PublicWorkspaceController } from "./modules/public/public-workspace.controller.js";
|
||||
import { AdminConfigController } from "./modules/admin/admin-config.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 { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
import { AdminMembershipGuard } from "./admin-membership.guard.js";
|
||||
@@ -53,12 +27,6 @@ import {
|
||||
PublicTemplateController,
|
||||
PublicTrustContentController,
|
||||
} from "./modules/public/public.controller.js";
|
||||
import type {
|
||||
RuntimeInquiryField,
|
||||
RuntimeOffering,
|
||||
RuntimeWorkspace,
|
||||
RuntimeModule,
|
||||
} from "@personal-brand/types";
|
||||
|
||||
@Controller("health")
|
||||
export class HealthController {
|
||||
@@ -68,193 +36,6 @@ export class HealthController {
|
||||
}
|
||||
}
|
||||
|
||||
@Controller("public/offerings")
|
||||
export class PublicOfferingController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@Get()
|
||||
async list(): Promise<unknown> {
|
||||
const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
const items = await this.prisma.offering.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: {
|
||||
inquiryForms: {
|
||||
where: { isEnabled: true },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { id: true, name: true, purpose: true, targetType: true, version: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
return items.map((item) => this.present(item));
|
||||
}
|
||||
@Get(":id")
|
||||
async get(@Param("id") id: string): Promise<unknown> {
|
||||
const item = await this.prisma.offering.findFirst({
|
||||
where: {
|
||||
id,
|
||||
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
||||
isEnabled: true,
|
||||
},
|
||||
include: {
|
||||
inquiryForms: {
|
||||
where: { isEnabled: true },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { id: true, name: true, purpose: true, targetType: true, version: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!item) throw new BadRequestException("业务提供项不存在");
|
||||
return this.present(item);
|
||||
}
|
||||
private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown {
|
||||
const config = (item.config ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
...item,
|
||||
sections: config.sections ?? [],
|
||||
media: config.media ?? [],
|
||||
cta: config.cta ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Controller("public/inquiry-forms")
|
||||
export class PublicInquiryFormController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@Get(":id")
|
||||
async get(@Param("id") id: string): Promise<unknown> {
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: {
|
||||
id,
|
||||
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
||||
isEnabled: true,
|
||||
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
|
||||
},
|
||||
});
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
return form;
|
||||
}
|
||||
}
|
||||
|
||||
@Controller("customer/inquiry-submissions")
|
||||
export class CustomerInquirySubmissionController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
|
||||
const {
|
||||
customerSubject: _customerSubject,
|
||||
adminNote: _adminNote,
|
||||
...publicSubmission
|
||||
} = submission;
|
||||
void _customerSubject;
|
||||
void _adminNote;
|
||||
return publicSubmission;
|
||||
}
|
||||
private identity(request: FastifyRequest): ReturnType<typeof readIdentity> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少客户登录态");
|
||||
try {
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
|
||||
return identity;
|
||||
} catch (error) {
|
||||
if (error instanceof ForbiddenException) throw error;
|
||||
throw new UnauthorizedException("客户登录态无效或已过期");
|
||||
}
|
||||
}
|
||||
|
||||
@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" },
|
||||
},
|
||||
},
|
||||
});
|
||||
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("咨询记录不存在");
|
||||
return this.present(submission);
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: {
|
||||
id: body.formId,
|
||||
brandId: identity.brandId,
|
||||
isEnabled: true,
|
||||
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
|
||||
},
|
||||
});
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
const capabilityKey = form.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(form.fieldsSnapshot)
|
||||
? (form.fieldsSnapshot as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
for (const field of fields) {
|
||||
const key = typeof field.key === "string" ? field.key : "";
|
||||
const value = body.values[key];
|
||||
const empty = value === undefined || value === null || value === "";
|
||||
if (field.required === true && empty)
|
||||
throw new BadRequestException(`${String(field.label ?? key)}不能为空`);
|
||||
if (empty) continue;
|
||||
if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(String(value)))
|
||||
throw new BadRequestException(`${String(field.label ?? key)}格式不正确`);
|
||||
if (field.type === "number" && !Number.isFinite(Number(value)))
|
||||
throw new BadRequestException(`${String(field.label ?? key)}必须是数字`);
|
||||
}
|
||||
const allowedKeys = new Set(fields.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: form.offeringId,
|
||||
formVersion: form.version,
|
||||
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
values: values as Prisma.InputJsonValue,
|
||||
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
|
||||
},
|
||||
});
|
||||
return this.present(submission);
|
||||
}
|
||||
}
|
||||
|
||||
@Module({
|
||||
controllers: [
|
||||
HealthController,
|
||||
|
||||
Reference in new issue
Block a user