test: comprehensive test suites and quality gates pass across backend, storefront and admin
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s

- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
devops committed 2026-10-13 16:01:00 +00:00
1 parent 1e73715169
commit ddbf1ca026
439 files changed
+32911 -6107

No files matched your search

+14 -14
View File
@@ -1,4 +1,4 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsNotEmpty,
IsArray,
@@ -6,66 +6,66 @@ import {
IsNumber,
IsOptional,
IsString,
} from 'class-validator';
import { Type } from 'class-transformer';
} from "class-validator";
import { Type } from "class-transformer";
class OrderItemDto {
@ApiProperty({ description: 'ID محصول' })
@ApiProperty({ description: "ID محصول" })
@IsNotEmpty()
@IsString()
productId: string;
@ApiProperty({ description: 'تعداد محصول' })
@ApiProperty({ description: "تعداد محصول" })
@IsNotEmpty()
@IsNumber()
quantity: number;
}
export class CreateOrderDto {
@ApiPropertyOptional({ description: 'ID حیوان خانگی مرتبط' })
@ApiPropertyOptional({ description: "ID حیوان خانگی مرتبط" })
@IsOptional()
@IsString()
petId?: string;
@ApiPropertyOptional({ description: 'کد تخفیف (اختیاری)' })
@ApiPropertyOptional({ description: "کد تخفیف (اختیاری)" })
@IsOptional()
@IsString()
couponCode?: string;
@ApiPropertyOptional({
description: 'آدرس/شناسه تصویر نسخه پزشکی (برای داروهای نیازمند نسخه)',
description: "آدرس/شناسه تصویر نسخه پزشکی (برای داروهای نیازمند نسخه)",
})
@IsOptional()
@IsString()
prescriptionUrl?: string;
@ApiPropertyOptional({
description: 'مبلغ کمک به پناهگاه حیوانات (ردپای مهربانی)',
description: "مبلغ کمک به پناهگاه حیوانات (ردپای مهربانی)",
})
@IsOptional()
@IsNumber()
charityDonation?: number;
@ApiPropertyOptional({ description: 'فعالسازی تمدید خودکار سفارش' })
@ApiPropertyOptional({ description: "فعالسازی تمدید خودکار سفارش" })
@IsOptional()
isRefill?: boolean;
@ApiPropertyOptional({ description: 'روش پرداخت (online, wallet)' })
@ApiPropertyOptional({ description: "روش پرداخت (online, wallet)" })
@IsOptional()
@IsString()
paymentMethod?: string;
@ApiPropertyOptional({ description: 'دوره زمانی تمدید خودکار (روز)' })
@ApiPropertyOptional({ description: "دوره زمانی تمدید خودکار (روز)" })
@IsOptional()
@IsNumber()
refillIntervalDays?: number;
@ApiPropertyOptional({ description: 'آدرس تحویل گیرنده' })
@ApiPropertyOptional({ description: "آدرس تحویل گیرنده" })
@IsOptional()
@IsString()
shippingAddress?: string;
@ApiProperty({ description: 'لیست اقلام سفارش', type: [OrderItemDto] })
@ApiProperty({ description: "لیست اقلام سفارش", type: [OrderItemDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => OrderItemDto)
+21 -21
View File
@@ -1,17 +1,17 @@
import { Test, TestingModule } from '@nestjs/testing';
import { OrdersController } from './orders.controller';
import { OrdersService } from './orders.service';
import { Test, TestingModule } from "@nestjs/testing";
import { OrdersController } from "./orders.controller";
import { OrdersService } from "./orders.service";
describe('OrdersController', () => {
describe("OrdersController", () => {
let controller: OrdersController;
let service: OrdersService;
const mockOrdersService = {
create: jest.fn().mockResolvedValue({ id: 'order-id', totalAmount: 1000 }),
create: jest.fn().mockResolvedValue({ id: "order-id", totalAmount: 1000 }),
findAllByUser: jest
.fn()
.mockResolvedValue([{ id: 'order-id', totalAmount: 1000 }]),
findOne: jest.fn().mockResolvedValue({ id: 'order-id', totalAmount: 1000 }),
.mockResolvedValue([{ id: "order-id", totalAmount: 1000 }]),
findOne: jest.fn().mockResolvedValue({ id: "order-id", totalAmount: 1000 }),
};
beforeEach(async () => {
@@ -28,29 +28,29 @@ describe('OrdersController', () => {
jest.clearAllMocks();
});
it('should be defined', () => {
it("should be defined", () => {
expect(controller).toBeDefined();
});
it('should create order', async () => {
const req = { user: { id: 'user-id' } };
const dto = { items: [{ productId: 'prod-1', quantity: 2 }] };
it("should create order", async () => {
const req = { user: { id: "user-id" } };
const dto = { items: [{ productId: "prod-1", quantity: 2 }] };
const result = await controller.create(req, dto);
expect(service.create).toHaveBeenCalledWith('user-id', dto);
expect(result.id).toBe('order-id');
expect(service.create).toHaveBeenCalledWith("user-id", dto);
expect(result.id).toBe("order-id");
});
it('should list orders of user', async () => {
const req = { user: { id: 'user-id' } };
it("should list orders of user", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.findAll(req, {});
expect(service.findAllByUser).toHaveBeenCalledWith('user-id', {});
expect(service.findAllByUser).toHaveBeenCalledWith("user-id", {});
expect(result).toHaveLength(1);
});
it('should find one order', async () => {
const req = { user: { id: 'user-id' } };
const result = await controller.findOne(req, 'order-id');
expect(service.findOne).toHaveBeenCalledWith('order-id', 'user-id');
expect(result.id).toBe('order-id');
it("should find one order", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.findOne(req, "order-id");
expect(service.findOne).toHaveBeenCalledWith("order-id", "user-id");
expect(result.id).toBe("order-id");
});
});
+63 -63
View File
@@ -8,11 +8,11 @@ import {
Req,
HttpStatus,
Query,
} from '@nestjs/common';
import { OrdersService } from './orders.service';
import { CreateOrderDto } from './dto/create-order.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { Prisma } from '@prisma/client';
} from "@nestjs/common";
import { OrdersService } from "./orders.service";
import { CreateOrderDto } from "./dto/create-order.dto";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { Prisma } from "@prisma/client";
import {
ApiTags,
ApiBearerAuth,
@@ -22,9 +22,9 @@ import {
ApiCreatedResponse,
ApiBadRequestResponse,
ApiNotFoundResponse,
} from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
import { IsString, IsNumber, IsNotEmpty } from 'class-validator';
} from "@nestjs/swagger";
import { PaginationDto } from "../common/dto/pagination.dto";
import { IsString, IsNumber, IsNotEmpty } from "class-validator";
class ValidateCouponDto {
@IsString()
@@ -35,18 +35,18 @@ class ValidateCouponDto {
cartTotal: number;
}
@ApiTags('Orders - مدیریت سفارش‌ها')
@ApiTags("Orders - مدیریت سفارش‌ها")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('orders')
@Controller("orders")
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
description: "عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است",
schema: {
example: {
success: false,
message: 'Unauthorized',
code: 'UNAUTHORIZED',
message: "Unauthorized",
code: "UNAUTHORIZED",
details: {},
},
},
@@ -55,29 +55,29 @@ export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}
@Post()
@ApiOperation({ summary: 'ثبت سفارش جدید' })
@ApiOperation({ summary: "ثبت سفارش جدید" })
@ApiCreatedResponse({
description: 'سفارش با موفقیت ثبت شد',
description: "سفارش با موفقیت ثبت شد",
schema: {
example: {
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
id: "e1d2c3b4-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
couponId: null,
totalAmount: '3500000.00',
charityDonation: '10000.00',
status: 'processing',
totalAmount: "3500000.00",
charityDonation: "10000.00",
status: "processing",
trackingNumber: null,
createdAt: '2026-05-26T18:10:00.000Z',
createdAt: "2026-05-26T18:10:00.000Z",
},
},
})
@ApiBadRequestResponse({
description: 'اعتبارسنجی اقلام سبد خرید با خطا مواجه شد',
description: "اعتبارسنجی اقلام سبد خرید با خطا مواجه شد",
schema: {
example: {
success: false,
message: 'سبد خرید نمی‌تواند خالی باشد',
code: 'BAD_REQUEST',
message: "سبد خرید نمی‌تواند خالی باشد",
code: "BAD_REQUEST",
details: {},
},
},
@@ -89,23 +89,23 @@ export class OrdersController {
return this.ordersService.create(req.user.id, createOrderDto);
}
@Post('validate-coupon')
@ApiOperation({ summary: 'اعتبارسنجی کد تخفیف و محاسبه میزان تخفیف' })
@Post("validate-coupon")
@ApiOperation({ summary: "اعتبارسنجی کد تخفیف و محاسبه میزان تخفیف" })
@ApiOkResponse({
description: 'نتیجه اعتبارسنجی کد تخفیف',
description: "نتیجه اعتبارسنجی کد تخفیف",
schema: {
example: {
valid: true,
couponId: 'abc-123',
code: 'CANINO10',
type: 'percent',
couponId: "abc-123",
code: "CANINO10",
type: "percent",
discountValue: 175000,
message: 'کد تخفیف اعمال شد — ۱۷۵,۰۰۰ تومان تخفیف',
message: "کد تخفیف اعمال شد — ۱۷۵,۰۰۰ تومان تخفیف",
},
},
})
@ApiBadRequestResponse({
description: 'کد تخفیف نامعتبر، منقضی، یا شرایط آن برقرار نیست',
description: "کد تخفیف نامعتبر، منقضی، یا شرایط آن برقرار نیست",
})
validateCoupon(
@Req() req: { user: { id: string } },
@@ -119,19 +119,19 @@ export class OrdersController {
}
@Get()
@ApiOperation({ summary: 'لیست سفارش‌های کاربر فعلی' })
@ApiOperation({ summary: "لیست سفارش‌های کاربر فعلی" })
@ApiOkResponse({
description: 'آرایه‌ای از سفارش‌های ثبت شده کاربر (صفحه‌بندی شده)',
description: "آرایه‌ای از سفارش‌های ثبت شده کاربر (صفحه‌بندی شده)",
schema: {
example: {
data: [
{
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
totalAmount: '3500000.00',
charityDonation: '10000.00',
status: 'processing',
createdAt: '2026-05-26T18:10:00.000Z',
id: "e1d2c3b4-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
totalAmount: "3500000.00",
charityDonation: "10000.00",
status: "processing",
createdAt: "2026-05-26T18:10:00.000Z",
},
],
meta: {
@@ -147,16 +147,16 @@ export class OrdersController {
return this.ordersService.findAllByUser(req.user.id, query);
}
@Post(':id/retry-payment')
@Post(":id/retry-payment")
@ApiOperation({
summary: 'پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت',
summary: "پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت",
})
@ApiOkResponse({
description: 'درخواست پرداخت مجدد با موفقیت پردازش شد',
description: "درخواست پرداخت مجدد با موفقیت پردازش شد",
})
retryPayment(
@Req() req: { user: { id: string } },
@Param('id') id: string,
@Param("id") id: string,
@Body() body: { paymentMethod?: string },
) {
return this.ordersService.retryPayment(
@@ -166,28 +166,28 @@ export class OrdersController {
);
}
@Get(':id')
@ApiOperation({ summary: 'دریافت جزئیات یک سفارش خاص' })
@Get(":id")
@ApiOperation({ summary: "دریافت جزئیات یک سفارش خاص" })
@ApiOkResponse({
description: 'اطلاعات کامل سفارش مشخص شده به همراه اقلام سفارش',
description: "اطلاعات کامل سفارش مشخص شده به همراه اقلام سفارش",
schema: {
example: {
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
totalAmount: '3500000.00',
charityDonation: '10000.00',
status: 'processing',
trackingNumber: 'TRK-987654321',
createdAt: '2026-05-26T18:10:00.000Z',
id: "e1d2c3b4-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
totalAmount: "3500000.00",
charityDonation: "10000.00",
status: "processing",
trackingNumber: "TRK-987654321",
createdAt: "2026-05-26T18:10:00.000Z",
orderItems: [
{
id: 'item-1',
id: "item-1",
quantity: 2,
product: {
id: 'a1b2c3d4-1234-5678-abcd-ef1234567890',
name: 'Canhydrox GAG (کنهیدروکس)',
priceDisplay: '۱,۷۵۰,۰۰۰ تومان',
imageUrl: 'https://example.com/canhydrox.png',
id: "a1b2c3d4-1234-5678-abcd-ef1234567890",
name: "Canhydrox GAG (کنهیدروکس)",
priceDisplay: "۱,۷۵۰,۰۰۰ تومان",
imageUrl: "https://example.com/canhydrox.png",
},
},
],
@@ -195,17 +195,17 @@ export class OrdersController {
},
})
@ApiNotFoundResponse({
description: 'سفارش یافت نشد یا متعلق به کاربر فعلی نیست',
description: "سفارش یافت نشد یا متعلق به کاربر فعلی نیست",
schema: {
example: {
success: false,
message: 'Order not found',
code: 'NOT_FOUND',
message: "Order not found",
code: "NOT_FOUND",
details: {},
},
},
})
findOne(@Req() req: { user: { id: string } }, @Param('id') id: string) {
findOne(@Req() req: { user: { id: string } }, @Param("id") id: string) {
return this.ordersService.findOne(id, req.user.id);
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { OrdersService } from './orders.service';
import { OrdersController } from './orders.controller';
import { Module } from "@nestjs/common";
import { OrdersService } from "./orders.service";
import { OrdersController } from "./orders.controller";
@Module({
controllers: [OrdersController],
+207 -46
View File
@@ -1,11 +1,11 @@
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';
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', () => {
describe("OrdersService", () => {
let service: OrdersService;
let prisma: PrismaService;
@@ -13,13 +13,19 @@ describe('OrdersService', () => {
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(),
@@ -33,13 +39,20 @@ describe('OrdersService', () => {
uiText: {
findFirst: jest.fn().mockResolvedValue(null),
},
$executeRaw: jest.fn(),
$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<unknown>) =>
callback(mockPrisma),
);
const module: TestingModule = await Test.createTestingModule({
providers: [
OrdersService,
@@ -56,106 +69,254 @@ describe('OrdersService', () => {
jest.clearAllMocks();
});
it('should be defined', () => {
it("should be defined", () => {
expect(service).toBeDefined();
});
describe('create', () => {
it('should throw BadRequestException if items are empty', async () => {
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(
await expect(service.create("user-id", dto)).rejects.toThrow(
BadRequestException,
);
});
it('should throw BadRequestException for duplicate product IDs in order items', async () => {
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 },
{ productId: "prod-1", quantity: 1 },
{ productId: "prod-1", quantity: 2 },
],
};
await expect(service.create('user-id', dto)).rejects.toThrow(
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(
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(
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 () => {
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') },
{ id: "prod-1", priceValue: new Prisma.Decimal("1000") },
]);
const dto = {
items: [
{ productId: 'prod-1', quantity: 1 },
{ productId: 'prod-missing', quantity: 2 },
{ productId: "prod-1", quantity: 1 },
{ productId: "prod-missing", quantity: 2 },
],
};
await expect(service.create('user-id', dto)).rejects.toThrow(
await expect(service.create("user-id", dto)).rejects.toThrow(
NotFoundException,
);
});
it('should successfully create order using batched findMany and precise Decimal calculations', async () => {
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', priceValue: new Prisma.Decimal('32.49') },
{ id: 'prod-2', priceValue: new Prisma.Decimal('15.50') },
{
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'),
id: "order-1",
totalAmount: new Prisma.Decimal("80.48"),
trackingNumber: "CN-12345",
});
const dto = {
items: [
{ productId: 'prod-1', quantity: 2 }, // 32.49 * 2 = 64.98
{ productId: 'prod-2', quantity: 1 }, // 15.50 * 1 = 15.50 Total = 80.48
{ productId: "prod-1", quantity: 2 },
{ productId: "prod-2", quantity: 1 },
],
paymentMethod: "card",
};
const result = await service.create('user-id', dto);
const result = await service.create("user-id", dto);
expect(prisma.product.findMany).toHaveBeenCalledWith({
where: { id: { in: ['prod-1', 'prod-2'] } },
where: { id: { in: ["prod-1", "prod-2"] } },
});
expect(prisma.order.create).toHaveBeenCalled();
expect(result.id).toBe('order-1');
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' }]);
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', {});
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 () => {
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(
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' };
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-1', 'user-id');
const result = await service.findOne("order-id", "user-id");
expect(result).toEqual(order);
});
});
+100 -100
View File
@@ -3,12 +3,12 @@ import {
NotFoundException,
BadRequestException,
Logger,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { CreateOrderDto } from './dto/create-order.dto';
import { SmsService } from '../common/services/sms.service';
import { Prisma } from '@prisma/client';
} from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { PaginationDto } from "../common/dto/pagination.dto";
import { CreateOrderDto } from "./dto/create-order.dto";
import { SmsService } from "../common/services/sms.service";
import { Prisma } from "@prisma/client";
@Injectable()
export class OrdersService {
@@ -36,46 +36,46 @@ export class OrdersService {
if (!coupon || !coupon.isActive) {
throw new BadRequestException({
message: 'کد تخفیف معتبر نیست یا منقضی شده است',
error: 'COUPON_INVALID',
message: "کد تخفیف معتبر نیست یا منقضی شده است",
error: "COUPON_INVALID",
});
}
if (coupon.expiresAt && new Date() > coupon.expiresAt) {
throw new BadRequestException({
message: 'کد تخفیف منقضی شده است',
error: 'COUPON_EXPIRED',
message: "کد تخفیف منقضی شده است",
error: "COUPON_EXPIRED",
});
}
if (coupon.maxUses && coupon.usedCount >= coupon.maxUses) {
throw new BadRequestException({
message: 'ظرفیت استفاده از این کد تخفیف تکمیل شده است',
error: 'COUPON_LIMIT_REACHED',
message: "ظرفیت استفاده از این کد تخفیف تکمیل شده است",
error: "COUPON_LIMIT_REACHED",
});
}
if (coupon.minCartValue && cartTotal.lessThan(coupon.minCartValue)) {
throw new BadRequestException({
message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString('fa-IR')} تومان است`,
error: 'COUPON_MIN_CART',
message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString("fa-IR")} تومان است`,
error: "COUPON_MIN_CART",
});
}
// Check user-specific targets
const userTargets = coupon.targets.filter((t) => t.targetType === 'USER');
const userTargets = coupon.targets.filter((t) => t.targetType === "USER");
if (
userTargets.length > 0 &&
!userTargets.some((t) => t.targetId === userId)
) {
throw new BadRequestException({
message: 'این کد تخفیف برای حساب کاربری شما فعال نیست',
error: 'COUPON_USER_MISMATCH',
message: "این کد تخفیف برای حساب کاربری شما فعال نیست",
error: "COUPON_USER_MISMATCH",
});
}
let discountAmount = new Prisma.Decimal(0);
if (coupon.type === 'percent' || coupon.type === 'PERCENTAGE') {
if (coupon.type === "percent" || coupon.type === "PERCENTAGE") {
discountAmount = cartTotal.mul(coupon.value).div(100);
if (
coupon.maxCartValue &&
@@ -101,29 +101,29 @@ export class OrdersService {
async create(userId: string, createOrderDto: CreateOrderDto) {
// Check catalog mode settings
const catalogSetting = await this.prisma.setting.findFirst({
where: { key: { in: ['catalog_mode', 'catalog_disable_checkout'] } },
where: { key: { in: ["catalog_mode", "catalog_disable_checkout"] } },
});
const catalogUiText = await this.prisma.uiText.findFirst({
where: {
key: { in: ['catalog_mode', 'catalog_disable_checkout'] },
value: 'true',
key: { in: ["catalog_mode", "catalog_disable_checkout"] },
value: "true",
},
});
if ((catalogSetting && catalogSetting.value === 'true') || catalogUiText) {
if ((catalogSetting && catalogSetting.value === "true") || catalogUiText) {
throw new BadRequestException(
'امکان ثبت سفارش به دلیل فعال بودن حالت کاتالوگ در حال حاضر وجود ندارد.',
"امکان ثبت سفارش به دلیل فعال بودن حالت کاتالوگ در حال حاضر وجود ندارد.",
);
}
if (!createOrderDto.items || createOrderDto.items.length === 0) {
throw new BadRequestException('سبد خرید خالی است');
throw new BadRequestException("سبد خرید خالی است");
}
// Validate quantities and duplicate product IDs
const productIds = createOrderDto.items.map((item) => item.productId);
const uniqueProductIds = new Set(productIds);
if (uniqueProductIds.size !== productIds.length) {
throw new BadRequestException('تکرار محصول در سبد خرید مجاز نیست');
throw new BadRequestException("تکرار محصول در سبد خرید مجاز نیست");
}
for (const item of createOrderDto.items) {
@@ -147,8 +147,8 @@ export class OrdersService {
throw new NotFoundException(`محصول یافت نشد`);
}
const isOutOfStock =
product.stockStatus === 'OUT_OF_STOCK' ||
product.stockStatus === 'DISCONTINUED' ||
product.stockStatus === "OUT_OF_STOCK" ||
product.stockStatus === "DISCONTINUED" ||
product.stock <= 0;
if (isOutOfStock) {
throw new BadRequestException(
@@ -206,10 +206,10 @@ export class OrdersService {
const trackingNumber = this.generateTrackingNumber();
// Deduct user wallet balance and create order atomically
if (createOrderDto.paymentMethod === 'wallet' && userId) {
if (createOrderDto.paymentMethod === "wallet" && userId) {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) {
throw new NotFoundException('کاربر یافت نشد');
throw new NotFoundException("کاربر یافت نشد");
}
const createdWalletOrder = await this.prisma.$transaction(async (tx) => {
@@ -222,7 +222,7 @@ export class OrdersService {
if (updatedCount === 0) {
throw new BadRequestException(
'موجودی کیف پول برای پرداخت این سفارش کافی نیست',
"موجودی کیف پول برای پرداخت این سفارش کافی نیست",
);
}
@@ -230,8 +230,8 @@ export class OrdersService {
data: {
userId,
amount: Number(finalAmount),
type: 'withdrawal',
status: 'completed',
type: "withdrawal",
status: "completed",
description: `پرداخت سفارش ${trackingNumber}`,
},
});
@@ -254,8 +254,8 @@ export class OrdersService {
isRefill: Boolean(createOrderDto.isRefill),
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
trackingNumber,
status: 'processing',
paymentMethod: 'wallet',
status: "processing",
paymentMethod: "wallet",
shippingAddress: createOrderDto.shippingAddress,
orderItems: {
create: orderItemsData,
@@ -288,7 +288,7 @@ export class OrdersService {
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: 'OUT_OF_STOCK' },
data: { stockStatus: "OUT_OF_STOCK" },
});
}
}
@@ -299,7 +299,7 @@ export class OrdersService {
// Send Order Confirmation SMS for wallet orders
if (user.mobile) {
const orderData = this.buildOrderEventData(createdWalletOrder, user);
this.smsService.triggerEvent('ORDER_PAID', orderData).catch((err) => {
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
this.logger.warn(`Failed to trigger wallet order SMS: ${err}`);
});
}
@@ -307,8 +307,8 @@ export class OrdersService {
return createdWalletOrder;
}
const isOnline = createOrderDto.paymentMethod === 'online';
const initialStatus = isOnline ? 'pending_payment' : 'processing';
const isOnline = createOrderDto.paymentMethod === "online";
const initialStatus = isOnline ? "pending_payment" : "processing";
const reservationExpiry = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes hold
const createdOrder = await this.prisma.$transaction(async (tx) => {
@@ -322,7 +322,7 @@ export class OrdersService {
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
trackingNumber,
status: initialStatus,
paymentMethod: createOrderDto.paymentMethod || 'card',
paymentMethod: createOrderDto.paymentMethod || "card",
shippingAddress: createOrderDto.shippingAddress,
orderItems: {
create: orderItemsData,
@@ -332,7 +332,7 @@ export class OrdersService {
productId: item.productId,
quantity: item.quantity,
expiresAt: reservationExpiry,
status: isOnline ? 'ACTIVE' : 'CONSUMED',
status: isOnline ? "ACTIVE" : "CONSUMED",
})),
},
},
@@ -355,7 +355,7 @@ export class OrdersService {
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: 'OUT_OF_STOCK' },
data: { stockStatus: "OUT_OF_STOCK" },
});
}
}
@@ -372,7 +372,7 @@ export class OrdersService {
if (user?.mobile) {
const orderData = this.buildOrderEventData(createdOrder, user);
this.smsService
.triggerEvent('ORDER_CREATED', orderData)
.triggerEvent("ORDER_CREATED", orderData)
.catch(() => {});
}
}
@@ -384,11 +384,11 @@ export class OrdersService {
const rawShipping = order.shippingAddress;
let shipping: Record<string, any> = {};
if (typeof rawShipping === 'object' && rawShipping !== null) {
if (typeof rawShipping === "object" && rawShipping !== null) {
shipping = rawShipping;
} else if (typeof rawShipping === 'string') {
} else if (typeof rawShipping === "string") {
const trimmed = rawShipping.trim();
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
try {
shipping = JSON.parse(trimmed);
} catch {
@@ -409,7 +409,7 @@ export class OrdersService {
if (!shipping.fullName) shipping.fullName = recipientMatch[1]?.trim();
if (!shipping.phone && recipientMatch[2])
shipping.phone = recipientMatch[2]?.trim();
text = text.replace(recipientMatch[0], '').trim();
text = text.replace(recipientMatch[0], "").trim();
}
// 2. Extract postal code: (کد پستی: ۱۲۳۴۵۶۷۸۹۰)
@@ -417,7 +417,7 @@ export class OrdersService {
if (postalMatch) {
if (!shipping.postalCode)
shipping.postalCode = postalMatch[1]?.trim();
text = text.replace(postalMatch[0], '').trim();
text = text.replace(postalMatch[0], "").trim();
}
// 3. Extract province and city: "استان، شهر، بقیه آدرس" or "استان - شهر - بقیه آدرس"
@@ -428,7 +428,7 @@ export class OrdersService {
if (parts.length >= 3) {
if (!shipping.province) shipping.province = parts[0];
if (!shipping.city) shipping.city = parts[1];
if (!shipping.address) shipping.address = parts.slice(2).join('، ');
if (!shipping.address) shipping.address = parts.slice(2).join("، ");
} else if (parts.length === 2) {
if (!shipping.province) shipping.province = parts[0];
if (!shipping.address) shipping.address = parts[1];
@@ -440,8 +440,8 @@ export class OrdersService {
const items = order.orderItems || [];
const itemsSummary = items
.map((i: any) => `${i.product?.nameFa || 'محصول'} (${i.quantity})`)
.join('، ');
.map((i: any) => `${i.product?.nameFa || "محصول"} (${i.quantity})`)
.join("، ");
const itemCount = items.reduce(
(sum: number, i: any) => sum + (i.quantity || 1),
0,
@@ -449,8 +449,8 @@ export class OrdersService {
const customerFullName = (
user?.firstName
? `${user.firstName} ${user.lastName || ''}`
: shipping.fullName || 'مشتری'
? `${user.firstName} ${user.lastName || ""}`
: shipping.fullName || "مشتری"
).trim();
const recipientFullName = (
@@ -459,39 +459,39 @@ export class OrdersService {
customerFullName
).trim();
const recipientMobile = (shipping.phone || user?.mobile || '').trim();
const recipientMobile = (shipping.phone || user?.mobile || "").trim();
const provinceCity = (
shipping.province && shipping.city
? `${shipping.province} - ${shipping.city}`
: shipping.province || shipping.city || ''
: shipping.province || shipping.city || ""
).trim();
const addressDetail = (
shipping.address ||
shipping.detail ||
(typeof rawShipping === 'string' ? rawShipping : '')
(typeof rawShipping === "string" ? rawShipping : "")
).trim();
return {
orderNumber: order.trackingNumber || order.id.slice(0, 8),
amount: Number(order.totalAmount || 0).toLocaleString('fa-IR'),
amount: Number(order.totalAmount || 0).toLocaleString("fa-IR"),
customerName: customerFullName,
customerPhone: user?.mobile || shipping.phone || '',
customerPhone: user?.mobile || shipping.phone || "",
recipientName: recipientFullName,
recipientPhone: recipientMobile,
provinceCity: provinceCity || 'ثبت نشده',
postalCode: shipping.postalCode || shipping.zipCode || '',
address: addressDetail || '',
provinceCity: provinceCity || "ثبت نشده",
postalCode: shipping.postalCode || shipping.zipCode || "",
address: addressDetail || "",
itemsSummary,
itemCount: String(itemCount),
paymentMethod:
order.paymentMethod === 'online'
? 'آنلاین'
: order.paymentMethod === 'wallet'
? 'کیف پول'
: 'کارت به کارت',
orderDate: new Date().toLocaleDateString('fa-IR'),
order.paymentMethod === "online"
? "آنلاین"
: order.paymentMethod === "wallet"
? "کیف پول"
: "کارت به کارت",
orderDate: new Date().toLocaleDateString("fa-IR"),
};
}
@@ -502,7 +502,7 @@ export class OrdersService {
});
if (!order) {
throw new NotFoundException('سفارش یافت نشد');
throw new NotFoundException("سفارش یافت نشد");
}
const updatedOrder = await this.prisma.order.update({
@@ -516,19 +516,19 @@ export class OrdersService {
// Send Shipping SMS with Tracking Code (or courier delivery fallback)
const mobile = updatedOrder.user?.mobile;
const finalTracking = trackingCode || updatedOrder.trackingNumber || '';
if (status === 'shipped' && mobile) {
const finalTracking = trackingCode || updatedOrder.trackingNumber || "";
if (status === "shipped" && mobile) {
const orderData = this.buildOrderEventData(
updatedOrder,
updatedOrder.user,
);
orderData.trackingCode = finalTracking || 'ارسال با پیک شهری';
orderData.shippingTrackingCode = finalTracking || 'ارسال با پیک شهری';
orderData.trackingCode = finalTracking || "ارسال با پیک شهری";
orderData.shippingTrackingCode = finalTracking || "ارسال با پیک شهری";
orderData.shippingMethod = finalTracking
? 'پست پیشتاز / تیپاکس'
: 'پیک شهری';
? "پست پیشتاز / تیپاکس"
: "پیک شهری";
this.smsService.triggerEvent('ORDER_SHIPPED', orderData).catch(() => {});
this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {});
}
return updatedOrder;
@@ -538,8 +538,8 @@ export class OrdersService {
const {
page = 1,
limit = 10,
sortBy = 'createdAt',
sortOrder = 'desc',
sortBy = "createdAt",
sortOrder = "desc",
} = filters;
const skip = (page - 1) * limit;
@@ -576,7 +576,7 @@ export class OrdersService {
});
if (!order) {
throw new NotFoundException('سفارش یافت نشد');
throw new NotFoundException("سفارش یافت نشد");
}
return order;
}
@@ -616,11 +616,11 @@ export class OrdersService {
const expiredReservations =
await this.prisma.inventoryReservation.updateMany({
where: {
status: 'ACTIVE',
status: "ACTIVE",
expiresAt: { lte: now },
},
data: {
status: 'RELEASED',
status: "RELEASED",
},
});
@@ -640,22 +640,22 @@ export class OrdersService {
});
if (!order) {
throw new NotFoundException('سفارش مورد نظر یافت نشد');
throw new NotFoundException("سفارش مورد نظر یافت نشد");
}
const ALLOWED_RETRY_STATUSES = ['pending_payment', 'failed'];
const ALLOWED_RETRY_STATUSES = ["pending_payment", "failed"];
if (!ALLOWED_RETRY_STATUSES.includes(order.status)) {
throw new BadRequestException(
'تنها سفارش‌های در انتظار پرداخت یا ناموفق قابلیت پرداخت مجدد دارند.',
"تنها سفارش‌های در انتظار پرداخت یا ناموفق قابلیت پرداخت مجدد دارند.",
);
}
const selectedMethod = paymentMethod || order.paymentMethod || 'online';
const selectedMethod = paymentMethod || order.paymentMethod || "online";
const finalAmount = Number(order.totalAmount);
if (selectedMethod === 'wallet') {
if (selectedMethod === "wallet") {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) throw new NotFoundException('کاربر یافت نشد');
if (!user) throw new NotFoundException("کاربر یافت نشد");
await this.prisma.$transaction(async (tx) => {
// SEC-002: Atomic decrement preventing race condition & overdraft
@@ -667,7 +667,7 @@ export class OrdersService {
if (updatedCount === 0) {
throw new BadRequestException(
`موجودی کیف پول شما برای پرداخت این سفارش (${finalAmount.toLocaleString('fa-IR')} تومان) کافی نیست.`,
`موجودی کیف پول شما برای پرداخت این سفارش (${finalAmount.toLocaleString("fa-IR")} تومان) کافی نیست.`,
);
}
@@ -675,8 +675,8 @@ export class OrdersService {
data: {
userId,
amount: finalAmount,
type: 'withdrawal',
status: 'completed',
type: "withdrawal",
status: "completed",
description: `پرداخت مجدد سفارش ${order.trackingNumber || order.id}`,
},
});
@@ -695,8 +695,8 @@ export class OrdersService {
await tx.order.update({
where: { id: order.id },
data: {
status: 'processing',
paymentMethod: 'wallet',
status: "processing",
paymentMethod: "wallet",
},
});
});
@@ -704,29 +704,29 @@ export class OrdersService {
if (user.mobile) {
const orderData = this.buildOrderEventData(order, user);
await this.smsService
.triggerEvent('ORDER_PAID', orderData)
.triggerEvent("ORDER_PAID", orderData)
.catch(() => {});
}
return {
success: true,
message: 'پرداخت با موفقیت از طریق کیف پول انجام شد.',
paymentMethod: 'wallet',
message: "پرداخت با موفقیت از طریق کیف پول انجام شد.",
paymentMethod: "wallet",
orderId: order.id,
};
}
if (selectedMethod === 'card') {
if (selectedMethod === "card") {
await this.prisma.order.update({
where: { id: order.id },
data: { paymentMethod: 'card', status: 'pending_payment' },
data: { paymentMethod: "card", status: "pending_payment" },
});
return {
success: true,
message:
'روش پرداخت به کارت به کارت تغییر یافت. لطفاً پس از واریز فیش را ثبت فرمایید.',
paymentMethod: 'card',
"روش پرداخت به کارت به کارت تغییر یافت. لطفاً پس از واریز فیش را ثبت فرمایید.",
paymentMethod: "card",
orderId: order.id,
};
}
@@ -734,13 +734,13 @@ export class OrdersService {
// Default: Online Gateway (Zibal)
await this.prisma.order.update({
where: { id: order.id },
data: { paymentMethod: 'online', status: 'pending_payment' },
data: { paymentMethod: "online", status: "pending_payment" },
});
return {
success: true,
message: 'سفارش آماده پرداخت آنلاین است.',
paymentMethod: 'online',
message: "سفارش آماده پرداخت آنلاین است.",
paymentMethod: "online",
orderId: order.id,
paymentInitiateRequired: true,
};