test: 补充订单业务测试和数据库验证
This commit is contained in:
1 parent
7dfa603ba8
commit
50f405932b
13 files changed
+421
-20
No files matched your search
+14
-8
@@ -1,6 +1,6 @@
|
||||
# Project Status
|
||||
|
||||
最后更新:2026-09-18
|
||||
最后更新:2026-09-19
|
||||
|
||||
## 当前目标
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
## 当前阶段
|
||||
|
||||
后端基础与工程环境已建立,正在把 API 做到可以交给小程序和管理后台接入的程度。小程序和后台页面尚未接入真实 API。
|
||||
后端基础、数据库环境和订单 API 已完成首轮验证,正在补 HTTP 集成测试和接口契约,然后接入管理后台与小程序。小程序和后台页面尚未接入真实 API。
|
||||
|
||||
## 已完成
|
||||
|
||||
@@ -27,11 +27,18 @@
|
||||
- 管理员订单列表、状态、未读、标签和内部备忘能力。
|
||||
- DTO 校验、全局异常响应、请求 ID和订单状态流转规则。
|
||||
- Docker PostgreSQL Compose、seed 和 Prisma 脚本说明。
|
||||
- 初始 Prisma migration,已在本地 PostgreSQL 应用并验证数据库 schema up to date。
|
||||
- seed 已写入品牌、服务、标签和管理员数据,并完成数量核验。
|
||||
- 管理员订单详情、状态/未读/标签筛选和未读数量接口。
|
||||
- API 自动化业务规则测试:订单创建、客户取消、状态流转和标签品牌隔离,共 6 项通过。
|
||||
- 修复 ESM 下 `bcryptjs` 导入和 Fastify 请求 ID middleware 的运行时问题。
|
||||
- API 已通过真实 HTTP 验证:健康检查、公开品牌/服务读取和管理员登录。
|
||||
- 已执行多轮 Codex 代码审查并修复关键认证和权限问题。
|
||||
|
||||
## 最近提交
|
||||
|
||||
```text
|
||||
本次工作:数据库初始化、订单管理接口、业务规则测试和运行时修复
|
||||
f2687c5 chore: prepare portable postgres development environment
|
||||
0e8b8e1 feat: add api http conventions and booking state rules
|
||||
0d4caab feat: add admin order tags and read state
|
||||
@@ -43,12 +50,11 @@ b89853b fix: harden api authentication and validation
|
||||
|
||||
## 下一步优先级
|
||||
|
||||
1. 在有 Docker/PostgreSQL 的机器执行 Prisma migration 和 seed,确认真实数据库可运行。
|
||||
2. 修正并补齐 API 集成测试:客户隔离、订单提交、取消、状态机、管理员权限、标签归属。
|
||||
3. 补管理员订单详情、筛选和未读数量接口。
|
||||
4. 补 OpenAPI/Swagger 契约和统一响应示例。
|
||||
5. 创建类型化 `api-client`,再接入管理后台和小程序。
|
||||
6. 先接管理后台订单处理,再接小程序品牌展示和下单。
|
||||
1. 补 HTTP 层集成测试:客户隔离、管理员权限、DTO 校验和统一错误响应。
|
||||
2. 补 OpenAPI/Swagger 契约和统一响应示例。
|
||||
3. 创建类型化 `api-client`,固定前后端接口边界。
|
||||
4. 接入管理后台订单处理页面。
|
||||
5. 接入小程序品牌展示、服务列表和下单流程。
|
||||
|
||||
## 未决问题
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -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: "品牌管理员",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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")
|
||||
|
||||
Vendored
+5
@@ -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>;
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
@@ -16,4 +16,15 @@ export default tseslint.config(
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["apps/api/test/**/*.ts"],
|
||||
rules: {
|
||||
"@typescript-eslint/no-unsafe-argument": "off",
|
||||
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||
"@typescript-eslint/no-unsafe-return": "off",
|
||||
"@typescript-eslint/no-floating-promises": "off",
|
||||
"@typescript-eslint/require-await": "off",
|
||||
},
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user