Compare commits

..

No commits in common. "95e488baaaeeec67d63738648ef36c7d81a109c0" and "f0329d8b5be29e795b0b40aab96ef65b34b92e3d" have entirely different histories.

9 changed files with 62 additions and 147 deletions

View File

@ -1,4 +1,4 @@
import { Injectable, HttpException, NotFoundException } from '@nestjs/common'; import { Injectable, HttpException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service'; import { RedisService } from '../redis/redis.service';

View File

@ -27,10 +27,7 @@ export class AuthService {
// Dispatch OTP via MeliPayamak Pattern SMS // Dispatch OTP via MeliPayamak Pattern SMS
await this.smsService.sendOtp(phoneNumber, code); await this.smsService.sendOtp(phoneNumber, code);
return { return { success: true, message: 'کد تایید با موفقیت به شماره شما پیامک شد.' };
success: true,
message: 'کد تایید با موفقیت به شماره شما پیامک شد.',
};
} }
async verifyOtp(verifyOtpDto: VerifyOtpDto) { async verifyOtp(verifyOtpDto: VerifyOtpDto) {

View File

@ -19,10 +19,9 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
const request = ctx.getRequest<Request>(); const request = ctx.getRequest<Request>();
let status = HttpStatus.INTERNAL_SERVER_ERROR; let status = HttpStatus.INTERNAL_SERVER_ERROR;
let message = let message = 'خطای داخلی سرور رخ داده است. لطفاً بعداً تلاش کنید یا با پشتیبانی تماس بگیرید.';
'خطای داخلی سرور رخ داده است. لطفاً بعداً تلاش کنید یا با پشتیبانی تماس بگیرید.';
let code = 'INTERNAL_SERVER_ERROR'; let code = 'INTERNAL_SERVER_ERROR';
let details: ErrorDetailField[] | Record<string, unknown> = {}; let details: ErrorDetailField[] | Record<string, any> = {};
if (exception instanceof HttpException) { if (exception instanceof HttpException) {
status = exception.getStatus(); status = exception.getStatus();
@ -31,17 +30,14 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
if (typeof exceptionResponse === 'string') { if (typeof exceptionResponse === 'string') {
message = this.translateGenericMessage(exceptionResponse, status); message = this.translateGenericMessage(exceptionResponse, status);
code = this.deriveErrorCode(status, exceptionResponse); code = this.deriveErrorCode(status, exceptionResponse);
} else if ( } else if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
typeof exceptionResponse === 'object' && const resObj = exceptionResponse as Record<string, any>;
exceptionResponse !== null
) {
const resObj = exceptionResponse as Record<string, unknown>;
// Handle class-validator validation array messages // Handle class-validator validation array messages
if (Array.isArray(resObj.message)) { if (Array.isArray(resObj.message)) {
message = 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.'; message = 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.';
code = 'INVALID_INPUT_DATA'; code = 'INVALID_INPUT_DATA';
details = (resObj.message as string[]).map((msg: string) => { details = resObj.message.map((msg: string) => {
const parts = msg.split(' '); const parts = msg.split(' ');
return { return {
field: parts[0] || 'general', field: parts[0] || 'general',
@ -49,19 +45,13 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
}; };
}); });
} else { } else {
const rawMsg = typeof resObj.message === 'string' ? resObj.message : exception.message; message = this.translateGenericMessage(resObj.message || exception.message, status);
message = this.translateGenericMessage(rawMsg, status); code = resObj.code || this.deriveErrorCode(status, resObj.error);
const rawCode = typeof resObj.code === 'string' ? resObj.code : undefined; details = resObj.details || {};
const rawError = typeof resObj.error === 'string' ? resObj.error : undefined;
code = rawCode || this.deriveErrorCode(status, rawError);
details = (resObj.details as Record<string, unknown>) || {};
} }
} }
} else if (exception instanceof Error) { } else if (exception instanceof Error) {
this.logger.error( this.logger.error(`Unhandled Exception: ${exception.message}`, exception.stack);
`Unhandled Exception: ${exception.message}`,
exception.stack,
);
message = 'خطای غیرمنتظره در پردازش درخواست رخ داد.'; message = 'خطای غیرمنتظره در پردازش درخواست رخ داد.';
code = 'UNHANDLED_EXCEPTION'; code = 'UNHANDLED_EXCEPTION';
} }
@ -76,9 +66,7 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
path: request.url, path: request.url,
}; };
this.logger.warn( this.logger.warn(`[${request.method}] ${request.url} - Status ${status} - ${message}`);
`[${request.method}] ${request.url} - Status ${status} - ${message}`,
);
response.status(status).json(errorPayload); response.status(status).json(errorPayload);
} }
@ -112,22 +100,14 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
} }
switch (status) { switch (status) {
case 400: case 400: return 'BAD_REQUEST';
return 'BAD_REQUEST'; case 401: return 'UNAUTHORIZED';
case 401: case 403: return 'FORBIDDEN';
return 'UNAUTHORIZED'; case 404: return 'NOT_FOUND';
case 403: case 409: return 'CONFLICT';
return 'FORBIDDEN'; case 422: return 'UNPROCESSABLE_ENTITY';
case 404: case 429: return 'TOO_MANY_REQUESTS';
return 'NOT_FOUND'; default: return 'INTERNAL_SERVER_ERROR';
case 409:
return 'CONFLICT';
case 422:
return 'UNPROCESSABLE_ENTITY';
case 429:
return 'TOO_MANY_REQUESTS';
default:
return 'INTERNAL_SERVER_ERROR';
} }
} }
} }

