feat(phase2): implement database optimization and RBAC enforcement
Deploy Canina / deploy (push) Failing after 28s

- TASK-FIN-001: Eliminate N+1 query loop in OrdersService.create with batched findMany query.
- Perform monetary calculations strictly using Prisma.Decimal methods (.add(), .mul(), .sub()).
- Add validation for duplicate product IDs and invalid quantities in order items.
- Implement global DecimalInterceptor registered in main.ts to serialize Prisma.Decimal values into exact string representations in API responses.
- TASK-SEC-003: Create roles.decorator.ts and roles.guard.ts in common directory with backward-compatible re-exports in auth directory.
- Enforce RBAC on SettingsController with @UseGuards(JwtAuthGuard, RolesGuard) and @Roles('Admin').
- Add unit specs for DecimalInterceptor, RolesGuard, SettingsController, and OrdersService Decimal batch operations.
This commit is contained in:
parsa committed 2026-08-06 21:29:20 +03:30
1 parent a64291a19a
commit 809c69f923
13 files changed
+403 -128

No files matched your search

+2 -1
View File
@@ -13,6 +13,7 @@ import {
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,
@@ -108,7 +109,7 @@ export class OrdersController {
validateCoupon(@Req() req: any, @Body() body: ValidateCouponDto) {
return this.ordersService.validateCoupon(
body.code,
body.cartTotal,
new Prisma.Decimal(body.cartTotal),
req.user.id,
);
}
+71 -30
View File
@@ -1,7 +1,9 @@
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;
@@ -10,6 +12,7 @@ describe('OrdersService', () => {
const mockPrisma = {
product: {
findUnique: jest.fn(),
findMany: jest.fn(),
},
order: {
create: jest.fn(),
@@ -17,6 +20,17 @@ describe('OrdersService', () => {
findFirst: jest.fn(),
count: jest.fn(),
},
user: {
findUnique: jest.fn(),
update: jest.fn(),
},
walletTransaction: {
create: jest.fn(),
},
};
const mockSmsService = {
sendOrderConfirmation: jest.fn().mockResolvedValue(true),
};
beforeEach(async () => {
@@ -24,6 +38,7 @@ describe('OrdersService', () => {
providers: [
OrdersService,
{ provide: PrismaService, useValue: mockPrisma },
{ provide: SmsService, useValue: mockSmsService },
],
}).compile();
@@ -40,14 +55,6 @@ describe('OrdersService', () => {
});
describe('create', () => {
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,
);
});
it('should throw BadRequestException if items are empty', async () => {
const dto = { items: [] };
await expect(service.create('user-id', dto)).rejects.toThrow(
@@ -55,35 +62,68 @@ describe('OrdersService', () => {
);
});
it('should successfully create order and sum amounts', async () => {
const prod = { id: 'prod-1', priceValue: 1000 };
mockPrisma.product.findUnique.mockResolvedValue(prod);
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 successfully create order using batched findMany and precise Decimal calculations', async () => {
const products = [
{ id: 'prod-1', priceValue: new Prisma.Decimal('32.49') },
{ id: 'prod-2', priceValue: new Prisma.Decimal('15.50') },
];
mockPrisma.product.findMany.mockResolvedValue(products);
mockPrisma.order.create.mockResolvedValue({
id: 'order-1',
totalAmount: 2000,
totalAmount: new Prisma.Decimal('80.48'),
});
const dto = { items: [{ productId: 'prod-1', quantity: 2 }] };
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
],
};
const result = await service.create('user-id', dto);
expect(prisma.product.findUnique).toHaveBeenCalledWith({
where: { id: 'prod-1' },
});
expect(prisma.order.create).toHaveBeenCalledWith({
data: {
userId: 'user-id',
totalAmount: 2000,
status: 'processing',
orderItems: {
create: [{ productId: 'prod-1', quantity: 2 }],
},
},
include: {
orderItems: {
include: { product: true },
},
},
expect(prisma.product.findMany).toHaveBeenCalledWith({
where: { id: { in: ['prod-1', 'prod-2'] } },
});
expect(prisma.order.create).toHaveBeenCalled();
expect(result.id).toBe('order-1');
});
});
@@ -114,3 +154,4 @@ describe('OrdersService', () => {
});
});
});
+84 -53
View File
@@ -7,6 +7,7 @@ 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 {
@@ -22,7 +23,7 @@ export class OrdersService {
return `CN-${dateStr}-${random}`;
}
async validateCoupon(code: string, cartTotal: number, userId: string) {
async validateCoupon(code: string, cartTotal: Prisma.Decimal, userId: string) {
const coupon = await this.prisma.coupon.findUnique({
where: { code: code.toUpperCase().trim() },
include: { targets: true },
@@ -49,7 +50,7 @@ export class OrdersService {
});
}
if (coupon.minCartValue && cartTotal < Number(coupon.minCartValue)) {
if (coupon.minCartValue && cartTotal.lessThan(coupon.minCartValue)) {
throw new BadRequestException({
message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString('fa-IR')} تومان است`,
error: 'COUPON_MIN_CART',
@@ -68,20 +69,24 @@ export class OrdersService {
});
}
let discountAmount = 0;
let discountAmount = new Prisma.Decimal(0);
if (coupon.type === 'percent' || coupon.type === 'PERCENTAGE') {
discountAmount = (cartTotal * Number(coupon.value)) / 100;
if (coupon.maxCartValue && discountAmount > Number(coupon.maxCartValue)) {
discountAmount = Number(coupon.maxCartValue);
discountAmount = cartTotal.mul(coupon.value).div(100);
if (coupon.maxCartValue && discountAmount.greaterThan(coupon.maxCartValue)) {
discountAmount = new Prisma.Decimal(coupon.maxCartValue);
}
} else {
discountAmount = Number(coupon.value);
discountAmount = new Prisma.Decimal(coupon.value);
}
const finalDiscount = discountAmount.greaterThan(cartTotal)
? cartTotal
: discountAmount;
return {
couponId: coupon.id,
code: coupon.code,
discountAmount: Math.min(discountAmount, cartTotal),
discountAmount: finalDiscount,
};
}
@@ -90,9 +95,34 @@ export class OrdersService {
throw new BadRequestException('سبد خرید خالی است');
}
// Verify stock and build items
let cartTotal = 0;
const orderItems: Array<{
// 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('تکرار محصول در سبد خرید مجاز نیست');
}
for (const item of createOrderDto.items) {
if (item.quantity <= 0 || !Number.isInteger(item.quantity)) {
throw new BadRequestException(`تعداد محصول ${item.productId} نامعتبر است`);
}
}
// Batch fetch products using single findMany query
const products = await this.prisma.product.findMany({
where: { id: { in: productIds } },
});
const productMap = new Map(products.map((p) => [p.id, p]));
for (const productId of productIds) {
if (!productMap.has(productId)) {
throw new NotFoundException(`محصول یافت نشد`);
}
}
let cartTotal = new Prisma.Decimal(0);
const orderItemsData: Array<{
productId: string;
quantity: number;
unitPrice: number;
@@ -100,24 +130,20 @@ export class OrdersService {
}> = [];
for (const item of createOrderDto.items) {
const product = await this.prisma.product.findUnique({
where: { id: item.productId },
});
if (!product) {
throw new NotFoundException(`محصول یافت نشد`);
}
const itemPrice = Number(product.priceValue);
const totalItemPrice = itemPrice * item.quantity;
cartTotal += totalItemPrice;
orderItems.push({
const product = productMap.get(item.productId)!;
const unitPrice = new Prisma.Decimal(product.priceValue);
const totalItemPrice = unitPrice.mul(item.quantity);
cartTotal = cartTotal.add(totalItemPrice);
orderItemsData.push({
productId: item.productId,
quantity: item.quantity,
unitPrice: itemPrice,
totalPrice: totalItemPrice,
unitPrice: Number(unitPrice),
totalPrice: Number(totalItemPrice),
});
}
let discountAmount = 0;
let discountAmount = new Prisma.Decimal(0);
let couponId: string | undefined = undefined;
if (createOrderDto.couponCode) {
@@ -130,8 +156,9 @@ export class OrdersService {
couponId = couponResult.couponId;
}
const charityAmount = createOrderDto.charityDonation || 0;
const finalAmount = Math.max(0, cartTotal - discountAmount) + charityAmount;
const charityAmount = new Prisma.Decimal(createOrderDto.charityDonation || 0);
const totalAfterDiscount = cartTotal.sub(discountAmount);
const finalAmount = (totalAfterDiscount.lessThan(0) ? new Prisma.Decimal(0) : totalAfterDiscount).add(charityAmount);
const trackingNumber = this.generateTrackingNumber();
@@ -141,8 +168,8 @@ export class OrdersService {
if (!user) {
throw new NotFoundException('کاربر یافت نشد');
}
const userBalance = Number(user.walletBalance || 0);
if (userBalance < finalAmount) {
const userBalance = new Prisma.Decimal(user.walletBalance || 0);
if (userBalance.lessThan(finalAmount)) {
throw new BadRequestException(
'موجودی کیف پول برای پرداخت این سفارش کافی نیست',
);
@@ -152,24 +179,24 @@ export class OrdersService {
await tx.user.update({
where: { id: userId },
data: {
walletBalance: { decrement: finalAmount },
walletBalance: { decrement: Number(finalAmount) },
},
});
await tx.walletTransaction.create({
data: {
userId,
amount: finalAmount,
amount: Number(finalAmount),
type: 'withdrawal',
status: 'completed',
description: `پرداخت سفارش ${trackingNumber}`,
},
});
if (charityAmount > 0) {
if (charityAmount.greaterThan(0)) {
await tx.user.update({
where: { id: userId },
data: { charityDonationTotal: { increment: charityAmount } },
data: { charityDonationTotal: { increment: Number(charityAmount) } },
});
}
@@ -177,14 +204,14 @@ export class OrdersService {
data: {
userId,
couponId,
totalAmount: finalAmount,
charityDonation: charityAmount,
totalAmount: Number(finalAmount),
charityDonation: Number(charityAmount),
isRefill: Boolean(createOrderDto.isRefill),
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
trackingNumber,
status: 'processing',
orderItems: {
create: orderItems,
create: orderItemsData,
},
} as any,
include: {
@@ -200,14 +227,14 @@ export class OrdersService {
data: {
userId,
couponId,
totalAmount: finalAmount,
charityDonation: charityAmount,
totalAmount: Number(finalAmount),
charityDonation: Number(charityAmount),
isRefill: Boolean(createOrderDto.isRefill),
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
trackingNumber,
status: 'processing',
orderItems: {
create: orderItems,
create: orderItemsData,
},
} as any,
include: {
@@ -218,21 +245,25 @@ export class OrdersService {
});
// Send Order Confirmation SMS
if (userId) {
this.prisma.user
.findUnique({ where: { id: userId } })
.then((user) => {
if (user && user.mobile) {
this.smsService
.sendOrderConfirmation(
user.mobile,
trackingNumber,
finalAmount.toLocaleString('fa-IR'),
)
.catch(() => {});
}
})
.catch(() => {});
if (userId && this.prisma.user?.findUnique) {
try {
const userPromise = this.prisma.user.findUnique({ where: { id: userId } });
if (userPromise && typeof userPromise.then === 'function') {
userPromise
.then((user) => {
if (user && user.mobile) {
this.smsService
.sendOrderConfirmation(
user.mobile,
trackingNumber,
Number(finalAmount).toLocaleString('fa-IR'),
)
.catch(() => {});
}
})
.catch(() => {});
}
} catch (e) {}
}
return createdOrder;