style: 统一项目代码格式

This commit is contained in:
que01 committed 2026-09-19 18:37:00 +08:00
1 parent f0836ec056
commit 718d357d88
8 files changed
+1012 -117

No files matched your search

+5 -2
View File
@@ -41,7 +41,8 @@ export class CreateServiceDto {
}
export class CreateTrustContentDto {
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"]) type!: string;
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
type!: string;
@IsString() title!: string;
@IsOptional() @IsString() summary?: string;
@IsString() content!: string;
@@ -52,7 +53,9 @@ export class CreateTrustContentDto {
}
export class UpdateTrustContentDto {
@IsOptional() @IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"]) type?: string;
@IsOptional()
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
type?: string;
@IsOptional() @IsString() title?: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() content?: string;
+124 -19
View File
@@ -23,7 +23,16 @@ 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 {
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";
@@ -89,7 +98,15 @@ export class PublicController {
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" }] }); }
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")
@@ -202,10 +219,7 @@ export class CustomerBookingController {
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
@Get()
list(
@Req() request: FastifyRequest,
@Query() query: AdminBookingQueryDto,
): Promise<unknown> {
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",
@@ -289,7 +303,11 @@ export class AdminBookingController {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try { identity = readIdentity(token); } catch { throw new UnauthorizedException("管理员登录态无效或已过期"); }
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
}
@@ -297,37 +315,124 @@ export class AdminBookingController {
@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 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("管理员登录态无效或已过期"); }
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() } }); }
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 }); }
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" }] }); }
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 }) } }); }
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 }) } }); }
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 }; }
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" } }); }
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 }) } }); }
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> {
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 }) } });
return this.prisma.service.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
}
+68 -16
View File
@@ -26,7 +26,10 @@ after(async () => {
});
async function request(url, options = {}) {
return app.getHttpAdapter().getInstance().inject({ method: "GET", url, ...options });
return app
.getHttpAdapter()
.getInstance()
.inject({ method: "GET", url, ...options });
}
test("health and public content are available without authentication", async () => {
@@ -101,14 +104,20 @@ test("admin can read and update brand and service configuration", async () => {
let createdServiceId;
try {
const brand = await request("/admin/config/brand", { headers: { authorization: `Bearer ${adminToken}` } });
const brand = await request("/admin/config/brand", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(brand.statusCode, 200);
assert.equal(JSON.parse(brand.body).id, brandId);
const updatedBrand = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${adminToken}` },
payload: { description: "集成测试品牌简介", contactPhone: "13800000000", templateKey: "personal" },
payload: {
description: "集成测试品牌简介",
contactPhone: "13800000000",
templateKey: "personal",
},
});
assert.equal(updatedBrand.statusCode, 200);
assert.equal(JSON.parse(updatedBrand.body).description, "集成测试品牌简介");
@@ -123,33 +132,61 @@ test("admin can read and update brand and service configuration", async () => {
assert.equal(JSON.parse(updatedService.body).priceText, "集成测试价格");
assert.equal(JSON.parse(updatedService.body).sortOrder, 99);
const listedServices = await request("/admin/config/services", { headers: { authorization: `Bearer ${adminToken}` } });
const listedServices = await request("/admin/config/services", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(listedServices.statusCode, 200);
assert.ok(JSON.parse(listedServices.body).some((item) => item.id === serviceBefore.id));
const createdService = await request("/admin/config/services", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: { name: "集成测试通用服务", description: "通用品牌服务", categoryKey: "consulting", config: { duration: 60 } },
payload: {
name: "集成测试通用服务",
description: "通用品牌服务",
categoryKey: "consulting",
config: { duration: 60 },
},
});
assert.equal(createdService.statusCode, 201);
createdServiceId = JSON.parse(createdService.body).id;
assert.equal(JSON.parse(createdService.body).categoryKey, "consulting");
} finally {
await prisma.brandProfile.update({ where: { id: brandId }, data: { description: brandBefore.description, contactPhone: brandBefore.contactPhone, templateKey: brandBefore.templateKey } });
await prisma.service.update({ where: { id: serviceBefore.id }, data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder } });
await prisma.brandProfile.update({
where: { id: brandId },
data: {
description: brandBefore.description,
contactPhone: brandBefore.contactPhone,
templateKey: brandBefore.templateKey,
},
});
await prisma.service.update({
where: { id: serviceBefore.id },
data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder },
});
if (createdServiceId) await prisma.service.delete({ where: { id: createdServiceId } });
}
});
test("admin can manage trust content", async () => {
const login = await request("/admin/session/login", { method: "POST", payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD } });
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
const created = await request("/admin/config/trust-content", { method: "POST", headers: { authorization: `Bearer ${token}` }, payload: { type: "profile", title: "关于我", content: "集成测试内容", summary: "测试摘要" } });
const created = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { type: "profile", title: "关于我", content: "集成测试内容", summary: "测试摘要" },
});
assert.equal(created.statusCode, 201);
const id = JSON.parse(created.body).id;
const draft = await request("/admin/config/trust-content", { method: "POST", headers: { authorization: `Bearer ${token}` }, payload: { type: "experience", title: "草稿", content: "不应公开", isPublished: false } });
const draft = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { type: "experience", title: "草稿", content: "不应公开", isPublished: false },
});
assert.equal(draft.statusCode, 201);
const publicContent = await request("/public/trust-content");
assert.equal(publicContent.statusCode, 200);
@@ -157,13 +194,22 @@ test("admin can manage trust content", async () => {
assert.ok(publicItems.some((item) => item.id === id));
assert.ok(!publicItems.some((item) => item.id === JSON.parse(draft.body).id));
try {
const list = await request("/admin/config/trust-content", { headers: { authorization: `Bearer ${token}` } });
const list = await request("/admin/config/trust-content", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(list.statusCode, 200);
const updated = await request(`/admin/config/trust-content/${id}`, { method: "PATCH", headers: { authorization: `Bearer ${token}` }, payload: { content: "更新后的内容" } });
const updated = await request(`/admin/config/trust-content/${id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { content: "更新后的内容" },
});
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).content, "更新后的内容");
} finally {
const deleted = await request(`/admin/config/trust-content/${id}`, { method: "DELETE", headers: { authorization: `Bearer ${token}` } });
const deleted = await request(`/admin/config/trust-content/${id}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(deleted.statusCode, 200);
await prisma.trustContent.delete({ where: { id: JSON.parse(draft.body).id } });
}
@@ -216,7 +262,9 @@ test("customer can create a generic inquiry without food-specific fields", async
});
test("customer can create and cancel a package booking", async () => {
const service = await prisma.service.findFirst({ where: { brandId, isEnabled: true, priceAmount: { not: null } } });
const service = await prisma.service.findFirst({
where: { brandId, isEnabled: true, priceAmount: { not: null } },
});
assert.ok(service);
const created = await request("/customer/bookings", {
method: "POST",
@@ -245,7 +293,9 @@ test("customer can create and cancel a package booking", async () => {
});
test("admin can advance booking status but cannot skip the state machine", async () => {
const service = await prisma.service.findFirst({ where: { brandId, isEnabled: true, priceAmount: { not: null } } });
const service = await prisma.service.findFirst({
where: { brandId, isEnabled: true, priceAmount: { not: null } },
});
assert.ok(service);
const created = await request("/customer/bookings", {
method: "POST",
@@ -258,7 +308,9 @@ test("admin can advance booking status but cannot skip the state machine", async
items: [{ serviceId: service.id, quantity: 1 }],
},
});
const booking = await prisma.booking.findUnique({ where: { bookingNo: JSON.parse(created.body).bookingNo } });
const booking = await prisma.booking.findUnique({
where: { bookingNo: JSON.parse(created.body).bookingNo },
});
assert.ok(booking);
createdBookingIds.push(booking.id);