View File

@ -20,7 +20,7 @@ export class PrismaExceptionFilter implements ExceptionFilter {
let status = HttpStatus.BAD_REQUEST; let status = HttpStatus.BAD_REQUEST;
let message = 'خطایی در پردازش اطلاعات دیتابیس رخ داده است.'; let message = 'خطایی در پردازش اطلاعات دیتابیس رخ داده است.';
let code = `PRISMA_${exception.code}`; let code = `PRISMA_${exception.code}`;
let details: Record<string, unknown> = {}; let details: Record<string, any> = {};
switch (exception.code) { switch (exception.code) {
case 'P2002': { case 'P2002': {
@ -34,16 +34,14 @@ export class PrismaExceptionFilter implements ExceptionFilter {
} }
case 'P2025': { case 'P2025': {
status = HttpStatus.NOT_FOUND; status = HttpStatus.NOT_FOUND;
message = message = 'اطلاعات یا رکورد مورد نظر در سیستم یافت نشد یا قبلاً حذف شده است.';
'اطلاعات یا رکورد مورد نظر در سیستم یافت نشد یا قبلاً حذف شده است.';
code = 'RECORD_NOT_FOUND'; code = 'RECORD_NOT_FOUND';
details = { meta: exception.meta }; details = { meta: exception.meta };
break; break;
} }
case 'P2003': { case 'P2003': {
status = HttpStatus.BAD_REQUEST; status = HttpStatus.BAD_REQUEST;
message = message = 'امکان انجام عملیات به دلیل وجود وابستگی بین اطلاعات وجود ندارد.';
'امکان انجام عملیات به دلیل وجود وابستگی بین اطلاعات وجود ندارد.';
code = 'FOREIGN_KEY_CONSTRAINT_FAILED'; code = 'FOREIGN_KEY_CONSTRAINT_FAILED';
break; break;
} }
@ -54,9 +52,7 @@ export class PrismaExceptionFilter implements ExceptionFilter {
} }
} }
this.logger.error( this.logger.error(`[Prisma ${exception.code}] ${request.method} ${request.url} - ${message}`);
`[Prisma ${exception.code}] ${request.method} ${request.url} - ${message}`,
);
response.status(status).json({ response.status(status).json({
success: false, success: false,

View File

@ -4,18 +4,12 @@ export class ErrorDetailField {
@ApiProperty({ description: 'نام فیلد دارای خطا', example: 'phone' }) @ApiProperty({ description: 'نام فیلد دارای خطا', example: 'phone' })
field: string; field: string;
@ApiProperty({ @ApiProperty({ description: 'توضیح توصیفی خطا به فارسی', example: 'شماره تلفن همراه وارد شده نامعتبر است.' })
description: 'توضیح توصیفی خطا به فارسی',
example: 'شماره تلفن همراه وارد شده نامعتبر است.',
})
message: string; message: string;
} }
export class ApiErrorResponse { export class ApiErrorResponse {
@ApiProperty({ @ApiProperty({ description: 'وضعیت موفقیت درخواست (همیشه false در زمان خطا)', example: false })
description: 'وضعیت موفقیت درخواست (همیشه false در زمان خطا)',
example: false,
})
success: boolean; success: boolean;
@ApiProperty({ description: 'کد وضعیت HTTP درخواست', example: 400 }) @ApiProperty({ description: 'کد وضعیت HTTP درخواست', example: 400 })
@ -23,15 +17,11 @@ export class ApiErrorResponse {
@ApiProperty({ @ApiProperty({
description: 'پیام جامع و توصیفی خطا به زبان فارسی', description: 'پیام جامع و توصیفی خطا به زبان فارسی',
example: example: 'اطلاعات وارد شده نامعتبر است. لطفاً موارد مشخص شده را بررسی نمایید.',
'اطلاعات وارد شده نامعتبر است. لطفاً موارد مشخص شده را بررسی نمایید.',
}) })
message: string; message: string;
@ApiProperty({ @ApiProperty({ description: 'کد سیستمیک و ثابت خطا جهت پردازش فرانت‌اند', example: 'INVALID_INPUT_DATA' })
description: 'کد سیستمیک و ثابت خطا جهت پردازش فرانت‌اند',
example: 'INVALID_INPUT_DATA',
})
code: string; code: string;
@ApiProperty({ @ApiProperty({
@ -41,15 +31,9 @@ export class ApiErrorResponse {
}) })
details?: ErrorDetailField[] | Record<string, any>; details?: ErrorDetailField[] | Record<string, any>;
@ApiProperty({ @ApiProperty({ description: 'زمان وقوع خطا به فرمت ISO', example: '2026-07-29T16:30:00.000Z' })
description: 'زمان وقوع خطا به فرمت ISO',
example: '2026-07-29T16:30:00.000Z',
})
timestamp: string; timestamp: string;
@ApiProperty({ @ApiProperty({ description: 'مسیر و انکوینتی که خطا در آن رخ داده است', example: '/api/auth/register' })
description: 'مسیر و انکوینتی که خطا در آن رخ داده است',
example: '/api/auth/register',
})
path: string; path: string;
} }

View File

@ -68,9 +68,7 @@ export class SmsService {
); );
req.on('error', (err) => { req.on('error', (err) => {
this.logger.error( this.logger.error(`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`);
`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`,
);
resolve(false); resolve(false);
}); });
@ -94,11 +92,7 @@ export class SmsService {
/** /**
* Send Order Confirmation SMS * Send Order Confirmation SMS
*/ */
async sendOrderConfirmation( async sendOrderConfirmation(phone: string, orderNumber: string, amount: string): Promise<boolean> {
phone: string,
orderNumber: string,
amount: string,
): Promise<boolean> {
const bodyId = parseInt(process.env.MELIPAYAMAK_ORDER_BODY_ID || '0', 10); const bodyId = parseInt(process.env.MELIPAYAMAK_ORDER_BODY_ID || '0', 10);
return this.sendPatternSms({ return this.sendPatternSms({
to: phone, to: phone,
@ -110,15 +104,8 @@ export class SmsService {
/** /**
* Send Shipping Status SMS with Tracking Code * Send Shipping Status SMS with Tracking Code
*/ */
async sendShippingNotification( async sendShippingNotification(phone: string, orderNumber: string, trackingCode: string): Promise<boolean> {
phone: string, const bodyId = parseInt(process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '0', 10);
orderNumber: string,
trackingCode: string,
): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '0',
10,
);
return this.sendPatternSms({ return this.sendPatternSms({
to: phone, to: phone,
bodyId, bodyId,
@ -129,15 +116,8 @@ export class SmsService {
/** /**
* Send Pet Care Vaccination / Deworming Reminder SMS * Send Pet Care Vaccination / Deworming Reminder SMS
*/ */
async sendPetCareReminder( async sendPetCareReminder(phone: string, petName: string, reminderType: string): Promise<boolean> {
phone: string, const bodyId = parseInt(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0', 10);
petName: string,
reminderType: string,
): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0',
10,
);
return this.sendPatternSms({ return this.sendPatternSms({
to: phone, to: phone,
bodyId, bodyId,

View File

@ -36,21 +36,15 @@ async function bootstrap() {
forbidNonWhitelisted: true, forbidNonWhitelisted: true,
exceptionFactory: (errors) => { exceptionFactory: (errors) => {
const formattedDetails = errors.map((err) => { const formattedDetails = errors.map((err) => {
const constraints = err.constraints const constraints = err.constraints ? Object.values(err.constraints) : [];
? Object.values(err.constraints)
: [];
return { return {
field: err.property, field: err.property,
message: message: constraints.length > 0 ? constraints[0] : 'مقدار وارد شده نامعتبر است.',
constraints.length > 0
? constraints[0]
: 'مقدار وارد شده نامعتبر است.',
}; };
}); });
return new BadRequestException({ return new BadRequestException({
message: message: 'اطلاعات ورودی فرم معتبر نمی‌باشد. لطفاً موارد مشخص شده را اصلاح نمایید.',
'اطلاعات ورودی فرم معتبر نمی‌باشد. لطفاً موارد مشخص شده را اصلاح نمایید.',
error: 'INVALID_INPUT_DATA', error: 'INVALID_INPUT_DATA',
details: formattedDetails, details: formattedDetails,
}); });
@ -58,10 +52,7 @@ async function bootstrap() {
}), }),
); );
app.useGlobalFilters( app.useGlobalFilters(new CustomHttpExceptionFilter(), new PrismaExceptionFilter());
new CustomHttpExceptionFilter(),
new PrismaExceptionFilter(),
);
const config = new DocumentBuilder() const config = new DocumentBuilder()
.setTitle('Canina Iran API') .setTitle('Canina Iran API')

View File

@ -92,12 +92,7 @@ export class OrdersService {
// Verify stock and build items // Verify stock and build items
let cartTotal = 0; let cartTotal = 0;
const orderItems: Array<{ const orderItems: Array<{ productId: string; quantity: number; unitPrice: number; totalPrice: number }> = [];
productId: string;
quantity: number;
unitPrice: number;
totalPrice: number;
}> = [];
for (const item of createOrderDto.items) { for (const item of createOrderDto.items) {
const product = await this.prisma.product.findUnique({ const product = await this.prisma.product.findUnique({
@ -187,20 +182,15 @@ export class OrdersService {
// Send Order Confirmation SMS // Send Order Confirmation SMS
if (userId) { if (userId) {
this.prisma.user this.prisma.user.findUnique({ where: { id: userId } }).then((user) => {
.findUnique({ where: { id: userId } })
.then((user) => {
if (user && user.mobile) { if (user && user.mobile) {
this.smsService this.smsService.sendOrderConfirmation(
.sendOrderConfirmation(
user.mobile, user.mobile,
trackingNumber, trackingNumber,
finalAmount.toLocaleString('fa-IR'), finalAmount.toLocaleString('fa-IR'),
) ).catch(() => {});
.catch(() => {});
} }
}) }).catch(() => {});
.catch(() => {});
} }
return createdOrder; return createdOrder;
@ -229,9 +219,11 @@ export class OrdersService {
const mobile = updatedOrder.user?.mobile; const mobile = updatedOrder.user?.mobile;
const trackingNum = updatedOrder.trackingNumber || trackingCode || ''; const trackingNum = updatedOrder.trackingNumber || trackingCode || '';
if (status === 'shipped' && mobile && trackingCode) { if (status === 'shipped' && mobile && trackingCode) {
this.smsService this.smsService.sendShippingNotification(
.sendShippingNotification(mobile, trackingNum, trackingCode) mobile,
.catch(() => {}); trackingNum,
trackingCode,
).catch(() => {});
} }
return updatedOrder; return updatedOrder;

View File

@ -26,16 +26,11 @@ export class WholesaleService {
// Alert admin via SMS if admin mobile is configured // Alert admin via SMS if admin mobile is configured
const adminMobile = process.env.ADMIN_MOBILE_ALERT; const adminMobile = process.env.ADMIN_MOBILE_ALERT;
if (adminMobile) { if (adminMobile) {
this.smsService this.smsService.sendPatternSms({
.sendPatternSms({
to: adminMobile, to: adminMobile,
bodyId: parseInt( bodyId: parseInt(process.env.MELIPAYAMAK_ADMIN_ALERT_BODY_ID || '0', 10),
process.env.MELIPAYAMAK_ADMIN_ALERT_BODY_ID || '0',
10,
),
args: [dto.businessName || 'نامشخص', user.mobile || ''], args: [dto.businessName || 'نامشخص', user.mobile || ''],
}) }).catch(() => {});
.catch(() => {});
} }
return { return {