Files
persionalBrand/apps/api/src/main.ts
T
2026-09-19 18:37:00 +08:00

470 lines
15 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 } from "./booking.dto.js";
import {
CreateServiceDto,
CreateTagDto,
CreateTrustContentDto,
UpdateBookingStatusDto,
UpdateBookingTagsDto,
UpdateBrandDto,
UpdateServiceDto,
UpdateTrustContentDto,
} 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";
@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("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,
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());
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" });
}