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

+1 -4
View File
@@ -1,4 +1 @@
import { SetMetadata } from '@nestjs/common';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
export * from '../common/decorators/roles.decorator';
+1 -40
View File
@@ -1,41 +1,2 @@
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './roles.decorator';
export * from '../common/guards/roles.guard';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (!user || !user.role) {
throw new ForbiddenException('شما دسترسی لازم برای این بخش را ندارید');
}
const userRoleLower = user.role.toLowerCase();
const hasRole = requiredRoles.some(
(r) =>
r.toLowerCase() === userRoleLower ||
(userRoleLower.includes('admin') && r.toLowerCase().includes('admin')),
);
if (!hasRole) {
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
}
return true;
}
}
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
@@ -0,0 +1,71 @@
import { Test, TestingModule } from '@nestjs/testing';
import { RolesGuard } from './roles.guard';
import { Reflector } from '@nestjs/core';
import { ExecutionContext, ForbiddenException } from '@nestjs/common';
import { ROLES_KEY } from '../decorators/roles.decorator';
describe('RolesGuard', () => {
let guard: RolesGuard;
let reflector: Reflector;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
RolesGuard,
{
provide: Reflector,
useValue: {
getAllAndOverride: jest.fn(),
},
},
],
}).compile();
guard = module.get<RolesGuard>(RolesGuard);
reflector = module.get<Reflector>(Reflector);
});
const createMockContext = (user?: any): ExecutionContext => {
return {
getHandler: jest.fn(),
getClass: jest.fn(),
switchToHttp: () => ({
getRequest: () => ({ user }),
}),
} as any;
};
it('should be defined', () => {
expect(guard).toBeDefined();
});
it('should allow access if no roles are required', () => {
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(undefined);
const context = createMockContext({ role: 'User_PetOwner' });
expect(guard.canActivate(context)).toBe(true);
});
it('should throw ForbiddenException if user is missing', () => {
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
const context = createMockContext(undefined);
expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
});
it('should throw ForbiddenException if user has non-matching role', () => {
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
const context = createMockContext({ role: 'User_PetOwner' });
expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
});
it('should allow access if user has matching role', () => {
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
const context = createMockContext({ role: 'Admin' });
expect(guard.canActivate(context)).toBe(true);
});
it('should allow access if user has case-insensitive matching admin role', () => {
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
const context = createMockContext({ role: 'SUPER_ADMIN' });
expect(guard.canActivate(context)).toBe(true);
});
});
+41
View File
@@ -0,0 +1,41 @@
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (!user || !user.role) {
throw new ForbiddenException('شما دسترسی لازم برای این بخش را ندارید');
}
const userRoleLower = user.role.toLowerCase();
const hasRole = requiredRoles.some(
(r) =>
r.toLowerCase() === userRoleLower ||
(userRoleLower.includes('admin') && r.toLowerCase().includes('admin')),
);
if (!hasRole) {
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
}
return true;
}
}
@@ -0,0 +1,65 @@
import { DecimalInterceptor } from './decimal.interceptor';
import { Prisma } from '@prisma/client';
import { of } from 'rxjs';
describe('DecimalInterceptor', () => {
let interceptor: DecimalInterceptor;
beforeEach(() => {
interceptor = new DecimalInterceptor();
});
it('should be defined', () => {
expect(interceptor).toBeDefined();
});
it('should transform Prisma.Decimal instances to exact string representations', (done) => {
const mockData = {
id: 'order-1',
totalAmount: new Prisma.Decimal('64.98'),
items: [
{
id: 'item-1',
unitPrice: new Prisma.Decimal('32.49'),
},
],
};
const executionContext: any = {};
const callHandler: any = {
handle: () => of(mockData),
};
interceptor.intercept(executionContext, callHandler).subscribe((result) => {
expect(result).toEqual({
id: 'order-1',
totalAmount: '64.98',
items: [
{
id: 'item-1',
unitPrice: '32.49',
},
],
});
done();
});
});
it('should leave non-decimal values unchanged', (done) => {
const mockData = {
name: 'Test',
age: 5,
isActive: true,
createdAt: new Date('2026-01-01T00:00:00.000Z'),
};
const callHandler: any = {
handle: () => of(mockData),
};
interceptor.intercept({} as any, callHandler).subscribe((result) => {
expect(result).toEqual(mockData);
done();
});
});
});
@@ -0,0 +1,40 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Prisma } from '@prisma/client';
@Injectable()
export class DecimalInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(map((data) => this.transform(data)));
}
private transform(data: any): any {
if (data === null || data === undefined) {
return data;
}
if (Prisma.Decimal.isDecimal(data)) {
return data.toString();
}
if (Array.isArray(data)) {
return data.map((item) => this.transform(item));
}
if (typeof data === 'object' && !(data instanceof Date)) {
const transformedObj: Record<string, any> = {};
for (const key of Object.keys(data)) {
transformedObj[key] = this.transform(data[key]);
}
return transformedObj;
}
return data;
}
}
+3
View File
@@ -6,6 +6,7 @@ import { ValidationPipe, BadRequestException } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { CustomHttpExceptionFilter } from './common/filters/http-exception.filter';
import { PrismaExceptionFilter } from './common/filters/prisma-exception.filter';
import { DecimalInterceptor } from './common/interceptors/decimal.interceptor';
import helmet from 'helmet';
async function bootstrap() {
@@ -80,6 +81,8 @@ async function bootstrap() {
new PrismaExceptionFilter(),
);
app.useGlobalInterceptors(new DecimalInterceptor());
const config = new DocumentBuilder()
.setTitle('Canina Iran API')
.setDescription(
+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;
@@ -1,6 +1,11 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SettingsController } from './settings.controller';
import { SettingsService } from './settings.service';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { ROLES_KEY } from '../common/decorators/roles.decorator';
import { Reflector } from '@nestjs/core';
describe('SettingsController', () => {
let controller: SettingsController;
@@ -32,6 +37,16 @@ describe('SettingsController', () => {
expect(controller).toBeDefined();
});
it('should have JwtAuthGuard, RolesGuard and Admin role applied at controller level', () => {
const guards = Reflect.getMetadata(GUARDS_METADATA, SettingsController);
expect(guards).toBeDefined();
expect(guards).toContain(JwtAuthGuard);
expect(guards).toContain(RolesGuard);
const roles = Reflect.getMetadata(ROLES_KEY, SettingsController);
expect(roles).toEqual(['Admin']);
});
it('should getUiTexts', async () => {
const result = await controller.getUiTexts();
expect(service.getUiTexts).toHaveBeenCalled();
@@ -63,3 +78,4 @@ describe('SettingsController', () => {
expect(result).toBeDefined();
});
});
@@ -11,6 +11,8 @@ import {
} from '@nestjs/common';
import { SettingsService } from './settings.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import {
ApiTags,
ApiOperation,
@@ -21,6 +23,8 @@ import {
} from '@nestjs/swagger';
@ApiTags('Settings - تنظیمات متون پویا و واژه‌نامه علمی')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@Controller('settings')
export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}