1018 lines
34 KiB
TypeScript
1018 lines
34 KiB
TypeScript
import "reflect-metadata";
|
|
import {
|
|
BadRequestException,
|
|
UnauthorizedException,
|
|
ForbiddenException,
|
|
Body,
|
|
Controller,
|
|
Delete,
|
|
Get,
|
|
Module,
|
|
Param,
|
|
Post,
|
|
Patch,
|
|
Query,
|
|
Req,
|
|
ValidationPipe,
|
|
} from "@nestjs/common";
|
|
import { NestFactory } from "@nestjs/core";
|
|
import { BookingStatus, Prisma } from "@prisma/client";
|
|
import { FastifyAdapter } from "@nestjs/platform-fastify";
|
|
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 { CreateBookingDto, CreateInquirySubmissionDto } from "./booking.dto.js";
|
|
import {
|
|
CreateServiceDto,
|
|
CreateTagDto,
|
|
CreateTrustContentDto,
|
|
UpdateBookingStatusDto,
|
|
UpdateBookingTagsDto,
|
|
UpdateBrandDto,
|
|
UpdateServiceDto,
|
|
UpdateTrustContentDto,
|
|
InstallTemplateDto,
|
|
CreateOfferingDto,
|
|
UpdateOfferingDto,
|
|
UpdateModuleDto,
|
|
CreateFieldDefinitionDto,
|
|
UpdateFieldDefinitionDto,
|
|
CreateInquiryFormDto,
|
|
UpdateInquiryFormDto,
|
|
} from "./admin.dto.js";
|
|
import { AdminAuthService } from "./admin-auth.service.js";
|
|
import { AdminLoginDto } from "./admin-auth.dto.js";
|
|
import type { FastifyRequest } from "fastify";
|
|
import { Transform } from "class-transformer";
|
|
import type { TransformFnParams } from "class-transformer";
|
|
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
|
import { readIdentity, signIdentity } from "./auth.js";
|
|
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
|
|
import { brandTemplates, getBrandTemplate } from "@personal-brand/config";
|
|
|
|
@Controller("health")
|
|
export class HealthController {
|
|
@Get()
|
|
check(): { status: string; service: string } {
|
|
return { status: "ok", service: "personal-brand-api" };
|
|
}
|
|
}
|
|
|
|
@Controller("public")
|
|
export class PublicController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
@Get("brand")
|
|
async brand(): Promise<unknown> {
|
|
return this.prisma.brandProfile.findFirst({
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
templateKey: true,
|
|
tagline: true,
|
|
description: true,
|
|
avatarUrl: true,
|
|
coverUrl: true,
|
|
hours: true,
|
|
address: true,
|
|
deliveryNote: true,
|
|
contactPhone: true,
|
|
contactWechat: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Get("services")
|
|
async services(): Promise<unknown> {
|
|
return this.prisma.service.findMany({
|
|
where: { isEnabled: true },
|
|
orderBy: { sortOrder: "asc" },
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
description: true,
|
|
coverUrl: true,
|
|
priceText: true,
|
|
priceAmount: true,
|
|
bookingEnabled: true,
|
|
categoryKey: true,
|
|
config: true,
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
@Controller("public/trust-content")
|
|
export class PublicTrustContentController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
@Get()
|
|
list(): Promise<unknown> {
|
|
return this.prisma.trustContent.findMany({
|
|
where: {
|
|
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
isPublished: true,
|
|
},
|
|
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
|
});
|
|
}
|
|
}
|
|
|
|
@Controller("public/templates")
|
|
export class PublicTemplateController {
|
|
@Get(":key")
|
|
get(@Param("key") key: string): unknown {
|
|
const template = getBrandTemplate(key);
|
|
if (!template) throw new BadRequestException("行业模板不存在");
|
|
return template;
|
|
}
|
|
}
|
|
|
|
@Controller("public/workspace")
|
|
export class PublicWorkspaceController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
@Get()
|
|
async get(): Promise<unknown> {
|
|
const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
|
const [brand, modules, fields, offerings, inquiryForm] = await Promise.all([
|
|
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
|
this.prisma.brandModule.findMany({
|
|
where: { brandId, isEnabled: true },
|
|
orderBy: { sortOrder: "asc" },
|
|
}),
|
|
this.prisma.brandFieldDefinition.findMany({
|
|
where: { brandId, isVisible: true },
|
|
orderBy: { sortOrder: "asc" },
|
|
}),
|
|
this.prisma.offering.findMany({
|
|
where: { brandId, isEnabled: true },
|
|
orderBy: { sortOrder: "asc" },
|
|
}),
|
|
this.prisma.inquiryForm.findFirst({
|
|
where: { brandId, isEnabled: true },
|
|
orderBy: { updatedAt: "desc" },
|
|
}),
|
|
]);
|
|
return { brand, modules, fields, offerings, inquiryForm };
|
|
}
|
|
}
|
|
|
|
@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" },
|
|
});
|
|
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,
|
|
},
|
|
});
|
|
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,
|
|
},
|
|
});
|
|
if (!form) throw new BadRequestException("咨询表单不存在");
|
|
return form;
|
|
}
|
|
}
|
|
|
|
@Controller("customer/inquiry-submissions")
|
|
export class CustomerInquirySubmissionController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
@Post()
|
|
async create(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: CreateInquirySubmissionDto,
|
|
): Promise<unknown> {
|
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
if (!token) throw new UnauthorizedException("缺少客户登录态");
|
|
let identity;
|
|
try {
|
|
identity = readIdentity(token);
|
|
} catch {
|
|
throw new UnauthorizedException("客户登录态无效或已过期");
|
|
}
|
|
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
|
|
const form = await this.prisma.inquiryForm.findFirst({
|
|
where: { id: body.formId, brandId: identity.brandId, isEnabled: true },
|
|
});
|
|
if (!form) throw new BadRequestException("咨询表单不存在");
|
|
return this.prisma.inquirySubmission.create({
|
|
data: {
|
|
brandId: identity.brandId,
|
|
inquiryFormId: form.id,
|
|
formVersion: form.version,
|
|
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
|
|
values: body.values as Prisma.InputJsonValue,
|
|
activeFields: Object.fromEntries(Object.keys(body.values).map((key) => [key, true])),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
@Controller("admin/workspace")
|
|
export class AdminWorkspaceController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
private brandId(): string {
|
|
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
|
}
|
|
|
|
@Get("offerings")
|
|
async listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const items = await this.prisma.offering.findMany({
|
|
where: { brandId: this.brandId() },
|
|
orderBy: { sortOrder: "asc" },
|
|
});
|
|
return items.map((item) => {
|
|
const config = (item.config ?? {}) as Record<string, unknown>;
|
|
return {
|
|
...item,
|
|
sections: config.sections ?? [],
|
|
media: config.media ?? [],
|
|
cta: config.cta ?? null,
|
|
};
|
|
});
|
|
}
|
|
|
|
@Post("offerings")
|
|
createOffering(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: CreateOfferingDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const { config, sections, media, cta, ...fields } = body;
|
|
return this.prisma.offering.create({
|
|
data: {
|
|
...fields,
|
|
brandId: this.brandId(),
|
|
config: {
|
|
...(config ?? {}),
|
|
...(sections === undefined ? {} : { sections }),
|
|
...(media === undefined ? {} : { media }),
|
|
...(cta === undefined ? {} : { cta }),
|
|
} as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Patch("offerings/:id")
|
|
async updateOffering(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateOfferingDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.offering.findFirst({ where: { id, brandId: this.brandId() } });
|
|
if (!item) throw new BadRequestException("业务提供项不存在");
|
|
const { config, sections, media, cta, ...fields } = body;
|
|
return this.prisma.offering.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(config === undefined &&
|
|
sections === undefined &&
|
|
media === undefined &&
|
|
cta === undefined
|
|
? {}
|
|
: {
|
|
config: {
|
|
...(config ?? {}),
|
|
...(sections === undefined ? {} : { sections }),
|
|
...(media === undefined ? {} : { media }),
|
|
...(cta === undefined ? {} : { cta }),
|
|
} as Prisma.InputJsonValue,
|
|
}),
|
|
},
|
|
});
|
|
}
|
|
private requireAdmin(request: FastifyRequest): void {
|
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
|
let identity;
|
|
try {
|
|
identity = readIdentity(token);
|
|
} catch {
|
|
throw new UnauthorizedException("管理员登录态无效或已过期");
|
|
}
|
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
|
}
|
|
@Get()
|
|
async get(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const brandId = this.brandId();
|
|
const [brand, installations, modules, fields, offerings, forms] = await Promise.all([
|
|
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
|
this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }),
|
|
this.prisma.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
|
this.prisma.brandFieldDefinition.findMany({
|
|
where: { brandId },
|
|
orderBy: { sortOrder: "asc" },
|
|
}),
|
|
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
|
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
|
|
]);
|
|
return { brand, installations, modules, fields, offerings, forms };
|
|
}
|
|
@Post("install")
|
|
async install(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: InstallTemplateDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const brandId = this.brandId();
|
|
const template = getBrandTemplate(body.templateKey);
|
|
if (!template) throw new BadRequestException("行业模板不存在");
|
|
const existing = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
|
|
if (existing) {
|
|
if (existing.templateKey === body.templateKey)
|
|
throw new BadRequestException("该模板已经安装");
|
|
throw new BadRequestException("品牌已经安装主模板,请先完成模板切换流程");
|
|
}
|
|
return this.prisma.$transaction(async (tx) => {
|
|
const installation = await tx.brandTemplateInstallation.create({
|
|
data: {
|
|
brandId,
|
|
templateKey: body.templateKey,
|
|
templateVersion: template.version,
|
|
configSnapshot: template as unknown as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
await tx.brandModule.createMany({
|
|
data: template.modules.map(({ type, title }, sortOrder) => ({
|
|
brandId,
|
|
type,
|
|
title,
|
|
sortOrder,
|
|
source: "template",
|
|
})),
|
|
});
|
|
await tx.brandFieldDefinition.createMany({
|
|
data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({
|
|
brandId,
|
|
scope,
|
|
key,
|
|
label,
|
|
type,
|
|
sortOrder,
|
|
source: "core",
|
|
required,
|
|
})),
|
|
});
|
|
return { installation, template };
|
|
});
|
|
}
|
|
|
|
@Get("template/preview")
|
|
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
|
where: { brandId: this.brandId() },
|
|
});
|
|
if (!installation) throw new BadRequestException("尚未安装行业模板");
|
|
const template = getBrandTemplate(installation.templateKey);
|
|
if (!template) throw new BadRequestException("已安装模板不存在");
|
|
const [modules, fields] = await Promise.all([
|
|
this.prisma.brandModule.findMany({ where: { brandId: this.brandId() } }),
|
|
this.prisma.brandFieldDefinition.findMany({ where: { brandId: this.brandId() } }),
|
|
]);
|
|
const missingModules = template.modules.filter(
|
|
(item) =>
|
|
!modules.some((current) => current.type === item.type && current.source === "template"),
|
|
);
|
|
const missingFields = template.fields.filter(
|
|
(item) => !fields.some((current) => current.scope === item.scope && current.key === item.key),
|
|
);
|
|
return {
|
|
currentVersion: installation.templateVersion,
|
|
latestVersion: template.version,
|
|
canUpgrade: installation.templateVersion !== template.version,
|
|
canRollback:
|
|
Array.isArray(installation.previousSnapshots) && installation.previousSnapshots.length > 0,
|
|
missingModules,
|
|
missingFields,
|
|
};
|
|
}
|
|
|
|
@Post("template/upgrade")
|
|
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const brandId = this.brandId();
|
|
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
|
where: { brandId },
|
|
});
|
|
if (!installation) throw new BadRequestException("尚未安装行业模板");
|
|
const template = getBrandTemplate(installation.templateKey);
|
|
if (!template) throw new BadRequestException("已安装模板不存在");
|
|
if (installation.templateVersion === template.version)
|
|
throw new BadRequestException("当前模板已经是最新版本");
|
|
return this.prisma.$transaction(async (tx) => {
|
|
const [modules, fields] = await Promise.all([
|
|
tx.brandModule.findMany({ where: { brandId } }),
|
|
tx.brandFieldDefinition.findMany({ where: { brandId } }),
|
|
]);
|
|
const missingModules = template.modules.filter(
|
|
(item) =>
|
|
!modules.some((current) => current.type === item.type && current.source === "template"),
|
|
);
|
|
const missingFields = template.fields.filter(
|
|
(item) =>
|
|
!fields.some((current) => current.scope === item.scope && current.key === item.key),
|
|
);
|
|
await tx.brandModule.createMany({
|
|
data: missingModules.map(({ type, title }, index) => ({
|
|
brandId,
|
|
type,
|
|
title,
|
|
sortOrder: modules.length + index,
|
|
source: "template",
|
|
})),
|
|
});
|
|
await tx.brandFieldDefinition.createMany({
|
|
data: missingFields.map(({ scope, key, label, type, required }, index) => ({
|
|
brandId,
|
|
scope,
|
|
key,
|
|
label,
|
|
type,
|
|
required,
|
|
sortOrder: fields.length + index,
|
|
source: "template",
|
|
})),
|
|
});
|
|
const previousSnapshots = Array.isArray(installation.previousSnapshots)
|
|
? installation.previousSnapshots
|
|
: [];
|
|
const updated = await tx.brandTemplateInstallation.update({
|
|
where: { id: installation.id },
|
|
data: {
|
|
templateVersion: template.version,
|
|
configSnapshot: template as unknown as Prisma.InputJsonValue,
|
|
previousSnapshots: [
|
|
...previousSnapshots,
|
|
installation.configSnapshot,
|
|
] as unknown as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
return { installation: updated, addedModules: missingModules, addedFields: missingFields };
|
|
});
|
|
}
|
|
|
|
@Post("template/rollback")
|
|
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
|
where: { brandId: this.brandId() },
|
|
});
|
|
if (!installation) throw new BadRequestException("尚未安装行业模板");
|
|
const history = Array.isArray(installation.previousSnapshots)
|
|
? installation.previousSnapshots
|
|
: [];
|
|
const previous = history.at(-1);
|
|
if (!previous || typeof previous !== "object" || Array.isArray(previous))
|
|
throw new BadRequestException("没有可回滚的模板版本");
|
|
const previousVersion = (previous as { version?: unknown }).version;
|
|
if (typeof previousVersion !== "string") throw new BadRequestException("模板快照无效");
|
|
const remaining = history.slice(0, -1);
|
|
const updated = await this.prisma.brandTemplateInstallation.update({
|
|
where: { id: installation.id },
|
|
data: {
|
|
templateVersion: previousVersion,
|
|
configSnapshot: previous as Prisma.InputJsonValue,
|
|
previousSnapshots: remaining as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
return {
|
|
installation: updated,
|
|
note: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。",
|
|
};
|
|
}
|
|
|
|
@Patch("modules/:id")
|
|
async updateModule(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateModuleDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.brandModule.findFirst({
|
|
where: { id, brandId: this.brandId() },
|
|
});
|
|
if (!item) throw new BadRequestException("品牌模块不存在");
|
|
const { config, ...fields } = body;
|
|
return this.prisma.brandModule.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
|
|
@Post("fields")
|
|
createField(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: CreateFieldDefinitionDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.brandFieldDefinition.create({
|
|
data: {
|
|
...body,
|
|
brandId: this.brandId(),
|
|
source: "custom",
|
|
options: body.options as Prisma.InputJsonValue,
|
|
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Patch("fields/:id")
|
|
async updateField(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateFieldDefinitionDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.brandFieldDefinition.findFirst({
|
|
where: { id, brandId: this.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 }),
|
|
},
|
|
});
|
|
}
|
|
|
|
@Delete("fields/:id")
|
|
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.brandFieldDefinition.findFirst({
|
|
where: { id, brandId: this.brandId(), source: "custom" },
|
|
});
|
|
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
|
|
await this.prisma.brandFieldDefinition.delete({ where: { id } });
|
|
return { deleted: true };
|
|
}
|
|
|
|
@Get("forms")
|
|
listForms(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.inquiryForm.findMany({
|
|
where: { brandId: this.brandId() },
|
|
orderBy: { updatedAt: "desc" },
|
|
});
|
|
}
|
|
|
|
@Get("submissions")
|
|
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.inquirySubmission.findMany({
|
|
where: { brandId: this.brandId() },
|
|
include: { inquiryForm: { select: { name: true } } },
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
}
|
|
|
|
@Post("forms")
|
|
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.inquiryForm.create({
|
|
data: {
|
|
...body,
|
|
brandId: this.brandId(),
|
|
version: 1,
|
|
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Patch("forms/:id")
|
|
async updateForm(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateInquiryFormDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.inquiryForm.findFirst({
|
|
where: { id, brandId: this.brandId() },
|
|
});
|
|
if (!item) throw new BadRequestException("咨询表单不存在");
|
|
const { fieldsSnapshot, ...fields } = body;
|
|
return this.prisma.inquiryForm.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(fieldsSnapshot === undefined
|
|
? {}
|
|
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
|
|
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
@Controller("customer/session")
|
|
export class CustomerSessionController {
|
|
constructor(
|
|
private readonly wechatAuth: WechatAuthService,
|
|
private readonly prisma: PrismaService,
|
|
) {}
|
|
|
|
@Post("wechat")
|
|
async wechatLogin(@Body() body: { code?: string }): Promise<{ token: string }> {
|
|
const session = await this.wechatAuth.exchangeCode(body.code ?? "");
|
|
const brand = await this.prisma.brandProfile.findFirst({ 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" }),
|
|
};
|
|
}
|
|
}
|
|
|
|
@Controller("admin/session")
|
|
export class AdminSessionController {
|
|
constructor(private readonly auth: AdminAuthService) {}
|
|
@Post("login")
|
|
login(@Body() body: AdminLoginDto): Promise<{ token: string; displayName: string }> {
|
|
return this.auth.login(body.username, body.password);
|
|
}
|
|
}
|
|
|
|
class AdminBookingQueryDto {
|
|
@IsOptional()
|
|
@IsEnum(BookingStatus)
|
|
status?: BookingStatus;
|
|
|
|
@IsOptional()
|
|
@Transform((params: TransformFnParams): unknown => {
|
|
const value: unknown = params.value;
|
|
if (value === "true") return true;
|
|
if (value === "false") return false;
|
|
return value;
|
|
})
|
|
@IsBoolean()
|
|
unreadOnly?: boolean;
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
tagId?: string;
|
|
}
|
|
|
|
@Controller("customer/bookings")
|
|
export class CustomerBookingController {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
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, {
|
|
...body,
|
|
extraData: body.extraData as Prisma.InputJsonObject,
|
|
});
|
|
}
|
|
|
|
@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);
|
|
}
|
|
|
|
@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);
|
|
}
|
|
|
|
private identity(request: FastifyRequest): { brandId: string; openid: string } {
|
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
if (!token) throw new BadRequestException("缺少客户登录态");
|
|
try {
|
|
const identity = readIdentity(token);
|
|
if (identity.role !== "customer") throw new BadRequestException("客户登录态无效");
|
|
return { brandId: identity.brandId, openid: identity.subject };
|
|
} catch (error) {
|
|
if (error instanceof BadRequestException) throw error;
|
|
throw new BadRequestException("客户登录态无效");
|
|
}
|
|
}
|
|
}
|
|
|
|
@Controller("admin/bookings")
|
|
export class AdminBookingController {
|
|
constructor(private readonly bookings: BookingService) {}
|
|
@Get()
|
|
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.listForAdmin(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
query,
|
|
);
|
|
}
|
|
|
|
@Get("unread-count")
|
|
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.unreadCountForAdmin(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
);
|
|
}
|
|
|
|
@Get(":id")
|
|
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.getForAdmin(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
id,
|
|
);
|
|
}
|
|
@Post(":id/status")
|
|
update(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body()
|
|
body: UpdateBookingStatusDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.updateStatus(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
id,
|
|
body.status,
|
|
body.adminNote,
|
|
);
|
|
}
|
|
|
|
@Post(":id/read")
|
|
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.markRead(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
id,
|
|
);
|
|
}
|
|
|
|
@Post(":id/tags")
|
|
updateTags(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateBookingTagsDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.updateTags(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
id,
|
|
body.tagIds,
|
|
);
|
|
}
|
|
|
|
@Get("/tags")
|
|
listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.listTags(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
);
|
|
}
|
|
|
|
@Post("/tags")
|
|
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.bookings.createTag(
|
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
|
body.name,
|
|
);
|
|
}
|
|
|
|
private requireAdmin(request: FastifyRequest): void {
|
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
|
let identity;
|
|
try {
|
|
identity = readIdentity(token);
|
|
} catch {
|
|
throw new UnauthorizedException("管理员登录态无效或已过期");
|
|
}
|
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
|
}
|
|
}
|
|
|
|
@Controller("admin/config")
|
|
export class AdminConfigController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
private brandId(): string {
|
|
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
|
}
|
|
private requireAdmin(request: FastifyRequest): void {
|
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
|
let identity;
|
|
try {
|
|
identity = readIdentity(token);
|
|
} catch {
|
|
throw new UnauthorizedException("管理员登录态无效或已过期");
|
|
}
|
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
|
}
|
|
@Get("brand")
|
|
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId() } });
|
|
}
|
|
@Patch("brand")
|
|
updateBrand(@Req() request: FastifyRequest, @Body() body: UpdateBrandDto): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.brandProfile.update({ where: { id: this.brandId() }, data: body });
|
|
}
|
|
@Get("trust-content")
|
|
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.trustContent.findMany({
|
|
where: { brandId: this.brandId() },
|
|
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
|
});
|
|
}
|
|
@Post("trust-content")
|
|
createTrustContent(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: CreateTrustContentDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const { config, ...fields } = body;
|
|
return this.prisma.trustContent.create({
|
|
data: {
|
|
...fields,
|
|
brandId: this.brandId(),
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
@Patch("trust-content/:id")
|
|
async updateTrustContent(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateTrustContentDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.trustContent.findFirst({
|
|
where: { id, brandId: this.brandId() },
|
|
});
|
|
if (!item) throw new BadRequestException("信任内容不存在");
|
|
const { config, ...fields } = body;
|
|
return this.prisma.trustContent.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
@Delete("trust-content/:id")
|
|
async deleteTrustContent(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const item = await this.prisma.trustContent.findFirst({
|
|
where: { id, brandId: this.brandId() },
|
|
});
|
|
if (!item) throw new BadRequestException("信任内容不存在");
|
|
await this.prisma.trustContent.delete({ where: { id } });
|
|
return { deleted: true };
|
|
}
|
|
@Get("services")
|
|
listServices(@Req() request: FastifyRequest): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
return this.prisma.service.findMany({
|
|
where: { brandId: this.brandId() },
|
|
orderBy: { sortOrder: "asc" },
|
|
});
|
|
}
|
|
@Post("services")
|
|
createService(@Req() request: FastifyRequest, @Body() body: CreateServiceDto): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const { config, ...fields } = body;
|
|
return this.prisma.service.create({
|
|
data: {
|
|
...fields,
|
|
brandId: this.brandId(),
|
|
categoryKey: body.categoryKey ?? "standard",
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
@Patch("services/:id")
|
|
async updateService(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateServiceDto,
|
|
): Promise<unknown> {
|
|
this.requireAdmin(request);
|
|
const service = await this.prisma.service.findFirst({ where: { id, brandId: this.brandId() } });
|
|
if (!service) throw new BadRequestException("服务不存在");
|
|
const { config, ...fields } = body;
|
|
return this.prisma.service.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
@Module({
|
|
controllers: [
|
|
HealthController,
|
|
PublicController,
|
|
PublicTrustContentController,
|
|
PublicTemplateController,
|
|
PublicWorkspaceController,
|
|
PublicOfferingController,
|
|
PublicInquiryFormController,
|
|
CustomerInquirySubmissionController,
|
|
AdminWorkspaceController,
|
|
CustomerSessionController,
|
|
AdminSessionController,
|
|
CustomerBookingController,
|
|
AdminBookingController,
|
|
AdminConfigController,
|
|
],
|
|
providers: [PrismaService, WechatAuthService, BookingService, AdminAuthService],
|
|
exports: [PrismaService, WechatAuthService],
|
|
})
|
|
export class AppModule {}
|
|
|
|
export async function createApp(): Promise<NestFastifyApplication> {
|
|
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
|
|
);
|
|
app.useGlobalFilters(new ApiExceptionFilter());
|
|
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
|
|
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
|
|
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
|
|
app.enableCors();
|
|
return app;
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== "test") {
|
|
const app = await createApp();
|
|
await app.listen({ port: Number(process.env.API_PORT ?? 3001), host: "0.0.0.0" });
|
|
}
|