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 { RedisService } from '../redis/redis.service';

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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