fix(admin): sync product update & image URL features to main
Deploy Canina / deploy (push) Failing after 1m1s
Deploy Canina / deploy (push) Failing after 1m1s
This commit is contained in:
commit
f0329d8b5b
21 files changed
+931
-973
No files matched your search
@@ -168,6 +168,11 @@ export class AdminService {
|
||||
}
|
||||
|
||||
async updateProduct(id: string, data: any) {
|
||||
const existing = await this.prisma.product.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
throw new NotFoundException(`محصولی با شناسه ${id} یافت نشد.`);
|
||||
}
|
||||
|
||||
const product = await this.prisma.product.update({
|
||||
where: { id },
|
||||
data: {
|
||||
|
||||
@@ -19,9 +19,11 @@ import { SeoModule } from './seo/seo.module';
|
||||
import { CmsModule } from './cms/cms.module';
|
||||
import { WholesaleModule } from './wholesale/wholesale.module';
|
||||
import { VideosModule } from './videos/videos.module';
|
||||
import { SmsModule } from './common/sms.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
SmsModule,
|
||||
PrismaModule,
|
||||
RedisModule,
|
||||
ProductsModule,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { SendOtpDto } from './dto/send-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
|
||||
@Injectable()
|
||||
@@ -12,19 +13,21 @@ export class AuthService {
|
||||
private prisma: PrismaService,
|
||||
private jwtService: JwtService,
|
||||
private redisService: RedisService,
|
||||
private smsService: SmsService,
|
||||
) {}
|
||||
|
||||
async sendOtp(sendOtpDto: SendOtpDto) {
|
||||
const { phoneNumber } = sendOtpDto;
|
||||
|
||||
const code = Math.floor(10000 + Math.random() * 90000).toString();
|
||||
// In production: replace this log with a real SMS provider (e.g. KaveNegar, Melipayamak)
|
||||
console.log(`[Dev SMS] OTP for ${phoneNumber}: ${code}`);
|
||||
console.log(`[SMS OTP] Code for ${phoneNumber}: ${code}`);
|
||||
|
||||
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
|
||||
|
||||
// SECURITY: Never return the OTP code in the response
|
||||
return { success: true, message: 'کد تایید ارسال شد' };
|
||||
// Dispatch OTP via MeliPayamak Pattern SMS
|
||||
await this.smsService.sendOtp(phoneNumber, code);
|
||||
|
||||
return { success: true, message: 'کد تایید با موفقیت به شماره شما پیامک شد.' };
|
||||
}
|
||||
|
||||
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
|
||||
|
||||
@@ -3,47 +3,111 @@ import {
|
||||
Catch,
|
||||
ArgumentsHost,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { Request, Response } from 'express';
|
||||
import { ErrorDetailField } from '../schemas/error-response.schema';
|
||||
|
||||
@Catch(HttpException)
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: HttpException, host: ArgumentsHost) {
|
||||
@Catch()
|
||||
export class CustomHttpExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(CustomHttpExceptionFilter.name);
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const status = exception.getStatus();
|
||||
const exceptionResponse: any = exception.getResponse();
|
||||
const request = ctx.getRequest<Request>();
|
||||
|
||||
let message =
|
||||
typeof exceptionResponse === 'string'
|
||||
? exceptionResponse
|
||||
: exceptionResponse.message || 'خطای سرور';
|
||||
let code =
|
||||
typeof exceptionResponse === 'object' && exceptionResponse.error
|
||||
? exceptionResponse.error
|
||||
: status === 400
|
||||
? 'BAD_REQUEST'
|
||||
: 'ERROR';
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let message = 'خطای داخلی سرور رخ داده است. لطفاً بعداً تلاش کنید یا با پشتیبانی تماس بگیرید.';
|
||||
let code = 'INTERNAL_SERVER_ERROR';
|
||||
let details: ErrorDetailField[] | Record<string, any> = {};
|
||||
|
||||
// Convert array of class-validator errors to a generic Farsi message if it's a 400
|
||||
if (Array.isArray(message) && status === 400) {
|
||||
message = 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.';
|
||||
} else if (message === 'Unauthorized' || status === 401) {
|
||||
message = 'شما دسترسی لازم برای این عملیات را ندارید. لطفاً وارد شوید.';
|
||||
code = 'UNAUTHORIZED';
|
||||
} else if (message === 'Forbidden' || status === 403) {
|
||||
message = 'دسترسی غیرمجاز.';
|
||||
code = 'FORBIDDEN';
|
||||
} else if (message === 'Not Found' || status === 404) {
|
||||
message = 'مورد درخواستی یافت نشد.';
|
||||
code = 'NOT_FOUND';
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const exceptionResponse = exception.getResponse();
|
||||
|
||||
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, any>;
|
||||
|
||||
// Handle class-validator validation array messages
|
||||
if (Array.isArray(resObj.message)) {
|
||||
message = 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.';
|
||||
code = 'INVALID_INPUT_DATA';
|
||||
details = resObj.message.map((msg: string) => {
|
||||
const parts = msg.split(' ');
|
||||
return {
|
||||
field: parts[0] || 'general',
|
||||
message: msg,
|
||||
};
|
||||
});
|
||||
} else {
|
||||
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);
|
||||
message = 'خطای غیرمنتظره در پردازش درخواست رخ داد.';
|
||||
code = 'UNHANDLED_EXCEPTION';
|
||||
}
|
||||
|
||||
response.status(status).json({
|
||||
const errorPayload = {
|
||||
success: false,
|
||||
statusCode: status,
|
||||
message,
|
||||
code,
|
||||
details: typeof exceptionResponse === 'object' ? exceptionResponse : {},
|
||||
});
|
||||
details,
|
||||
timestamp: new Date().toISOString(),
|
||||
path: request.url,
|
||||
};
|
||||
|
||||
this.logger.warn(`[${request.method}] ${request.url} - Status ${status} - ${message}`);
|
||||
|
||||
response.status(status).json(errorPayload);
|
||||
}
|
||||
|
||||
private translateGenericMessage(msg: string, status: number): string {
|
||||
if (!msg) return 'خطای نامشخص رخ داده است.';
|
||||
|
||||
const lower = msg.toLowerCase();
|
||||
if (lower.includes('unauthorized') || status === 401) {
|
||||
return 'شما دسترسی لازم برای این عملیات را ندارید. لطفاً ابتدا وارد حساب کاربری خود شوید.';
|
||||
}
|
||||
if (lower.includes('forbidden') || status === 403) {
|
||||
return 'دسترسی شما به این بخش یا منبع محدود شده است.';
|
||||
}
|
||||
if (lower.includes('not found') || status === 404) {
|
||||
return 'مورد یا صفحه درخواستی یافت نشد.';
|
||||
}
|
||||
if (status === 400) {
|
||||
return 'درخواست نامعتبر است. لطفاً پارامترهای ورودی را چک کنید.';
|
||||
}
|
||||
if (status === 429) {
|
||||
return 'تعداد درخواستهای شما بیش از حد مجاز است. لطفاً کمی صبر کرده و مجدداً تلاش کنید.';
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
private deriveErrorCode(status: number, defaultError?: string): string {
|
||||
if (defaultError && typeof defaultError === 'string') {
|
||||
return defaultError.toUpperCase().replace(/\s+/g, '_');
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
ExceptionFilter,
|
||||
Catch,
|
||||
ArgumentsHost,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
@Catch(Prisma.PrismaClientKnownRequestError)
|
||||
export class PrismaExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(PrismaExceptionFilter.name);
|
||||
|
||||
catch(exception: Prisma.PrismaClientKnownRequestError, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const request = ctx.getRequest<Request>();
|
||||
|
||||
let status = HttpStatus.BAD_REQUEST;
|
||||
let message = 'خطایی در پردازش اطلاعات دیتابیس رخ داده است.';
|
||||
let code = `PRISMA_${exception.code}`;
|
||||
let details: Record<string, any> = {};
|
||||
|
||||
switch (exception.code) {
|
||||
case 'P2002': {
|
||||
status = HttpStatus.CONFLICT;
|
||||
const target = (exception.meta?.target as string[]) || [];
|
||||
const fieldName = target.join(', ');
|
||||
message = `اطلاعات وارد شده در فیلد (${fieldName}) تکراری است و قبلاً ثبت شده است.`;
|
||||
code = 'DUPLICATE_ENTRY';
|
||||
details = { field: fieldName, meta: exception.meta };
|
||||
break;
|
||||
}
|
||||
case 'P2025': {
|
||||
status = HttpStatus.NOT_FOUND;
|
||||
message = 'اطلاعات یا رکورد مورد نظر در سیستم یافت نشد یا قبلاً حذف شده است.';
|
||||
code = 'RECORD_NOT_FOUND';
|
||||
details = { meta: exception.meta };
|
||||
break;
|
||||
}
|
||||
case 'P2003': {
|
||||
status = HttpStatus.BAD_REQUEST;
|
||||
message = 'امکان انجام عملیات به دلیل وجود وابستگی بین اطلاعات وجود ندارد.';
|
||||
code = 'FOREIGN_KEY_CONSTRAINT_FAILED';
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
message = `خطای دیتابیس (کد ${exception.code}): لطفاً با پشتیبانی تماس بگیرید.`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.error(`[Prisma ${exception.code}] ${request.method} ${request.url} - ${message}`);
|
||||
|
||||
response.status(status).json({
|
||||
success: false,
|
||||
statusCode: status,
|
||||
message,
|
||||
code,
|
||||
details,
|
||||
timestamp: new Date().toISOString(),
|
||||
path: request.url,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,39 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class ErrorDetailField {
|
||||
@ApiProperty({ description: 'نام فیلد دارای خطا', example: 'phone' })
|
||||
field: string;
|
||||
|
||||
@ApiProperty({ description: 'توضیح توصیفی خطا به فارسی', example: 'شماره تلفن همراه وارد شده نامعتبر است.' })
|
||||
message: string;
|
||||
}
|
||||
|
||||
export class ApiErrorResponse {
|
||||
@ApiProperty({ description: 'موفقیتآمیز بودن درخواست', example: false })
|
||||
@ApiProperty({ description: 'وضعیت موفقیت درخواست (همیشه false در زمان خطا)', example: false })
|
||||
success: boolean;
|
||||
|
||||
@ApiProperty({ description: 'کد وضعیت HTTP درخواست', example: 400 })
|
||||
statusCode: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'پیام خطا',
|
||||
example: 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.',
|
||||
description: 'پیام جامع و توصیفی خطا به زبان فارسی',
|
||||
example: 'اطلاعات وارد شده نامعتبر است. لطفاً موارد مشخص شده را بررسی نمایید.',
|
||||
})
|
||||
message: string;
|
||||
|
||||
@ApiProperty({ description: 'کد خطا', example: 'BAD_REQUEST' })
|
||||
@ApiProperty({ description: 'کد سیستمیک و ثابت خطا جهت پردازش فرانتاند', example: 'INVALID_INPUT_DATA' })
|
||||
code: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'جزئیات خطا (در صورت وجود)',
|
||||
description: 'جزئیات فیلدها و خطاهای اعتبارسنجی (در صورت وجود)',
|
||||
required: false,
|
||||
example: {},
|
||||
type: [ErrorDetailField],
|
||||
})
|
||||
details?: any;
|
||||
details?: ErrorDetailField[] | Record<string, any>;
|
||||
|
||||
@ApiProperty({ description: 'زمان وقوع خطا به فرمت ISO', example: '2026-07-29T16:30:00.000Z' })
|
||||
timestamp: string;
|
||||
|
||||
@ApiProperty({ description: 'مسیر و انکوینتی که خطا در آن رخ داده است', example: '/api/auth/register' })
|
||||
path: string;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as http from 'http';
|
||||
import * as https from 'https';
|
||||
|
||||
export interface SendPatternSmsOptions {
|
||||
to: string;
|
||||
bodyId: number; // MeliPayamak Shared Pattern Body ID
|
||||
args: string[]; // Dynamic variables inside pattern
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private readonly logger = new Logger(SmsService.name);
|
||||
private readonly username = process.env.MELIPAYAMAK_USERNAME || '';
|
||||
private readonly password = process.env.MELIPAYAMAK_PASSWORD || '';
|
||||
|
||||
/**
|
||||
* Send Pattern SMS using MeliPayamak Shared Service Line (Bypasses Blacklist)
|
||||
*/
|
||||
async sendPatternSms(options: SendPatternSmsOptions): Promise<boolean> {
|
||||
if (!this.username || !this.password) {
|
||||
this.logger.warn(
|
||||
`[SMS Disabled] MeliPayamak credentials missing. Simulated dispatch to ${options.to} (Pattern: ${options.bodyId}, Args: ${options.args.join(', ')})`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
text: options.args.join(';'),
|
||||
to: options.to,
|
||||
bodyId: options.bodyId,
|
||||
});
|
||||
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
if (json && (json.Value > 15 || json.RetStatus === 1)) {
|
||||
this.logger.log(
|
||||
`[SMS Sent] Pattern SMS ${options.bodyId} dispatched to ${options.to} (RecId: ${json.Value})`,
|
||||
);
|
||||
resolve(true);
|
||||
} else {
|
||||
this.logger.error(
|
||||
`[SMS Error] Failed sending pattern SMS to ${options.to}. Code: ${json?.Value}`,
|
||||
);
|
||||
resolve(false);
|
||||
}
|
||||
} catch {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err) => {
|
||||
this.logger.error(`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`);
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send OTP Verification Code
|
||||
*/
|
||||
async sendOtp(phone: string, otpCode: string): Promise<boolean> {
|
||||
const bodyId = parseInt(process.env.MELIPAYAMAK_OTP_BODY_ID || '0', 10);
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
args: [otpCode],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Order Confirmation SMS
|
||||
*/
|
||||
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,
|
||||
bodyId,
|
||||
args: [orderNumber, amount],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
args: [orderNumber, trackingCode],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
args: [petName, reminderType],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { SmsService } from './services/sms.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [SmsService],
|
||||
exports: [SmsService],
|
||||
})
|
||||
export class SmsModule {}
|
||||
+20
-3
@@ -2,9 +2,10 @@ import { NestFactory } from '@nestjs/core';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { AppModule } from './app.module';
|
||||
import { join } from 'path';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { ValidationPipe, BadRequestException } from '@nestjs/common';
|
||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { CustomHttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { PrismaExceptionFilter } from './common/filters/prisma-exception.filter';
|
||||
import helmet from 'helmet';
|
||||
|
||||
async function bootstrap() {
|
||||
@@ -33,9 +34,25 @@ async function bootstrap() {
|
||||
transform: true,
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
exceptionFactory: (errors) => {
|
||||
const formattedDetails = errors.map((err) => {
|
||||
const constraints = err.constraints ? Object.values(err.constraints) : [];
|
||||
return {
|
||||
field: err.property,
|
||||
message: constraints.length > 0 ? constraints[0] : 'مقدار وارد شده نامعتبر است.',
|
||||
};
|
||||
});
|
||||
|
||||
return new BadRequestException({
|
||||
message: 'اطلاعات ورودی فرم معتبر نمیباشد. لطفاً موارد مشخص شده را اصلاح نمایید.',
|
||||
error: 'INVALID_INPUT_DATA',
|
||||
details: formattedDetails,
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
|
||||
app.useGlobalFilters(new CustomHttpExceptionFilter(), new PrismaExceptionFilter());
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Canina Iran API')
|
||||
|
||||
@@ -6,11 +6,14 @@ import {
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { PaginationDto } from '../common/dto/pagination.dto';
|
||||
import { CreateOrderDto } from './dto/create-order.dto';
|
||||
import { Decimal } from '@prisma/client/runtime/library';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
|
||||
@Injectable()
|
||||
export class OrdersService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private smsService: SmsService,
|
||||
) {}
|
||||
|
||||
private generateTrackingNumber(): string {
|
||||
const date = new Date();
|
||||
@@ -60,84 +63,71 @@ export class OrdersService {
|
||||
!userTargets.some((t) => t.targetId === userId)
|
||||
) {
|
||||
throw new BadRequestException({
|
||||
message: 'این کد تخفیف برای حساب شما معتبر نیست',
|
||||
error: 'COUPON_NOT_FOR_USER',
|
||||
message: 'این کد تخفیف برای حساب کاربری شما فعال نیست',
|
||||
error: 'COUPON_USER_MISMATCH',
|
||||
});
|
||||
}
|
||||
|
||||
let discountValue: number;
|
||||
if (coupon.type === 'percent') {
|
||||
discountValue = cartTotal * (Number(coupon.value) / 100);
|
||||
if (coupon.maxCartValue) {
|
||||
discountValue = Math.min(discountValue, Number(coupon.maxCartValue));
|
||||
let discountAmount = 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);
|
||||
}
|
||||
} else {
|
||||
discountValue = Number(coupon.value);
|
||||
discountAmount = Number(coupon.value);
|
||||
}
|
||||
|
||||
discountValue = Math.min(discountValue, cartTotal);
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
couponId: coupon.id,
|
||||
code: coupon.code,
|
||||
type: coupon.type,
|
||||
discountValue,
|
||||
message: `کد تخفیف اعمال شد — ${discountValue.toLocaleString('fa-IR')} تومان تخفیف`,
|
||||
discountAmount: Math.min(discountAmount, cartTotal),
|
||||
};
|
||||
}
|
||||
|
||||
async create(userId: string, createOrderDto: CreateOrderDto) {
|
||||
let totalAmount = 0;
|
||||
let couponId: string | null = null;
|
||||
const orderItems = [];
|
||||
if (!createOrderDto.items || createOrderDto.items.length === 0) {
|
||||
throw new BadRequestException('سبد خرید خالی است');
|
||||
}
|
||||
|
||||
// Verify stock and build items
|
||||
let cartTotal = 0;
|
||||
const orderItems: Array<{ productId: string; quantity: number; unitPrice: number; totalPrice: number }> = [];
|
||||
|
||||
for (const item of createOrderDto.items) {
|
||||
const product = await this.prisma.product.findUnique({
|
||||
where: { id: item.productId },
|
||||
});
|
||||
if (!product) {
|
||||
throw new NotFoundException(
|
||||
`محصول با شناسه ${item.productId} یافت نشد`,
|
||||
);
|
||||
throw new NotFoundException(`محصول یافت نشد`);
|
||||
}
|
||||
totalAmount += Number(product.priceValue) * item.quantity;
|
||||
const itemPrice = Number(product.priceValue);
|
||||
const totalItemPrice = itemPrice * item.quantity;
|
||||
cartTotal += totalItemPrice;
|
||||
orderItems.push({
|
||||
productId: product.id,
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
unitPrice: itemPrice,
|
||||
totalPrice: totalItemPrice,
|
||||
});
|
||||
}
|
||||
|
||||
if (orderItems.length === 0) {
|
||||
throw new BadRequestException('سبد خرید خالی است');
|
||||
}
|
||||
|
||||
// Apply coupon if provided
|
||||
let discountAmount = 0;
|
||||
let couponId: string | undefined = undefined;
|
||||
|
||||
if (createOrderDto.couponCode) {
|
||||
try {
|
||||
const couponResult = await this.validateCoupon(
|
||||
createOrderDto.couponCode,
|
||||
totalAmount,
|
||||
userId,
|
||||
);
|
||||
discountAmount = couponResult.discountValue;
|
||||
couponId = couponResult.couponId;
|
||||
// Increment usedCount
|
||||
await this.prisma.coupon.update({
|
||||
where: { id: couponId },
|
||||
data: { usedCount: { increment: 1 } },
|
||||
});
|
||||
} catch {
|
||||
// Invalid coupon — ignore and proceed without discount
|
||||
}
|
||||
const couponResult = await this.validateCoupon(
|
||||
createOrderDto.couponCode,
|
||||
cartTotal,
|
||||
userId,
|
||||
);
|
||||
discountAmount = couponResult.discountAmount;
|
||||
couponId = couponResult.couponId;
|
||||
}
|
||||
|
||||
const charityAmount = Number(createOrderDto.charityDonation || 0);
|
||||
const finalAmount = Math.max(
|
||||
totalAmount - discountAmount + charityAmount,
|
||||
0,
|
||||
);
|
||||
const charityAmount = createOrderDto.charityDonation || 0;
|
||||
const finalAmount = Math.max(0, cartTotal - discountAmount) + charityAmount;
|
||||
|
||||
const trackingNumber = this.generateTrackingNumber();
|
||||
|
||||
// Deduct user wallet balance if payment method is wallet
|
||||
@@ -169,19 +159,7 @@ export class OrdersService {
|
||||
});
|
||||
}
|
||||
|
||||
// Increment user charity total if charity donation was added
|
||||
if (charityAmount > 0 && userId) {
|
||||
try {
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { charityDonationTotal: { increment: charityAmount } },
|
||||
});
|
||||
} catch {
|
||||
// Ignore if user not found or guest
|
||||
}
|
||||
}
|
||||
|
||||
return this.prisma.order.create({
|
||||
const createdOrder = await this.prisma.order.create({
|
||||
data: {
|
||||
userId,
|
||||
couponId,
|
||||
@@ -201,6 +179,54 @@ 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(() => {});
|
||||
}
|
||||
|
||||
return createdOrder;
|
||||
}
|
||||
|
||||
async updateStatus(orderId: string, status: string, trackingCode?: string) {
|
||||
const order = await this.prisma.order.findUnique({
|
||||
where: { id: orderId },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
throw new NotFoundException('سفارش یافت نشد');
|
||||
}
|
||||
|
||||
const updatedOrder = await this.prisma.order.update({
|
||||
where: { id: orderId },
|
||||
data: {
|
||||
status,
|
||||
...(trackingCode ? { trackingNumber: trackingCode } : {}),
|
||||
},
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
// Send Shipping SMS with Tracking Code
|
||||
const mobile = updatedOrder.user?.mobile;
|
||||
const trackingNum = updatedOrder.trackingNumber || trackingCode || '';
|
||||
if (status === 'shipped' && mobile && trackingCode) {
|
||||
this.smsService.sendShippingNotification(
|
||||
mobile,
|
||||
trackingNum,
|
||||
trackingCode,
|
||||
).catch(() => {});
|
||||
}
|
||||
|
||||
return updatedOrder;
|
||||
}
|
||||
|
||||
async findAllByUser(userId: string, filters: PaginationDto) {
|
||||
|
||||
@@ -2,9 +2,14 @@ import { Injectable, BadRequestException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { WholesaleApplyDto } from './dto/wholesale-apply.dto';
|
||||
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
|
||||
@Injectable()
|
||||
export class WholesaleService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private smsService: SmsService,
|
||||
) {}
|
||||
|
||||
async applyForWholesale(userId: string, dto: WholesaleApplyDto) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
@@ -18,6 +23,16 @@ 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(() => {});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
|
||||
Reference in new issue
Block a user