import { Test, TestingModule } from "@nestjs/testing"; import { OrdersService } from "./orders.service"; import { PrismaService } from "../prisma/prisma.service"; import { SmsService } from "../common/services/sms.service"; import { NotFoundException, BadRequestException } from "@nestjs/common"; import { Prisma } from "@prisma/client"; describe("OrdersService", () => { let service: OrdersService; let prisma: PrismaService; const mockPrisma = { product: { findUnique: jest.fn(), findMany: jest.fn(), update: jest.fn().mockResolvedValue({ id: "prod-1", stock: 10 }), }, order: { create: jest.fn(), findMany: jest.fn(), update: jest.fn().mockResolvedValue({ id: "prod-1", stock: 10 }), findFirst: jest.fn(), count: jest.fn(), }, coupon: { findUnique: jest.fn(), update: jest.fn(), }, user: { findUnique: jest.fn(), update: jest.fn(), }, walletTransaction: { create: jest.fn(), }, setting: { findFirst: jest.fn().mockResolvedValue(null), }, uiText: { findFirst: jest.fn().mockResolvedValue(null), }, $executeRaw: jest.fn().mockResolvedValue(1), $transaction: jest.fn(), }; const mockSmsService = { sendOrderConfirmation: jest.fn().mockResolvedValue(true), triggerEvent: jest.fn().mockResolvedValue(true), }; beforeEach(async () => { mockPrisma.$transaction.mockImplementation( (callback: (tx: typeof mockPrisma) => Promise) => callback(mockPrisma), ); const module: TestingModule = await Test.createTestingModule({ providers: [ OrdersService, { provide: PrismaService, useValue: mockPrisma }, { provide: SmsService, useValue: mockSmsService }, ], }).compile(); service = module.get(OrdersService); prisma = module.get(PrismaService); }); afterEach(() => { jest.clearAllMocks(); }); it("should be defined", () => { expect(service).toBeDefined(); }); describe("create - validation & edge cases", () => { it("should throw BadRequestException if catalog mode is active", async () => { mockPrisma.setting.findFirst.mockResolvedValueOnce({ key: "catalog_mode", value: "true", }); await expect( service.create("user-1", { items: [{ productId: "prod-1", quantity: 1 }], }), ).rejects.toThrow(BadRequestException); }); it("should throw BadRequestException if items are empty", async () => { const dto = { items: [] }; await expect(service.create("user-id", dto)).rejects.toThrow( BadRequestException, ); }); it("should throw BadRequestException for duplicate product IDs in order items", async () => { const dto = { items: [ { productId: "prod-1", quantity: 1 }, { productId: "prod-1", quantity: 2 }, ], }; await expect(service.create("user-id", dto)).rejects.toThrow( BadRequestException, ); }); it("should throw BadRequestException for non-positive or non-integer quantities", async () => { const dtoZero = { items: [{ productId: "prod-1", quantity: 0 }] }; await expect(service.create("user-id", dtoZero)).rejects.toThrow( BadRequestException, ); const dtoFloat = { items: [{ productId: "prod-1", quantity: 1.5 }] }; await expect(service.create("user-id", dtoFloat)).rejects.toThrow( BadRequestException, ); }); it("should throw NotFoundException if any product is not found in batched query", async () => { mockPrisma.product.findMany.mockResolvedValue([ { id: "prod-1", priceValue: new Prisma.Decimal("1000") }, ]); const dto = { items: [ { productId: "prod-1", quantity: 1 }, { productId: "prod-missing", quantity: 2 }, ], }; await expect(service.create("user-id", dto)).rejects.toThrow( NotFoundException, ); }); it("should throw BadRequestException if product is OUT_OF_STOCK or stock is 0", async () => { mockPrisma.product.findMany.mockResolvedValue([ { id: "prod-1", nameFa: "محصول ناموجود", stockStatus: "OUT_OF_STOCK", stock: 0, priceValue: 100000, }, ]); const dto = { items: [{ productId: "prod-1", quantity: 1 }], }; await expect(service.create("user-id", dto)).rejects.toThrow( /ناموجود است/, ); }); it("should throw BadRequestException if requested quantity exceeds available stock", async () => { mockPrisma.product.findMany.mockResolvedValue([ { id: "prod-1", nameFa: "محصول کم‌موجودی", stockStatus: "IN_STOCK", stock: 2, priceValue: 100000, }, ]); const dto = { items: [{ productId: "prod-1", quantity: 5 }], }; await expect(service.create("user-id", dto)).rejects.toThrow( /بیشتر از موجودی انبار/, ); }); }); describe("validateCoupon", () => { it("should reject invalid or inactive coupon", async () => { mockPrisma.coupon.findUnique.mockResolvedValue(null); await expect( service.validateCoupon("INVALID", new Prisma.Decimal(100000), "user-1"), ).rejects.toThrow(BadRequestException); }); it("should reject expired coupon", async () => { mockPrisma.coupon.findUnique.mockResolvedValue({ code: "EXPIRED", isActive: true, expiresAt: new Date(Date.now() - 100000), targets: [], }); await expect( service.validateCoupon("EXPIRED", new Prisma.Decimal(100000), "user-1"), ).rejects.toThrow(BadRequestException); }); it("should reject coupon if minCartValue is not met", async () => { mockPrisma.coupon.findUnique.mockResolvedValue({ code: "MINLIMIT", isActive: true, minCartValue: new Prisma.Decimal(200000), targets: [], }); await expect( service.validateCoupon( "MINLIMIT", new Prisma.Decimal(100000), "user-1", ), ).rejects.toThrow(BadRequestException); }); it("should correctly calculate percentage discount up to maxCartValue cap", async () => { mockPrisma.coupon.findUnique.mockResolvedValue({ id: "coup-1", code: "SAVE20", isActive: true, type: "PERCENTAGE", value: 20, // 20% maxCartValue: 50000, // Cap at 50,000 targets: [], }); // Cart: 1,000,000 -> 20% would be 200,000 -> Cap should reduce it to 50,000 const res = await service.validateCoupon( "SAVE20", new Prisma.Decimal(1000000), "user-1", ); expect(res.discountAmount).toEqual(new Prisma.Decimal(50000)); }); }); describe("create - wallet payment flow & inventory", () => { it("should throw BadRequestException when wallet balance is insufficient", async () => { mockPrisma.product.findMany.mockResolvedValue([ { id: "prod-1", stockStatus: "IN_STOCK", stock: 10, priceValue: 100000, }, ]); mockPrisma.user.findUnique.mockResolvedValue({ id: "user-1" }); // Execute raw returns 0 when condition wallet_balance >= finalAmount fails mockPrisma.$executeRaw.mockResolvedValue(0); const dto = { items: [{ productId: "prod-1", quantity: 1 }], paymentMethod: "wallet", }; await expect(service.create("user-1", dto)).rejects.toThrow( /موجودی کیف پول برای پرداخت این سفارش کافی نیست/, ); }); it("should successfully create order and update product stock", async () => { const products = [ { id: "prod-1", stockStatus: "IN_STOCK", stock: 5, priceValue: new Prisma.Decimal("32.49"), }, { id: "prod-2", stockStatus: "IN_STOCK", stock: 10, priceValue: new Prisma.Decimal("15.50"), }, ]; mockPrisma.product.findMany.mockResolvedValue(products); mockPrisma.order.create.mockResolvedValue({ id: "order-1", totalAmount: new Prisma.Decimal("80.48"), trackingNumber: "CN-12345", }); const dto = { items: [ { productId: "prod-1", quantity: 2 }, { productId: "prod-2", quantity: 1 }, ], paymentMethod: "card", }; const result = await service.create("user-id", dto); expect(prisma.product.findMany).toHaveBeenCalledWith({ where: { id: { in: ["prod-1", "prod-2"] } }, }); expect(mockPrisma.product.update).toHaveBeenCalledWith({ where: { id: "prod-1" }, data: { stock: { decrement: 2 } }, }); expect(mockPrisma.product.update).toHaveBeenCalledWith({ where: { id: "prod-2" }, data: { stock: { decrement: 1 } }, }); expect(result.id).toBe("order-1"); }); }); describe("findAllByUser", () => { it("should find all orders of a user", async () => { mockPrisma.order.findMany.mockResolvedValue([{ id: "order-1" }]); mockPrisma.order.count.mockResolvedValue(1); const result = await service.findAllByUser("user-id", {}); expect(prisma.order.findMany).toHaveBeenCalled(); expect(result.data).toHaveLength(1); }); }); describe("findOne", () => { it("should throw NotFoundException if order does not exist", async () => { mockPrisma.order.findFirst.mockResolvedValue(null); await expect(service.findOne("order-id", "user-id")).rejects.toThrow( NotFoundException, ); }); it("should return order if found", async () => { const order = { id: "order-1", userId: "user-id" }; mockPrisma.order.findFirst.mockResolvedValue(order); const result = await service.findOne("order-id", "user-id"); expect(result).toEqual(order); }); }); });