style: apply standard ESLint & Prettier formatting across backend
Deploy Canina / deploy (push) Successful in 4m58s

This commit is contained in:
parsa aghaei committed 2026-07-29 15:41:53 +03:30
1 parent ae636c8b03
commit 62bd8811fa
66 files changed
+1398 -607

No files matched your search

+14 -3
View File
@@ -1,5 +1,12 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsArray, ValidateNested, IsNumber, IsOptional, IsString } from 'class-validator';
import {
IsNotEmpty,
IsArray,
ValidateNested,
IsNumber,
IsOptional,
IsString,
} from 'class-validator';
import { Type } from 'class-transformer';
class OrderItemDto {
@@ -25,12 +32,16 @@ export class CreateOrderDto {
@IsString()
couponCode?: string;
@ApiPropertyOptional({ description: 'آدرس/شناسه تصویر نسخه پزشکی (برای داروهای نیازمند نسخه)' })
@ApiPropertyOptional({
description: 'آدرس/شناسه تصویر نسخه پزشکی (برای داروهای نیازمند نسخه)',
})
@IsOptional()
@IsString()
prescriptionUrl?: string;
@ApiPropertyOptional({ description: 'مبلغ کمک به پناهگاه حیوانات (ردپای مهربانی)' })
@ApiPropertyOptional({
description: 'مبلغ کمک به پناهگاه حیوانات (ردپای مهربانی)',
})
@IsOptional()
@IsNumber()
charityDonation?: number;
+4 -4
View File
@@ -8,16 +8,16 @@ describe('OrdersController', () => {
const mockOrdersService = {
create: jest.fn().mockResolvedValue({ id: 'order-id', totalAmount: 1000 }),
findAllByUser: 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 }),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [OrdersController],
providers: [
{ provide: OrdersService, useValue: mockOrdersService },
],
providers: [{ provide: OrdersService, useValue: mockOrdersService }],
}).compile();
controller = module.get<OrdersController>(OrdersController);
+58 -31
View File
@@ -1,8 +1,29 @@
import { Controller, Get, Post, Patch, Body, Param, UseGuards, Req, HttpStatus, Query } from '@nestjs/common';
import {
Controller,
Get,
Post,
Patch,
Body,
Param,
UseGuards,
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 { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse, ApiBody } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiOkResponse,
ApiCreatedResponse,
ApiBadRequestResponse,
ApiNotFoundResponse,
ApiBody,
} from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
import { IsString, IsNumber, IsNotEmpty } from 'class-validator';
@@ -27,9 +48,9 @@ class ValidateCouponDto {
success: false,
message: 'Unauthorized',
code: 'UNAUTHORIZED',
details: {}
}
}
details: {},
},
},
})
export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}
@@ -47,9 +68,9 @@ export class OrdersController {
charityDonation: '10000.00',
status: 'processing',
trackingNumber: null,
createdAt: '2026-05-26T18:10:00.000Z'
}
}
createdAt: '2026-05-26T18:10:00.000Z',
},
},
})
@ApiBadRequestResponse({
description: 'اعتبارسنجی اقلام سبد خرید با خطا مواجه شد',
@@ -58,9 +79,9 @@ export class OrdersController {
success: false,
message: 'سبد خرید نمی‌تواند خالی باشد',
code: 'BAD_REQUEST',
details: {}
}
}
details: {},
},
},
})
create(@Req() req: any, @Body() createOrderDto: CreateOrderDto) {
return this.ordersService.create(req.user.id, createOrderDto);
@@ -77,13 +98,19 @@ export class OrdersController {
code: 'CANINO10',
type: 'percent',
discountValue: 175000,
message: 'کد تخفیف اعمال شد — ۱۷۵,۰۰۰ تومان تخفیف'
}
}
message: 'کد تخفیف اعمال شد — ۱۷۵,۰۰۰ تومان تخفیف',
},
},
})
@ApiBadRequestResponse({
description: 'کد تخفیف نامعتبر، منقضی، یا شرایط آن برقرار نیست',
})
@ApiBadRequestResponse({ description: 'کد تخفیف نامعتبر، منقضی، یا شرایط آن برقرار نیست' })
validateCoupon(@Req() req: any, @Body() body: ValidateCouponDto) {
return this.ordersService.validateCoupon(body.code, body.cartTotal, req.user.id);
return this.ordersService.validateCoupon(
body.code,
body.cartTotal,
req.user.id,
);
}
@Get()
@@ -99,17 +126,17 @@ export class OrdersController {
totalAmount: '3500000.00',
charityDonation: '10000.00',
status: 'processing',
createdAt: '2026-05-26T18:10:00.000Z'
}
createdAt: '2026-05-26T18:10:00.000Z',
},
],
meta: {
total: 1,
page: 1,
lastPage: 1,
limit: 10
}
}
}
limit: 10,
},
},
},
})
findAll(@Req() req: any, @Query() query: PaginationDto) {
return this.ordersService.findAllByUser(req.user.id, query);
@@ -136,12 +163,12 @@ export class OrdersController {
id: 'a1b2c3d4-1234-5678-abcd-ef1234567890',
name: 'Canhydrox GAG (کنهیدروکس)',
priceDisplay: '۱,۷۵۰,۰۰۰ تومان',
imageUrl: 'https://example.com/canhydrox.png'
}
}
]
}
}
imageUrl: 'https://example.com/canhydrox.png',
},
},
],
},
},
})
@ApiNotFoundResponse({
description: 'سفارش یافت نشد یا متعلق به کاربر فعلی نیست',
@@ -150,9 +177,9 @@ export class OrdersController {
success: false,
message: 'Order not found',
code: 'NOT_FOUND',
details: {}
}
}
details: {},
},
},
})
findOne(@Req() req: any, @Param('id') id: string) {
return this.ordersService.findOne(id, req.user.id);
+16 -5
View File
@@ -43,23 +43,32 @@ describe('OrdersService', () => {
it('should throw NotFoundException if product does not exist', async () => {
mockPrisma.product.findUnique.mockResolvedValue(null);
const dto = { items: [{ productId: 'invalid-prod', quantity: 2 }] };
await expect(service.create('user-id', dto)).rejects.toThrow(NotFoundException);
await expect(service.create('user-id', dto)).rejects.toThrow(
NotFoundException,
);
});
it('should throw BadRequestException if items are empty', async () => {
const dto = { items: [] };
await expect(service.create('user-id', dto)).rejects.toThrow(BadRequestException);
await expect(service.create('user-id', dto)).rejects.toThrow(
BadRequestException,
);
});
it('should successfully create order and sum amounts', async () => {
const prod = { id: 'prod-1', priceValue: 1000 };
mockPrisma.product.findUnique.mockResolvedValue(prod);
mockPrisma.order.create.mockResolvedValue({ id: 'order-1', totalAmount: 2000 });
mockPrisma.order.create.mockResolvedValue({
id: 'order-1',
totalAmount: 2000,
});
const dto = { items: [{ productId: 'prod-1', quantity: 2 }] };
const result = await service.create('user-id', dto);
expect(prisma.product.findUnique).toHaveBeenCalledWith({ where: { id: 'prod-1' } });
expect(prisma.product.findUnique).toHaveBeenCalledWith({
where: { id: 'prod-1' },
});
expect(prisma.order.create).toHaveBeenCalledWith({
data: {
userId: 'user-id',
@@ -92,7 +101,9 @@ describe('OrdersService', () => {
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);
await expect(service.findOne('order-id', 'user-id')).rejects.toThrow(
NotFoundException,
);
});
it('should return order if found', async () => {
+61 -24
View File
@@ -1,4 +1,8 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import {
Injectable,
NotFoundException,
BadRequestException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { CreateOrderDto } from './dto/create-order.dto';
@@ -22,28 +26,43 @@ export class OrdersService {
});
if (!coupon || !coupon.isActive) {
throw new BadRequestException({ message: 'کد تخفیف معتبر نیست یا منقضی شده است', error: 'COUPON_INVALID' });
throw new BadRequestException({
message: 'کد تخفیف معتبر نیست یا منقضی شده است',
error: 'COUPON_INVALID',
});
}
if (coupon.expiresAt && new Date() > coupon.expiresAt) {
throw new BadRequestException({ message: 'کد تخفیف منقضی شده است', error: 'COUPON_EXPIRED' });
throw new BadRequestException({
message: 'کد تخفیف منقضی شده است',
error: 'COUPON_EXPIRED',
});
}
if (coupon.maxUses && coupon.usedCount >= coupon.maxUses) {
throw new BadRequestException({ message: 'ظرفیت استفاده از این کد تخفیف تکمیل شده است', error: 'COUPON_LIMIT_REACHED' });
throw new BadRequestException({
message: 'ظرفیت استفاده از این کد تخفیف تکمیل شده است',
error: 'COUPON_LIMIT_REACHED',
});
}
if (coupon.minCartValue && cartTotal < Number(coupon.minCartValue)) {
throw new BadRequestException({
message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString('fa-IR')} تومان است`,
error: 'COUPON_MIN_CART'
error: 'COUPON_MIN_CART',
});
}
// Check user-specific targets
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_NOT_FOR_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_NOT_FOR_USER',
});
}
let discountValue: number;
@@ -74,9 +93,13 @@ export class OrdersService {
const orderItems = [];
for (const item of createOrderDto.items) {
const product = await this.prisma.product.findUnique({ where: { id: item.productId } });
const product = await this.prisma.product.findUnique({
where: { id: item.productId },
});
if (!product) {
throw new NotFoundException(`محصول با شناسه ${item.productId} یافت نشد`);
throw new NotFoundException(
`محصول با شناسه ${item.productId} یافت نشد`,
);
}
totalAmount += Number(product.priceValue) * item.quantity;
orderItems.push({
@@ -93,7 +116,11 @@ export class OrdersService {
let discountAmount = 0;
if (createOrderDto.couponCode) {
try {
const couponResult = await this.validateCoupon(createOrderDto.couponCode, totalAmount, userId);
const couponResult = await this.validateCoupon(
createOrderDto.couponCode,
totalAmount,
userId,
);
discountAmount = couponResult.discountValue;
couponId = couponResult.couponId;
// Increment usedCount
@@ -107,7 +134,10 @@ export class OrdersService {
}
const charityAmount = Number(createOrderDto.charityDonation || 0);
const finalAmount = Math.max(totalAmount - discountAmount + charityAmount, 0);
const finalAmount = Math.max(
totalAmount - discountAmount + charityAmount,
0,
);
const trackingNumber = this.generateTrackingNumber();
// Deduct user wallet balance if payment method is wallet
@@ -118,13 +148,15 @@ export class OrdersService {
}
const userBalance = Number(user.walletBalance || 0);
if (userBalance < finalAmount) {
throw new BadRequestException('موجودی کیف پول برای پرداخت این سفارش کافی نیست');
throw new BadRequestException(
'موجودی کیف پول برای پرداخت این سفارش کافی نیست',
);
}
await this.prisma.user.update({
where: { id: userId },
data: {
walletBalance: { decrement: finalAmount }
}
walletBalance: { decrement: finalAmount },
},
});
await this.prisma.walletTransaction.create({
data: {
@@ -132,8 +164,8 @@ export class OrdersService {
amount: finalAmount,
type: 'withdrawal',
status: 'completed',
description: `پرداخت سفارش ${trackingNumber}`
}
description: `پرداخت سفارش ${trackingNumber}`,
},
});
}
@@ -142,7 +174,7 @@ export class OrdersService {
try {
await this.prisma.user.update({
where: { id: userId },
data: { charityDonationTotal: { increment: charityAmount } }
data: { charityDonationTotal: { increment: charityAmount } },
});
} catch {
// Ignore if user not found or guest
@@ -165,14 +197,19 @@ export class OrdersService {
} as any,
include: {
orderItems: {
include: { product: true }
}
}
include: { product: true },
},
},
});
}
async findAllByUser(userId: string, filters: PaginationDto) {
const { page = 1, limit = 10, sortBy = 'createdAt', sortOrder = 'desc' } = filters;
const {
page = 1,
limit = 10,
sortBy = 'createdAt',
sortOrder = 'desc',
} = filters;
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
@@ -185,7 +222,7 @@ export class OrdersService {
orderItems: { include: { product: true } },
},
}),
this.prisma.order.count({ where: { userId } })
this.prisma.order.count({ where: { userId } }),
]);
return {
@@ -195,7 +232,7 @@ export class OrdersService {
page,
lastPage: Math.ceil(total / limit),
limit,
}
},
};
}