test: 补充订单业务测试和数据库验证

This commit is contained in:
que01 committed 2026-09-19 00:54:19 +08:00
1 parent 7dfa603ba8
commit 50f405932b
13 files changed
+421 -20

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
"dev": "tsx watch src/main.ts",
"lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "tsx --test test/**/*.test.ts",
"clean": "rimraf dist",
"start": "node dist/main.js",
"db:generate": "prisma generate",
@@ -0,0 +1,187 @@
-- CreateEnum
CREATE TYPE "BookingStatus" AS ENUM ('received', 'contacting', 'confirmed', 'completed', 'cancelled');
-- CreateEnum
CREATE TYPE "BookingRequestType" AS ENUM ('package', 'private_chef');
-- CreateEnum
CREATE TYPE "ContactPreference" AS ENUM ('wechat', 'phone', 'none');
-- CreateEnum
CREATE TYPE "FulfillmentType" AS ENUM ('pickup', 'delivery');
-- CreateTable
CREATE TABLE "BrandProfile" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"tagline" TEXT,
"description" TEXT,
"avatarUrl" TEXT,
"coverUrl" TEXT,
"hours" TEXT,
"address" TEXT,
"deliveryNote" TEXT,
"contactPhone" TEXT,
"contactWechat" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "BrandProfile_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Service" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,
"coverUrl" TEXT,
"priceText" TEXT,
"priceAmount" INTEGER,
"bookingEnabled" BOOLEAN NOT NULL DEFAULT true,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Service_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CustomerUser" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"openid" TEXT NOT NULL,
"lastLoginAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "CustomerUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Booking" (
"id" TEXT NOT NULL,
"bookingNo" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"customerUserId" TEXT NOT NULL,
"requestType" "BookingRequestType" NOT NULL,
"customerName" TEXT NOT NULL,
"phone" TEXT,
"wechatId" TEXT,
"contactPreference" "ContactPreference" NOT NULL,
"fulfillmentType" "FulfillmentType",
"serviceId" TEXT,
"requestedDate" TIMESTAMP(3),
"requestedTime" TEXT,
"deliveryAddress" TEXT,
"estimatedAmount" INTEGER,
"extraData" JSONB,
"note" TEXT,
"adminNote" TEXT,
"status" "BookingStatus" NOT NULL DEFAULT 'received',
"isRead" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Booking_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BookingItem" (
"id" TEXT NOT NULL,
"bookingId" TEXT NOT NULL,
"serviceId" TEXT,
"serviceNameSnapshot" TEXT NOT NULL,
"unitPriceSnapshot" INTEGER NOT NULL,
"quantity" INTEGER NOT NULL,
"subtotalSnapshot" INTEGER NOT NULL,
CONSTRAINT "BookingItem_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Tag" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"isPreset" BOOLEAN NOT NULL DEFAULT false,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Tag_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AdminUser" (
"id" TEXT NOT NULL,
"username" TEXT NOT NULL,
"passwordHash" TEXT NOT NULL,
"displayName" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'admin',
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"lastLoginAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AdminUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BookingTag" (
"bookingId" TEXT NOT NULL,
"tagId" TEXT NOT NULL,
CONSTRAINT "BookingTag_pkey" PRIMARY KEY ("bookingId","tagId")
);
-- CreateIndex
CREATE INDEX "Service_brandId_isEnabled_sortOrder_idx" ON "Service"("brandId", "isEnabled", "sortOrder");
-- CreateIndex
CREATE UNIQUE INDEX "CustomerUser_brandId_openid_key" ON "CustomerUser"("brandId", "openid");
-- CreateIndex
CREATE UNIQUE INDEX "Booking_bookingNo_key" ON "Booking"("bookingNo");
-- CreateIndex
CREATE INDEX "Booking_brandId_status_createdAt_idx" ON "Booking"("brandId", "status", "createdAt");
-- CreateIndex
CREATE INDEX "Booking_customerUserId_createdAt_idx" ON "Booking"("customerUserId", "createdAt");
-- CreateIndex
CREATE UNIQUE INDEX "Tag_brandId_name_key" ON "Tag"("brandId", "name");
-- CreateIndex
CREATE UNIQUE INDEX "AdminUser_username_key" ON "AdminUser"("username");
-- AddForeignKey
ALTER TABLE "Service" ADD CONSTRAINT "Service_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CustomerUser" ADD CONSTRAINT "CustomerUser_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_customerUserId_fkey" FOREIGN KEY ("customerUserId") REFERENCES "CustomerUser"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingItem" ADD CONSTRAINT "BookingItem_bookingId_fkey" FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingItem" ADD CONSTRAINT "BookingItem_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Tag" ADD CONSTRAINT "Tag_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingTag" ADD CONSTRAINT "BookingTag_bookingId_fkey" FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingTag" ADD CONSTRAINT "BookingTag_tagId_fkey" FOREIGN KEY ("tagId") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+2 -2
View File
@@ -1,5 +1,5 @@
import { PrismaClient } from "@prisma/client";
import { hash } from "bcryptjs";
import bcrypt from "bcryptjs";
const prisma = new PrismaClient();
@@ -60,7 +60,7 @@ async function main(): Promise<void> {
update: {},
create: {
username: "admin",
passwordHash: await hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
displayName: "品牌管理员",
},
});
+2 -4
View File
@@ -1,5 +1,5 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { compare } from "bcryptjs";
import bcrypt from "bcryptjs";
import { PrismaService } from "./prisma.service.js";
import { signIdentity } from "./auth.js";
@@ -9,9 +9,7 @@ export class AdminAuthService {
async login(username: string, password: string): Promise<{ token: string; displayName: string }> {
const user = await this.prisma.adminUser.findUnique({ where: { username } });
// bcryptjs ships incomplete typings in this dependency version.
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (!user || !user.isEnabled || !(await compare(password, user.passwordHash))) {
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
throw new UnauthorizedException("账号或密码错误");
}
await this.prisma.adminUser.update({
+24 -3
View File
@@ -1,5 +1,5 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { BookingStatus, Prisma } from "@prisma/client";
import { PrismaService } from "./prisma.service.js";
export interface CreateBookingInput {
@@ -116,14 +116,35 @@ export class BookingService {
return this.prisma.booking.update({ where: { id }, data: { status: "cancelled" } });
}
async listForAdmin(brandId: string) {
async listForAdmin(
brandId: string,
options: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {},
) {
return this.prisma.booking.findMany({
where: { brandId },
where: {
brandId,
...(options.status ? { status: options.status } : {}),
...(options.unreadOnly ? { isRead: false } : {}),
...(options.tagId ? { tags: { some: { tagId: options.tagId } } } : {}),
},
orderBy: { createdAt: "desc" },
include: { items: true, tags: { include: { tag: true } } },
});
}
async getForAdmin(brandId: string, id: string) {
const booking = await this.prisma.booking.findFirst({
where: { id, brandId },
include: { items: true, tags: { include: { tag: true } }, service: true },
});
if (!booking) throw new NotFoundException("订单不存在");
return booking;
}
async unreadCountForAdmin(brandId: string) {
return { count: await this.prisma.booking.count({ where: { brandId, isRead: false } }) };
}
async updateStatus(
brandId: string,
id: string,
+8 -1
View File
@@ -7,7 +7,14 @@ import { randomUUID } from "node:crypto";
export class RequestIdMiddleware {
use(request: FastifyRequest, reply: FastifyReply, next: () => void): void {
const requestId = request.headers["x-request-id"]?.toString() ?? randomUUID();
reply.header("x-request-id", requestId);
if (typeof reply.header === "function") {
reply.header("x-request-id", requestId);
} else {
(reply as unknown as { setHeader: (name: string, value: string) => void }).setHeader(
"x-request-id",
requestId,
);
}
next();
}
}
+47 -2
View File
@@ -7,11 +7,12 @@ import {
Module,
Param,
Post,
Query,
Req,
ValidationPipe,
} from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { Prisma } from "@prisma/client";
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";
@@ -22,6 +23,9 @@ import { CreateTagDto, UpdateBookingStatusDto, UpdateBookingTagsDto } from "./ad
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";
@@ -104,6 +108,26 @@ export class AdminSessionController {
}
}
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(
@@ -162,10 +186,31 @@ export class CustomerBookingController {
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
@Get()
list(@Req() request: FastifyRequest): 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",
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")
+5
View File
@@ -1,4 +1,9 @@
declare module "bcryptjs" {
const bcrypt: {
compare(password: string, hash: string): Promise<boolean>;
hash(password: string, saltRounds: number): Promise<string>;
};
export default bcrypt;
export function compare(password: string, hash: string): Promise<boolean>;
export function hash(password: string, saltRounds: number): Promise<string>;
}
+109
View File
@@ -0,0 +1,109 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { BookingService } from "../src/booking.service.js";
const brandId = "brand-1";
const customerId = "customer-1";
const service = {
id: "service-1",
name: "套餐",
bookingEnabled: true,
priceAmount: 2800,
};
function createPrisma(overrides: Record<string, unknown> = {}): any {
return {
service: {
findMany: async () => [service],
},
booking: {
create: async ({ data }: any) => ({
bookingNo: "AC-test",
status: "received",
estimatedAmount: data.estimatedAmount,
createdAt: new Date(),
}),
findFirst: async () => null,
update: async ({ data }: any) => ({ status: data.status }),
findMany: async () => [],
count: async () => 0,
},
tag: { findMany: async () => [] },
bookingTag: { deleteMany: {}, createMany: {} },
$transaction: async () => undefined,
...overrides,
};
}
test("创建普通套餐订单时保存价格快照和预计金额", async () => {
const prisma = createPrisma();
const result = await new BookingService(prisma).create(brandId, customerId, {
requestType: "package",
customerName: "陈同学",
wechatId: "wx-test",
contactPreference: "wechat",
items: [{ serviceId: service.id, quantity: 2 }],
});
assert.equal(result.estimatedAmount, 5600);
assert.equal(result.status, "received");
});
test("普通套餐不能在没有明细时创建", async () => {
await assert.rejects(
() =>
new BookingService(createPrisma()).create(brandId, customerId, {
requestType: "package",
customerName: "陈同学",
phone: "13800000000",
contactPreference: "phone",
}),
(error: unknown) => error instanceof BadRequestException,
);
});
test("客户只能取消自己的 received 订单", async () => {
const prisma = createPrisma({
booking: {
findFirst: async () => ({ id: "booking-1", status: "confirmed" }),
update: async () => ({ status: "cancelled" }),
},
});
await assert.rejects(
() => new BookingService(prisma).cancelForCustomer(brandId, customerId, "booking-1"),
(error: unknown) => error instanceof BadRequestException,
);
});
test("取消不存在或不属于当前客户的订单返回不存在", async () => {
await assert.rejects(
() => new BookingService(createPrisma()).cancelForCustomer(brandId, customerId, "missing"),
(error: unknown) => error instanceof NotFoundException,
);
});
test("订单状态只能按定义的状态机流转", async () => {
const prisma = createPrisma({
booking: {
findFirst: async () => ({ id: "booking-1", status: "received" }),
update: async ({ data }: any) => data,
},
});
const bookings = new BookingService(prisma);
assert.equal((await bookings.updateStatus(brandId, "booking-1", "contacting")).status, "contacting");
await assert.rejects(
() => bookings.updateStatus(brandId, "booking-1", "completed"),
(error: unknown) => error instanceof BadRequestException,
);
});
test("更新订单标签时拒绝其他品牌的标签", async () => {
const prisma = createPrisma({
booking: { findFirst: async () => ({ id: "booking-1", brandId }) },
tag: { findMany: async () => [] },
});
await assert.rejects(
() => new BookingService(prisma).updateTags(brandId, "booking-1", ["foreign-tag"]),
(error: unknown) => error instanceof BadRequestException,
);
});
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".."
},
"include": ["./**/*.ts"]
}