test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { SetMetadata } from "@nestjs/common";
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const ROLES_KEY = "roles";
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -1,15 +1,15 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsInt, Min, IsString, IsEnum } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsOptional, IsInt, Min, IsString, IsEnum } from "class-validator";
|
||||
import { Type } from "class-transformer";
|
||||
|
||||
export enum SortOrder {
|
||||
ASC = 'asc',
|
||||
DESC = 'desc',
|
||||
ASC = "asc",
|
||||
DESC = "desc",
|
||||
}
|
||||
|
||||
export class PaginationDto {
|
||||
@ApiPropertyOptional({
|
||||
description: 'شماره صفحه (شروع از ۱)',
|
||||
description: "شماره صفحه (شروع از ۱)",
|
||||
minimum: 1,
|
||||
default: 1,
|
||||
})
|
||||
@@ -20,7 +20,7 @@ export class PaginationDto {
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'تعداد آیتمها در هر صفحه',
|
||||
description: "تعداد آیتمها در هر صفحه",
|
||||
minimum: 1,
|
||||
default: 10,
|
||||
})
|
||||
@@ -31,15 +31,15 @@ export class PaginationDto {
|
||||
limit?: number = 10;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'فیلد برای مرتبسازی',
|
||||
default: 'createdAt',
|
||||
description: "فیلد برای مرتبسازی",
|
||||
default: "createdAt",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sortBy?: string = 'createdAt';
|
||||
sortBy?: string = "createdAt";
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'جهت مرتبسازی (asc/desc)',
|
||||
description: "جهت مرتبسازی (asc/desc)",
|
||||
enum: SortOrder,
|
||||
default: SortOrder.DESC,
|
||||
})
|
||||
@@ -47,7 +47,7 @@ export class PaginationDto {
|
||||
@IsEnum(SortOrder)
|
||||
sortOrder?: SortOrder = SortOrder.DESC;
|
||||
|
||||
@ApiPropertyOptional({ description: 'عبارت جستجو' })
|
||||
@ApiPropertyOptional({ description: "عبارت جستجو" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import {
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
validateSync,
|
||||
} from 'class-validator';
|
||||
} from "class-validator";
|
||||
|
||||
class EnvironmentVariables {
|
||||
@IsNotEmpty({ message: 'DATABASE_URL is required for database connection' })
|
||||
@IsNotEmpty({ message: "DATABASE_URL is required for database connection" })
|
||||
@IsString()
|
||||
DATABASE_URL: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
NODE_ENV?: string = 'development';
|
||||
NODE_ENV?: string = "development";
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
PORT?: string = '4001';
|
||||
PORT?: string = "4001";
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@@ -47,21 +47,21 @@ export function validateEnv(config: Record<string, unknown>) {
|
||||
|
||||
if (errors.length > 0) {
|
||||
const messages = errors
|
||||
.map((err) => Object.values(err.constraints || {}).join(', '))
|
||||
.join('; ');
|
||||
.map((err) => Object.values(err.constraints || {}).join(", "))
|
||||
.join("; ");
|
||||
throw new Error(`Environment Validation Error: ${messages}`);
|
||||
}
|
||||
|
||||
if (!validatedConfig.JWT_ACCESS_SECRET) {
|
||||
process.env.JWT_ACCESS_SECRET =
|
||||
process.env.JWT_SECRET ||
|
||||
'canina_secure_access_token_jwt_secret_production_2026';
|
||||
"canina_secure_access_token_jwt_secret_production_2026";
|
||||
validatedConfig.JWT_ACCESS_SECRET = process.env.JWT_ACCESS_SECRET;
|
||||
}
|
||||
|
||||
if (!validatedConfig.JWT_REFRESH_SECRET) {
|
||||
process.env.JWT_REFRESH_SECRET =
|
||||
'canina_secure_refresh_token_jwt_secret_production_2026';
|
||||
"canina_secure_refresh_token_jwt_secret_production_2026";
|
||||
validatedConfig.JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { ErrorDetailField } from '../schemas/error-response.schema';
|
||||
} from "@nestjs/common";
|
||||
import { Request, Response } from "express";
|
||||
import { ErrorDetailField } from "../schemas/error-response.schema";
|
||||
|
||||
@Catch()
|
||||
export class CustomHttpExceptionFilter implements ExceptionFilter {
|
||||
@@ -20,44 +20,44 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
|
||||
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let message =
|
||||
'خطای داخلی سرور رخ داده است. لطفاً بعداً تلاش کنید یا با پشتیبانی تماس بگیرید.';
|
||||
let code = 'INTERNAL_SERVER_ERROR';
|
||||
"خطای داخلی سرور رخ داده است. لطفاً بعداً تلاش کنید یا با پشتیبانی تماس بگیرید.";
|
||||
let code = "INTERNAL_SERVER_ERROR";
|
||||
let details: ErrorDetailField[] | Record<string, unknown> = {};
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const exceptionResponse = exception.getResponse();
|
||||
|
||||
if (typeof exceptionResponse === 'string') {
|
||||
if (typeof exceptionResponse === "string") {
|
||||
message = this.translateGenericMessage(exceptionResponse, status);
|
||||
code = this.deriveErrorCode(status, exceptionResponse);
|
||||
} else if (
|
||||
typeof exceptionResponse === 'object' &&
|
||||
typeof exceptionResponse === "object" &&
|
||||
exceptionResponse !== null
|
||||
) {
|
||||
const resObj = exceptionResponse as Record<string, unknown>;
|
||||
|
||||
// Handle class-validator validation array messages
|
||||
if (Array.isArray(resObj.message)) {
|
||||
message = 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.';
|
||||
code = 'INVALID_INPUT_DATA';
|
||||
message = "اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.";
|
||||
code = "INVALID_INPUT_DATA";
|
||||
details = (resObj.message as string[]).map((msg: string) => {
|
||||
const parts = msg.split(' ');
|
||||
const parts = msg.split(" ");
|
||||
return {
|
||||
field: parts[0] || 'general',
|
||||
field: parts[0] || "general",
|
||||
message: msg,
|
||||
};
|
||||
});
|
||||
} else {
|
||||
const rawMsg =
|
||||
typeof resObj.message === 'string'
|
||||
typeof resObj.message === "string"
|
||||
? resObj.message
|
||||
: exception.message;
|
||||
message = this.translateGenericMessage(rawMsg, status);
|
||||
const rawCode =
|
||||
typeof resObj.code === 'string' ? resObj.code : undefined;
|
||||
typeof resObj.code === "string" ? resObj.code : undefined;
|
||||
const rawError =
|
||||
typeof resObj.error === 'string' ? resObj.error : undefined;
|
||||
typeof resObj.error === "string" ? resObj.error : undefined;
|
||||
code = rawCode || this.deriveErrorCode(status, rawError);
|
||||
details = (resObj.details as Record<string, unknown>) || {};
|
||||
}
|
||||
@@ -67,8 +67,8 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
|
||||
`Unhandled Exception: ${exception.message}`,
|
||||
exception.stack,
|
||||
);
|
||||
message = 'خطای غیرمنتظره در پردازش درخواست رخ داد.';
|
||||
code = 'UNHANDLED_EXCEPTION';
|
||||
message = "خطای غیرمنتظره در پردازش درخواست رخ داد.";
|
||||
code = "UNHANDLED_EXCEPTION";
|
||||
}
|
||||
|
||||
const errorPayload = {
|
||||
@@ -88,53 +88,53 @@ export class CustomHttpExceptionFilter implements ExceptionFilter {
|
||||
}
|
||||
|
||||
private translateGenericMessage(msg: string, status: number): string {
|
||||
if (!msg) return 'خطای نامشخص رخ داده است.';
|
||||
if (!msg) return "خطای نامشخص رخ داده است.";
|
||||
|
||||
const lower = msg.toLowerCase();
|
||||
if (lower === 'unauthorized' || msg === 'Unauthorized') {
|
||||
return 'شما دسترسی لازم برای این عملیات را ندارید. لطفاً ابتدا وارد حساب کاربری خود شوید.';
|
||||
if (lower === "unauthorized" || msg === "Unauthorized") {
|
||||
return "شما دسترسی لازم برای این عملیات را ندارید. لطفاً ابتدا وارد حساب کاربری خود شوید.";
|
||||
}
|
||||
if (lower === 'forbidden' || msg === 'Forbidden') {
|
||||
return 'دسترسی شما به این بخش یا منبع محدود شده است.';
|
||||
if (lower === "forbidden" || msg === "Forbidden") {
|
||||
return "دسترسی شما به این بخش یا منبع محدود شده است.";
|
||||
}
|
||||
if (lower === 'not found' || msg === 'Not Found') {
|
||||
return 'مورد یا صفحه درخواستی یافت نشد.';
|
||||
if (lower === "not found" || msg === "Not Found") {
|
||||
return "مورد یا صفحه درخواستی یافت نشد.";
|
||||
}
|
||||
if (lower === 'bad request' || msg === 'Bad Request') {
|
||||
return 'درخواست نامعتبر است. لطفاً پارامترهای ورودی را چک کنید.';
|
||||
if (lower === "bad request" || msg === "Bad Request") {
|
||||
return "درخواست نامعتبر است. لطفاً پارامترهای ورودی را چک کنید.";
|
||||
}
|
||||
if (
|
||||
lower === 'too many requests' ||
|
||||
msg === 'ThrottlerException: Too Many Requests'
|
||||
lower === "too many requests" ||
|
||||
msg === "ThrottlerException: Too Many Requests"
|
||||
) {
|
||||
return 'تعداد درخواستهای شما بیش از حد مجاز است. لطفاً کمی صبر کرده و مجدداً تلاش کنید.';
|
||||
return "تعداد درخواستهای شما بیش از حد مجاز است. لطفاً کمی صبر کرده و مجدداً تلاش کنید.";
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
private deriveErrorCode(status: number, defaultError?: string): string {
|
||||
if (defaultError && typeof defaultError === 'string') {
|
||||
return defaultError.toUpperCase().replace(/\s+/g, '_');
|
||||
if (defaultError && typeof defaultError === "string") {
|
||||
return defaultError.toUpperCase().replace(/\s+/g, "_");
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
return 'BAD_REQUEST';
|
||||
return "BAD_REQUEST";
|
||||
case 401:
|
||||
return 'UNAUTHORIZED';
|
||||
return "UNAUTHORIZED";
|
||||
case 403:
|
||||
return 'FORBIDDEN';
|
||||
return "FORBIDDEN";
|
||||
case 404:
|
||||
return 'NOT_FOUND';
|
||||
return "NOT_FOUND";
|
||||
case 409:
|
||||
return 'CONFLICT';
|
||||
return "CONFLICT";
|
||||
case 422:
|
||||
return 'UNPROCESSABLE_ENTITY';
|
||||
return "UNPROCESSABLE_ENTITY";
|
||||
case 429:
|
||||
return 'TOO_MANY_REQUESTS';
|
||||
return "TOO_MANY_REQUESTS";
|
||||
default:
|
||||
return 'INTERNAL_SERVER_ERROR';
|
||||
return "INTERNAL_SERVER_ERROR";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
ArgumentsHost,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Request, Response } from 'express';
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
@Catch(Prisma.PrismaClientKnownRequestError)
|
||||
export class PrismaExceptionFilter implements ExceptionFilter {
|
||||
@@ -18,33 +18,33 @@ export class PrismaExceptionFilter implements ExceptionFilter {
|
||||
const request = ctx.getRequest<Request>();
|
||||
|
||||
let status = HttpStatus.BAD_REQUEST;
|
||||
let message = 'خطایی در پردازش اطلاعات دیتابیس رخ داده است.';
|
||||
let message = "خطایی در پردازش اطلاعات دیتابیس رخ داده است.";
|
||||
let code = `PRISMA_${exception.code}`;
|
||||
let details: Record<string, unknown> = {};
|
||||
|
||||
switch (exception.code) {
|
||||
case 'P2002': {
|
||||
case "P2002": {
|
||||
status = HttpStatus.CONFLICT;
|
||||
const target = (exception.meta?.target as string[]) || [];
|
||||
const fieldName = target.join(', ');
|
||||
const fieldName = target.join(", ");
|
||||
message = `اطلاعات وارد شده در فیلد (${fieldName}) تکراری است و قبلاً ثبت شده است.`;
|
||||
code = 'DUPLICATE_ENTRY';
|
||||
code = "DUPLICATE_ENTRY";
|
||||
details = { field: fieldName, meta: exception.meta };
|
||||
break;
|
||||
}
|
||||
case 'P2025': {
|
||||
case "P2025": {
|
||||
status = HttpStatus.NOT_FOUND;
|
||||
message =
|
||||
'اطلاعات یا رکورد مورد نظر در سیستم یافت نشد یا قبلاً حذف شده است.';
|
||||
code = 'RECORD_NOT_FOUND';
|
||||
"اطلاعات یا رکورد مورد نظر در سیستم یافت نشد یا قبلاً حذف شده است.";
|
||||
code = "RECORD_NOT_FOUND";
|
||||
details = { meta: exception.meta };
|
||||
break;
|
||||
}
|
||||
case 'P2003': {
|
||||
case "P2003": {
|
||||
status = HttpStatus.BAD_REQUEST;
|
||||
message =
|
||||
'امکان انجام عملیات به دلیل وجود وابستگی بین اطلاعات وجود ندارد.';
|
||||
code = 'FOREIGN_KEY_CONSTRAINT_FAILED';
|
||||
"امکان انجام عملیات به دلیل وجود وابستگی بین اطلاعات وجود ندارد.";
|
||||
code = "FOREIGN_KEY_CONSTRAINT_FAILED";
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
@@ -54,10 +54,10 @@ export class PrismaExceptionFilter implements ExceptionFilter {
|
||||
}
|
||||
}
|
||||
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
const isProd = process.env.NODE_ENV === "production";
|
||||
if (isProd && status === HttpStatus.INTERNAL_SERVER_ERROR) {
|
||||
message =
|
||||
'خطایی در پردازش اطلاعات پایگاه داده رخ داد. لطفاً بعداً تلاش فرمایید.';
|
||||
"خطایی در پردازش اطلاعات پایگاه داده رخ داد. لطفاً بعداً تلاش فرمایید.";
|
||||
details = {};
|
||||
} else if (isProd && details && (details as any).meta) {
|
||||
delete (details as any).meta;
|
||||
|
||||
@@ -3,64 +3,64 @@ import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class CsrfGuard implements CanActivate {
|
||||
private readonly stateChangingMethods = new Set([
|
||||
'POST',
|
||||
'PUT',
|
||||
'PATCH',
|
||||
'DELETE',
|
||||
"POST",
|
||||
"PUT",
|
||||
"PATCH",
|
||||
"DELETE",
|
||||
]);
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const method = (req.method || '').toUpperCase();
|
||||
const method = (req.method || "").toUpperCase();
|
||||
|
||||
// Safe / Read-only HTTP methods are not subject to CSRF
|
||||
if (!this.stateChangingMethods.has(method)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const path = req.originalUrl || req.url || '';
|
||||
const path = req.originalUrl || req.url || "";
|
||||
|
||||
// Webhooks & Payment Callbacks (e.g. Zibal gateway callback, MeliPayamak incoming webhooks)
|
||||
if (
|
||||
path.includes('/payment/callback') ||
|
||||
path.includes('/payment/verify') ||
|
||||
path.includes('/webhooks')
|
||||
path.includes("/payment/callback") ||
|
||||
path.includes("/payment/verify") ||
|
||||
path.includes("/webhooks")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1. Authorization Bearer Token requests are immune to standard cross-site browser CSRF
|
||||
const authHeader = req.headers['authorization'];
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const authHeader = req.headers["authorization"];
|
||||
if (authHeader && authHeader.startsWith("Bearer ")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Custom header verification (X-Requested-With or X-CSRF-Token)
|
||||
const customHeader =
|
||||
req.headers['x-requested-with'] ||
|
||||
req.headers['x-csrf-token'] ||
|
||||
req.headers['x-api-key'];
|
||||
req.headers["x-requested-with"] ||
|
||||
req.headers["x-csrf-token"] ||
|
||||
req.headers["x-api-key"];
|
||||
|
||||
if (customHeader) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. Same-origin Sec-Fetch-Site check (Modern Browsers Protection)
|
||||
const secFetchSite = req.headers['sec-fetch-site'];
|
||||
if (secFetchSite === 'same-origin' || secFetchSite === 'same-site') {
|
||||
const secFetchSite = req.headers["sec-fetch-site"];
|
||||
if (secFetchSite === "same-origin" || secFetchSite === "same-site") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If request has cookie credentials but lacks any anti-CSRF signature, block it
|
||||
if (req.headers.cookie) {
|
||||
throw new ForbiddenException(
|
||||
'درخواست مشکوک به حمله CSRF است. هدر اعتبارسنجی یافت نشد.',
|
||||
"درخواست مشکوک به حمله CSRF است. هدر اعتبارسنجی یافت نشد.",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
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';
|
||||
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', () => {
|
||||
describe("RolesGuard", () => {
|
||||
let guard: RolesGuard;
|
||||
let reflector: Reflector;
|
||||
|
||||
@@ -35,37 +35,37 @@ describe('RolesGuard', () => {
|
||||
} as any;
|
||||
};
|
||||
|
||||
it('should be defined', () => {
|
||||
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' });
|
||||
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']);
|
||||
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' });
|
||||
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' });
|
||||
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' });
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -3,9 +3,9 @@ import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
} from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { ROLES_KEY } from "../decorators/roles.decorator";
|
||||
|
||||
interface RequestWithUser {
|
||||
user?: {
|
||||
@@ -32,21 +32,21 @@ export class RolesGuard implements CanActivate {
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
if (!user || !user.role) {
|
||||
throw new ForbiddenException('شما دسترسی لازم برای این بخش را ندارید');
|
||||
throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید");
|
||||
}
|
||||
|
||||
// If request originates from an API key, verify it has admin scope for admin-guarded routes
|
||||
if (user.isApiKey) {
|
||||
const scopes = Array.isArray(user.scopes) ? user.scopes : [];
|
||||
const hasAdminScope = scopes.includes('admin');
|
||||
const hasAdminScope = scopes.includes("admin");
|
||||
if (!hasAdminScope) {
|
||||
throw new ForbiddenException(
|
||||
'کلید API ارائهشده فاقد اسکوپ مدیریتی لازم برای این عملیات است',
|
||||
"کلید API ارائهشده فاقد اسکوپ مدیریتی لازم برای این عملیات است",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, '');
|
||||
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, "");
|
||||
|
||||
const userRoleNorm = normalizeRole(user.role);
|
||||
const hasRole = requiredRoles.some((r) => {
|
||||
@@ -55,8 +55,8 @@ export class RolesGuard implements CanActivate {
|
||||
if (requiredNorm === userRoleNorm) return true;
|
||||
// Superadmin satisfies admin
|
||||
if (
|
||||
(userRoleNorm === 'superadmin' || userRoleNorm === 'adminsuper') &&
|
||||
requiredNorm === 'admin'
|
||||
(userRoleNorm === "superadmin" || userRoleNorm === "adminsuper") &&
|
||||
requiredNorm === "admin"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export class RolesGuard implements CanActivate {
|
||||
});
|
||||
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
|
||||
throw new ForbiddenException("سطح دسترسی شما کافی نیست");
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { DecimalInterceptor } from './decimal.interceptor';
|
||||
import { ExecutionContext, CallHandler } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { of } from 'rxjs';
|
||||
import { DecimalInterceptor } from "./decimal.interceptor";
|
||||
import { ExecutionContext, CallHandler } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { of } from "rxjs";
|
||||
|
||||
describe('DecimalInterceptor', () => {
|
||||
describe("DecimalInterceptor", () => {
|
||||
let interceptor: DecimalInterceptor;
|
||||
|
||||
beforeEach(() => {
|
||||
interceptor = new DecimalInterceptor();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
it("should be defined", () => {
|
||||
expect(interceptor).toBeDefined();
|
||||
});
|
||||
|
||||
it('should transform Prisma.Decimal instances to exact string representations', (done) => {
|
||||
it("should transform Prisma.Decimal instances to exact string representations", (done) => {
|
||||
const mockData = {
|
||||
id: 'order-1',
|
||||
totalAmount: new Prisma.Decimal('64.98'),
|
||||
id: "order-1",
|
||||
totalAmount: new Prisma.Decimal("64.98"),
|
||||
items: [
|
||||
{
|
||||
id: 'item-1',
|
||||
unitPrice: new Prisma.Decimal('32.49'),
|
||||
id: "item-1",
|
||||
unitPrice: new Prisma.Decimal("32.49"),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -33,12 +33,12 @@ describe('DecimalInterceptor', () => {
|
||||
|
||||
interceptor.intercept(executionContext, callHandler).subscribe((result) => {
|
||||
expect(result).toEqual({
|
||||
id: 'order-1',
|
||||
totalAmount: '64.98',
|
||||
id: "order-1",
|
||||
totalAmount: "64.98",
|
||||
items: [
|
||||
{
|
||||
id: 'item-1',
|
||||
unitPrice: '32.49',
|
||||
id: "item-1",
|
||||
unitPrice: "32.49",
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -46,12 +46,12 @@ describe('DecimalInterceptor', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should leave non-decimal values unchanged', (done) => {
|
||||
it("should leave non-decimal values unchanged", (done) => {
|
||||
const mockData = {
|
||||
name: 'Test',
|
||||
name: "Test",
|
||||
age: 5,
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
};
|
||||
|
||||
const executionContext = {} as ExecutionContext;
|
||||
|
||||
@@ -3,10 +3,10 @@ import {
|
||||
NestInterceptor,
|
||||
ExecutionContext,
|
||||
CallHandler,
|
||||
} from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Prisma } from '@prisma/client';
|
||||
} from "@nestjs/common";
|
||||
import { Observable } from "rxjs";
|
||||
import { map } from "rxjs/operators";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class DecimalInterceptor implements NestInterceptor {
|
||||
@@ -27,7 +27,7 @@ export class DecimalInterceptor implements NestInterceptor {
|
||||
return data.map((item: unknown) => this.transform(item));
|
||||
}
|
||||
|
||||
if (typeof data === 'object' && !(data instanceof Date)) {
|
||||
if (typeof data === "object" && !(data instanceof Date)) {
|
||||
const obj = data as Record<string, unknown>;
|
||||
const transformedObj: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(obj)) {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { MetricsController } from "./metrics.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import type { Response } from "express";
|
||||
|
||||
describe("MetricsController", () => {
|
||||
let controller: MetricsController;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrismaService = {
|
||||
$queryRaw: jest.fn(),
|
||||
};
|
||||
|
||||
const createMockResponse = () => {
|
||||
const res: Partial<Response> = {};
|
||||
res.set = jest.fn().mockReturnValue(res);
|
||||
res.end = jest.fn().mockReturnValue(res);
|
||||
return res as Response;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [MetricsController],
|
||||
providers: [
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: mockPrismaService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<MetricsController>(MetricsController);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
describe("incrementRequestCount", () => {
|
||||
it("should increment static requestCount", async () => {
|
||||
const res = createMockResponse();
|
||||
mockPrismaService.$queryRaw.mockResolvedValue([{ 1: 1 }]);
|
||||
|
||||
MetricsController.incrementRequestCount();
|
||||
|
||||
await controller.getMetrics(res);
|
||||
|
||||
expect(res.end).toHaveBeenCalledTimes(1);
|
||||
const output = (res.end as jest.Mock).mock.calls[0][0];
|
||||
expect(output).toContain("canino_http_requests_total");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMetrics", () => {
|
||||
it("should set headers and return prometheus metrics when db is healthy", async () => {
|
||||
const res = createMockResponse();
|
||||
mockPrismaService.$queryRaw.mockResolvedValue([{ 1: 1 }]);
|
||||
|
||||
await controller.getMetrics(res);
|
||||
|
||||
expect(prisma.$queryRaw).toHaveBeenCalled();
|
||||
expect(res.set).toHaveBeenCalledWith(
|
||||
"Content-Type",
|
||||
"text/plain; version=0.0.4; charset=utf-8",
|
||||
);
|
||||
expect(res.end).toHaveBeenCalledTimes(1);
|
||||
|
||||
const output = (res.end as jest.Mock).mock.calls[0][0];
|
||||
expect(output).toContain("# HELP node_memory_rss_bytes");
|
||||
expect(output).toContain("# HELP node_memory_heap_used_bytes");
|
||||
expect(output).toContain("# HELP node_memory_heap_total_bytes");
|
||||
expect(output).toContain("# HELP node_cpu_user_time_microseconds");
|
||||
expect(output).toContain("# HELP node_cpu_system_time_microseconds");
|
||||
expect(output).toContain("# HELP node_app_uptime_seconds");
|
||||
expect(output).toContain("# HELP canino_db_connected");
|
||||
expect(output).toContain("canino_db_connected 1");
|
||||
expect(output).toContain("# HELP canino_http_requests_total");
|
||||
});
|
||||
|
||||
it("should return canino_db_connected 0 when db query throws", async () => {
|
||||
const res = createMockResponse();
|
||||
mockPrismaService.$queryRaw.mockRejectedValue(
|
||||
new Error("DB Connection Timeout"),
|
||||
);
|
||||
|
||||
await controller.getMetrics(res);
|
||||
|
||||
expect(prisma.$queryRaw).toHaveBeenCalled();
|
||||
expect(res.set).toHaveBeenCalledWith(
|
||||
"Content-Type",
|
||||
"text/plain; version=0.0.4; charset=utf-8",
|
||||
);
|
||||
expect(res.end).toHaveBeenCalledTimes(1);
|
||||
|
||||
const output = (res.end as jest.Mock).mock.calls[0][0];
|
||||
expect(output).toContain("canino_db_connected 0");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,15 @@
|
||||
import { Controller, Get, Res, UseGuards } from '@nestjs/common';
|
||||
import { ApiExcludeController } from '@nestjs/swagger';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from './guards/roles.guard';
|
||||
import { Roles } from './decorators/roles.decorator';
|
||||
import type { Response } from 'express';
|
||||
import { Controller, Get, Res, UseGuards } from "@nestjs/common";
|
||||
import { ApiExcludeController } from "@nestjs/swagger";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "./guards/roles.guard";
|
||||
import { Roles } from "./decorators/roles.decorator";
|
||||
import type { Response } from "express";
|
||||
|
||||
@ApiExcludeController()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('metrics')
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("metrics")
|
||||
export class MetricsController {
|
||||
private static requestCount = 0;
|
||||
|
||||
@@ -66,7 +66,7 @@ canino_db_connected ${dbStatus}
|
||||
canino_http_requests_total ${MetricsController.requestCount}
|
||||
`;
|
||||
|
||||
res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
|
||||
res.set("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
|
||||
res.end(responseText);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { RevalidationService } from './revalidation.service';
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("RevalidationService", () => {
|
||||
let service: RevalidationService;
|
||||
const originalEnv = process.env;
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env = { ...originalEnv };
|
||||
process.env.REVALIDATION_SECRET = "test-secret-123";
|
||||
process.env.FRONTEND_INTERNAL_URL = "http://frontend_mock:8080";
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [RevalidationService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<RevalidationService>(RevalidationService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe("revalidateTag", () => {
|
||||
it("should send POST request with tag and secret header and return true on 200", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
} as any);
|
||||
|
||||
const result = await service.revalidateTag("products");
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
"x-revalidate-secret": "test-secret-123",
|
||||
}),
|
||||
body: JSON.stringify({ tag: "products", secret: "test-secret-123" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should return false if frontend responds with non-ok status", async () => {
|
||||
jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: "Internal Error",
|
||||
} as any);
|
||||
|
||||
const result = await service.revalidateTag("products");
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should catch network errors gracefully and return false", async () => {
|
||||
jest
|
||||
.spyOn(global, "fetch" as any)
|
||||
.mockRejectedValue(new Error("Connection refused"));
|
||||
|
||||
const result = await service.revalidateTag("products");
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidatePath", () => {
|
||||
it("should send POST request with path and secret and return true on success", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
} as any);
|
||||
|
||||
const result = await service.revalidatePath("/shop");
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ path: "/shop", secret: "test-secret-123" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidateProduct", () => {
|
||||
it("should trigger all tags and paths for product slug and artNo", async () => {
|
||||
const tagSpy = jest
|
||||
.spyOn(service, "revalidateTag")
|
||||
.mockResolvedValue(true);
|
||||
const pathSpy = jest
|
||||
.spyOn(service, "revalidatePath")
|
||||
.mockResolvedValue(true);
|
||||
|
||||
await service.revalidateProduct("canivita-tonic", "ART-100");
|
||||
|
||||
expect(tagSpy).toHaveBeenCalledWith("products");
|
||||
expect(tagSpy).toHaveBeenCalledWith("home-data");
|
||||
expect(tagSpy).toHaveBeenCalledWith("product-canivita-tonic");
|
||||
expect(tagSpy).toHaveBeenCalledWith("product-ART-100");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/canivita-tonic");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class RevalidationService {
|
||||
@@ -9,24 +9,24 @@ export class RevalidationService {
|
||||
process.env.FRONTEND_INTERNAL_URL ||
|
||||
process.env.FRONTEND_URL ||
|
||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||
(process.env.NODE_ENV === 'production'
|
||||
? 'http://frontend_prod:8080'
|
||||
: 'http://localhost:3000');
|
||||
return raw.replace(/\/+$/, '');
|
||||
(process.env.NODE_ENV === "production"
|
||||
? "http://frontend_prod:8080"
|
||||
: "http://localhost:3000");
|
||||
return raw.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
private get secret(): string {
|
||||
const secret = process.env.REVALIDATION_SECRET;
|
||||
if (!secret) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
throw new Error(
|
||||
'REVALIDATION_SECRET is required in production environment.',
|
||||
"REVALIDATION_SECRET is required in production environment.",
|
||||
);
|
||||
}
|
||||
this.logger.warn(
|
||||
'REVALIDATION_SECRET is not defined in environment variables.',
|
||||
"REVALIDATION_SECRET is not defined in environment variables.",
|
||||
);
|
||||
return '';
|
||||
return "";
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
@@ -35,10 +35,10 @@ export class RevalidationService {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-revalidate-secret': this.secret,
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tag, secret: this.secret }),
|
||||
});
|
||||
@@ -64,10 +64,10 @@ export class RevalidationService {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-revalidate-secret': this.secret,
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ path, secret: this.secret }),
|
||||
});
|
||||
@@ -91,10 +91,10 @@ export class RevalidationService {
|
||||
|
||||
async revalidateProduct(slug?: string, artNo?: string): Promise<void> {
|
||||
const tasks: Promise<boolean>[] = [
|
||||
this.revalidateTag('products'),
|
||||
this.revalidateTag('home-data'),
|
||||
this.revalidatePath('/shop'),
|
||||
this.revalidatePath('/'),
|
||||
this.revalidateTag("products"),
|
||||
this.revalidateTag("home-data"),
|
||||
this.revalidatePath("/shop"),
|
||||
this.revalidatePath("/"),
|
||||
];
|
||||
|
||||
if (slug) {
|
||||
@@ -111,11 +111,11 @@ export class RevalidationService {
|
||||
|
||||
async revalidateBlog(slug?: string): Promise<void> {
|
||||
const tasks: Promise<boolean>[] = [
|
||||
this.revalidateTag('blogs'),
|
||||
this.revalidateTag('home-data'),
|
||||
this.revalidatePath('/blog'),
|
||||
this.revalidatePath('/sitemap.xml'),
|
||||
this.revalidatePath('/'),
|
||||
this.revalidateTag("blogs"),
|
||||
this.revalidateTag("home-data"),
|
||||
this.revalidatePath("/blog"),
|
||||
this.revalidatePath("/sitemap.xml"),
|
||||
this.revalidatePath("/"),
|
||||
];
|
||||
|
||||
if (slug) {
|
||||
@@ -128,10 +128,10 @@ export class RevalidationService {
|
||||
|
||||
async revalidateSettings(): Promise<void> {
|
||||
await Promise.allSettled([
|
||||
this.revalidateTag('settings'),
|
||||
this.revalidateTag('home-data'),
|
||||
this.revalidateTag('seo-config'),
|
||||
this.revalidatePath('/'),
|
||||
this.revalidateTag("settings"),
|
||||
this.revalidateTag("home-data"),
|
||||
this.revalidateTag("seo-config"),
|
||||
this.revalidatePath("/"),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,55 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
|
||||
export class ErrorDetailField {
|
||||
@ApiProperty({ description: 'نام فیلد دارای خطا', example: 'phone' })
|
||||
@ApiProperty({ description: "نام فیلد دارای خطا", example: "phone" })
|
||||
field: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'توضیح توصیفی خطا به فارسی',
|
||||
example: 'شماره تلفن همراه وارد شده نامعتبر است.',
|
||||
description: "توضیح توصیفی خطا به فارسی",
|
||||
example: "شماره تلفن همراه وارد شده نامعتبر است.",
|
||||
})
|
||||
message: string;
|
||||
}
|
||||
|
||||
export class ApiErrorResponse {
|
||||
@ApiProperty({
|
||||
description: 'وضعیت موفقیت درخواست (همیشه false در زمان خطا)',
|
||||
description: "وضعیت موفقیت درخواست (همیشه false در زمان خطا)",
|
||||
example: false,
|
||||
})
|
||||
success: boolean;
|
||||
|
||||
@ApiProperty({ description: 'کد وضعیت HTTP درخواست', example: 400 })
|
||||
@ApiProperty({ description: "کد وضعیت HTTP درخواست", example: 400 })
|
||||
statusCode: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'پیام جامع و توصیفی خطا به زبان فارسی',
|
||||
description: "پیام جامع و توصیفی خطا به زبان فارسی",
|
||||
example:
|
||||
'اطلاعات وارد شده نامعتبر است. لطفاً موارد مشخص شده را بررسی نمایید.',
|
||||
"اطلاعات وارد شده نامعتبر است. لطفاً موارد مشخص شده را بررسی نمایید.",
|
||||
})
|
||||
message: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'کد سیستمیک و ثابت خطا جهت پردازش فرانتاند',
|
||||
example: 'INVALID_INPUT_DATA',
|
||||
description: "کد سیستمیک و ثابت خطا جهت پردازش فرانتاند",
|
||||
example: "INVALID_INPUT_DATA",
|
||||
})
|
||||
code: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'جزئیات فیلدها و خطاهای اعتبارسنجی (در صورت وجود)',
|
||||
description: "جزئیات فیلدها و خطاهای اعتبارسنجی (در صورت وجود)",
|
||||
required: false,
|
||||
type: [ErrorDetailField],
|
||||
})
|
||||
details?: ErrorDetailField[] | Record<string, any>;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'زمان وقوع خطا به فرمت ISO',
|
||||
example: '2026-07-29T16:30:00.000Z',
|
||||
description: "زمان وقوع خطا به فرمت ISO",
|
||||
example: "2026-07-29T16:30:00.000Z",
|
||||
})
|
||||
timestamp: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'مسیر و انکوینتی که خطا در آن رخ داده است',
|
||||
example: '/api/auth/register',
|
||||
description: "مسیر و انکوینتی که خطا در آن رخ داده است",
|
||||
example: "/api/auth/register",
|
||||
})
|
||||
path: string;
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
|
||||
export class PaginationMeta {
|
||||
@ApiProperty({ description: 'تعداد کل آیتمها', example: 100 })
|
||||
@ApiProperty({ description: "تعداد کل آیتمها", example: 100 })
|
||||
total: number;
|
||||
|
||||
@ApiProperty({ description: 'شماره صفحه فعلی', example: 1 })
|
||||
@ApiProperty({ description: "شماره صفحه فعلی", example: 1 })
|
||||
page: number;
|
||||
|
||||
@ApiProperty({ description: 'تعداد کل صفحات', example: 10 })
|
||||
@ApiProperty({ description: "تعداد کل صفحات", example: 10 })
|
||||
lastPage: number;
|
||||
|
||||
@ApiProperty({ description: 'تعداد آیتمها در هر صفحه', example: 10 })
|
||||
@ApiProperty({ description: "تعداد آیتمها در هر صفحه", example: 10 })
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export class PaginatedResponse<T> {
|
||||
@ApiProperty({ description: 'آرایه آیتمها' })
|
||||
@ApiProperty({ description: "آرایه آیتمها" })
|
||||
data: T[];
|
||||
|
||||
@ApiProperty({ description: 'اطلاعات صفحهبندی' })
|
||||
@ApiProperty({ description: "اطلاعات صفحهبندی" })
|
||||
meta: PaginationMeta;
|
||||
}
|
||||
|
||||
@@ -29,11 +29,11 @@ export function createPaginatedSchema(dtoModel: { name: string }) {
|
||||
{
|
||||
properties: {
|
||||
data: {
|
||||
type: 'array',
|
||||
type: "array",
|
||||
items: { $ref: `#/components/schemas/${dtoModel.name}` },
|
||||
},
|
||||
meta: {
|
||||
$ref: '#/components/schemas/PaginationMeta',
|
||||
$ref: "#/components/schemas/PaginationMeta",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@ export interface SmsRule {
|
||||
title: string;
|
||||
event: string; // ORDER_PAID, ORDER_CREATED, ORDER_SHIPPED, B2B_SUBMITTED, CONTACT_SUBMITTED, OTP
|
||||
enabled: boolean;
|
||||
recipientType: 'customer' | 'admin' | 'custom';
|
||||
recipientType: "customer" | "admin" | "custom";
|
||||
customPhone?: string;
|
||||
patternId: number;
|
||||
variables: string[]; // Ordered parameter keys: e.g. ['orderNumber', 'recipientName', 'address']
|
||||
@@ -25,249 +25,249 @@ export interface SmsEventDefinition {
|
||||
|
||||
export const SMS_EVENT_DEFINITIONS: SmsEventDefinition[] = [
|
||||
{
|
||||
event: 'ORDER_PAID',
|
||||
label: 'پرداخت موفق سفارش (Order Paid)',
|
||||
event: "ORDER_PAID",
|
||||
label: "پرداخت موفق سفارش (Order Paid)",
|
||||
description:
|
||||
'هنگام پرداخت موفق آنلاین در درگاه بانکی یا تسویه حساب از طریق کیف پول',
|
||||
"هنگام پرداخت موفق آنلاین در درگاه بانکی یا تسویه حساب از طریق کیف پول",
|
||||
variables: [
|
||||
{
|
||||
key: 'orderNumber',
|
||||
label: 'شماره سفارش / فاکتور',
|
||||
sample: 'CN-140308-01',
|
||||
key: "orderNumber",
|
||||
label: "شماره سفارش / فاکتور",
|
||||
sample: "CN-140308-01",
|
||||
},
|
||||
{ key: 'amount', label: 'مبلغ پرداختی (تومان)', sample: '۱,۴۵۰,۰۰۰' },
|
||||
{ key: 'customerName', label: 'نام خریدار', sample: 'علی محمدی' },
|
||||
{ key: "amount", label: "مبلغ پرداختی (تومان)", sample: "۱,۴۵۰,۰۰۰" },
|
||||
{ key: "customerName", label: "نام خریدار", sample: "علی محمدی" },
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره موبایل خریدار',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره موبایل خریدار",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'recipientName', label: 'نام تحویلگیرنده', sample: 'رضا حسینی' },
|
||||
{ key: "recipientName", label: "نام تحویلگیرنده", sample: "رضا حسینی" },
|
||||
{
|
||||
key: 'recipientPhone',
|
||||
label: 'تلفن تماس تحویلگیرنده',
|
||||
sample: '09351234567',
|
||||
key: "recipientPhone",
|
||||
label: "تلفن تماس تحویلگیرنده",
|
||||
sample: "09351234567",
|
||||
},
|
||||
{
|
||||
key: 'provinceCity',
|
||||
label: 'استان و شهر مقصد',
|
||||
sample: 'تهران - تهران',
|
||||
key: "provinceCity",
|
||||
label: "استان و شهر مقصد",
|
||||
sample: "تهران - تهران",
|
||||
},
|
||||
{ key: 'postalCode', label: 'کد پستی ۱۰ رقمی', sample: '1967812345' },
|
||||
{ key: "postalCode", label: "کد پستی ۱۰ رقمی", sample: "1967812345" },
|
||||
{
|
||||
key: 'address',
|
||||
label: 'نشانی کامل پستی',
|
||||
sample: 'خیابان ولیعصر، کوچه بهار، پلاک ۴',
|
||||
key: "address",
|
||||
label: "نشانی کامل پستی",
|
||||
sample: "خیابان ولیعصر، کوچه بهار، پلاک ۴",
|
||||
},
|
||||
{
|
||||
key: 'itemsSummary',
|
||||
label: 'خلاصه اقلام سفارش',
|
||||
sample: 'شیر خشک توله سگ (۲)',
|
||||
key: "itemsSummary",
|
||||
label: "خلاصه اقلام سفارش",
|
||||
sample: "شیر خشک توله سگ (۲)",
|
||||
},
|
||||
{ key: 'itemCount', label: 'تعداد کل اقلام', sample: '۲' },
|
||||
{ key: 'paymentMethod', label: 'روش پرداخت', sample: 'آنلاین' },
|
||||
{ key: 'orderDate', label: 'تاریخ ثبت سفارش', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "itemCount", label: "تعداد کل اقلام", sample: "۲" },
|
||||
{ key: "paymentMethod", label: "روش پرداخت", sample: "آنلاین" },
|
||||
{ key: "orderDate", label: "تاریخ ثبت سفارش", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
{
|
||||
key: 'refNumber',
|
||||
label: 'شماره پیگیری پرداخت بانکی',
|
||||
sample: '83920192',
|
||||
key: "refNumber",
|
||||
label: "شماره پیگیری پرداخت بانکی",
|
||||
sample: "83920192",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'ORDER_CREATED',
|
||||
label: 'ثبت سفارش کارت به کارت یا غیرآنلاین',
|
||||
event: "ORDER_CREATED",
|
||||
label: "ثبت سفارش کارت به کارت یا غیرآنلاین",
|
||||
description:
|
||||
'هنگامی که سفارش با روش کارت به کارت در انتظار پرداخت ثبت میشود',
|
||||
"هنگامی که سفارش با روش کارت به کارت در انتظار پرداخت ثبت میشود",
|
||||
variables: [
|
||||
{
|
||||
key: 'orderNumber',
|
||||
label: 'شماره سفارش / فاکتور',
|
||||
sample: 'CN-140308-01',
|
||||
key: "orderNumber",
|
||||
label: "شماره سفارش / فاکتور",
|
||||
sample: "CN-140308-01",
|
||||
},
|
||||
{ key: 'amount', label: 'مبلغ کل سفارش', sample: '۱,۴۵۰,۰۰۰' },
|
||||
{ key: 'customerName', label: 'نام خریدار', sample: 'علی محمدی' },
|
||||
{ key: "amount", label: "مبلغ کل سفارش", sample: "۱,۴۵۰,۰۰۰" },
|
||||
{ key: "customerName", label: "نام خریدار", sample: "علی محمدی" },
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره موبایل خریدار',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره موبایل خریدار",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'recipientName', label: 'نام تحویلگیرنده', sample: 'رضا حسینی' },
|
||||
{ key: "recipientName", label: "نام تحویلگیرنده", sample: "رضا حسینی" },
|
||||
{
|
||||
key: 'recipientPhone',
|
||||
label: 'تلفن تحویلگیرنده',
|
||||
sample: '09351234567',
|
||||
key: "recipientPhone",
|
||||
label: "تلفن تحویلگیرنده",
|
||||
sample: "09351234567",
|
||||
},
|
||||
{
|
||||
key: 'provinceCity',
|
||||
label: 'استان و شهر مقصد',
|
||||
sample: 'تهران - تهران',
|
||||
key: "provinceCity",
|
||||
label: "استان و شهر مقصد",
|
||||
sample: "تهران - تهران",
|
||||
},
|
||||
{ key: 'postalCode', label: 'کد پستی ۱۰ رقمی', sample: '1967812345' },
|
||||
{ key: "postalCode", label: "کد پستی ۱۰ رقمی", sample: "1967812345" },
|
||||
{
|
||||
key: 'address',
|
||||
label: 'نشانی پستی',
|
||||
sample: 'خیابان ولیعصر، کوچه بهار، پلاک ۴',
|
||||
key: "address",
|
||||
label: "نشانی پستی",
|
||||
sample: "خیابان ولیعصر، کوچه بهار، پلاک ۴",
|
||||
},
|
||||
{
|
||||
key: 'itemsSummary',
|
||||
label: 'خلاصه اقلام سفارش',
|
||||
sample: 'شیر خشک توله سگ (۲)',
|
||||
key: "itemsSummary",
|
||||
label: "خلاصه اقلام سفارش",
|
||||
sample: "شیر خشک توله سگ (۲)",
|
||||
},
|
||||
{ key: 'itemCount', label: 'تعداد کل اقلام', sample: '۲' },
|
||||
{ key: 'paymentMethod', label: 'روش پرداخت', sample: 'کارت به کارت' },
|
||||
{ key: 'orderDate', label: 'تاریخ ثبت سفارش', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "itemCount", label: "تعداد کل اقلام", sample: "۲" },
|
||||
{ key: "paymentMethod", label: "روش پرداخت", sample: "کارت به کارت" },
|
||||
{ key: "orderDate", label: "تاریخ ثبت سفارش", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'ORDER_SHIPPED',
|
||||
label: 'ارسال مرسوله و صدور بارکد پست',
|
||||
description: 'هنگام تغییر وضعیت سفارش به ارسال شده یا درج کد رهگیری پستی',
|
||||
event: "ORDER_SHIPPED",
|
||||
label: "ارسال مرسوله و صدور بارکد پست",
|
||||
description: "هنگام تغییر وضعیت سفارش به ارسال شده یا درج کد رهگیری پستی",
|
||||
variables: [
|
||||
{ key: 'orderNumber', label: 'شماره سفارش', sample: 'CN-140308-01' },
|
||||
{ key: "orderNumber", label: "شماره سفارش", sample: "CN-140308-01" },
|
||||
{
|
||||
key: 'shippingTrackingCode',
|
||||
label: 'کد رهگیری ۲۴ رقمی پست',
|
||||
sample: '184920394857283948571928',
|
||||
key: "shippingTrackingCode",
|
||||
label: "کد رهگیری ۲۴ رقمی پست",
|
||||
sample: "184920394857283948571928",
|
||||
},
|
||||
{
|
||||
key: 'trackingCode',
|
||||
label: 'کد رهگیری پستی (مترادف)',
|
||||
sample: '184920394857283948571928',
|
||||
key: "trackingCode",
|
||||
label: "کد رهگیری پستی (مترادف)",
|
||||
sample: "184920394857283948571928",
|
||||
},
|
||||
{ key: 'customerName', label: 'نام خریدار', sample: 'علی محمدی' },
|
||||
{ key: 'recipientName', label: 'نام تحویلگیرنده', sample: 'رضا حسینی' },
|
||||
{ key: "customerName", label: "نام خریدار", sample: "علی محمدی" },
|
||||
{ key: "recipientName", label: "نام تحویلگیرنده", sample: "رضا حسینی" },
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره همراه مشتری',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره همراه مشتری",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'shippingMethod', label: 'روش ارسال', sample: 'پست پیشتاز' },
|
||||
{ key: "shippingMethod", label: "روش ارسال", sample: "پست پیشتاز" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'B2B_SUBMITTED',
|
||||
label: 'درخواست همکاری و عمدهفروشی B2B',
|
||||
description: 'هنگام ارسال فرم همکاری همکاران و کلینیکهای دامپزشکی',
|
||||
event: "B2B_SUBMITTED",
|
||||
label: "درخواست همکاری و عمدهفروشی B2B",
|
||||
description: "هنگام ارسال فرم همکاری همکاران و کلینیکهای دامپزشکی",
|
||||
variables: [
|
||||
{
|
||||
key: 'applicantName',
|
||||
label: 'نام متقاضی / فروشگاه',
|
||||
sample: 'پتشاپ آلفا',
|
||||
key: "applicantName",
|
||||
label: "نام متقاضی / فروشگاه",
|
||||
sample: "پتشاپ آلفا",
|
||||
},
|
||||
{
|
||||
key: 'applicantPhone',
|
||||
label: 'شماره همراه متقاضی',
|
||||
sample: '09123456789',
|
||||
key: "applicantPhone",
|
||||
label: "شماره همراه متقاضی",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{
|
||||
key: 'companyName',
|
||||
label: 'نام شرکت یا مجموعه',
|
||||
sample: 'فروشگاه آلفا',
|
||||
key: "companyName",
|
||||
label: "نام شرکت یا مجموعه",
|
||||
sample: "فروشگاه آلفا",
|
||||
},
|
||||
{ key: 'businessType', label: 'نوع فعالیت', sample: 'پتشاپ' },
|
||||
{ key: 'date', label: 'تاریخ ثبت درخواست', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "businessType", label: "نوع فعالیت", sample: "پتشاپ" },
|
||||
{ key: "date", label: "تاریخ ثبت درخواست", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'CONTACT_SUBMITTED',
|
||||
label: 'ثبت پیام در فرم تماس با ما',
|
||||
description: 'هنگامی که کاربری در فرم تماس پیامی ارسال میکند',
|
||||
event: "CONTACT_SUBMITTED",
|
||||
label: "ثبت پیام در فرم تماس با ما",
|
||||
description: "هنگامی که کاربری در فرم تماس پیامی ارسال میکند",
|
||||
variables: [
|
||||
{ key: 'senderName', label: 'نام فرستنده پیام', sample: 'سارا احمدی' },
|
||||
{ key: "senderName", label: "نام فرستنده پیام", sample: "سارا احمدی" },
|
||||
{
|
||||
key: 'senderPhone',
|
||||
label: 'شماره همراه فرستنده',
|
||||
sample: '09123456789',
|
||||
key: "senderPhone",
|
||||
label: "شماره همراه فرستنده",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'email', label: 'ایمیل فرستنده', sample: 'user@example.com' },
|
||||
{ key: 'subject', label: 'موضوع پیام', sample: 'مشاوره خرید مکمل' },
|
||||
{ key: "email", label: "ایمیل فرستنده", sample: "user@example.com" },
|
||||
{ key: "subject", label: "موضوع پیام", sample: "مشاوره خرید مکمل" },
|
||||
{
|
||||
key: 'message',
|
||||
label: 'متن پیام',
|
||||
sample: 'درخواست راهنمایی در مورد دوز کلسیم',
|
||||
key: "message",
|
||||
label: "متن پیام",
|
||||
sample: "درخواست راهنمایی در مورد دوز کلسیم",
|
||||
},
|
||||
{ key: 'date', label: 'تاریخ ارسال', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "date", label: "تاریخ ارسال", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'WALLET_CHARGED',
|
||||
label: 'شارژ و افزایش موجودی کیف پول',
|
||||
event: "WALLET_CHARGED",
|
||||
label: "شارژ و افزایش موجودی کیف پول",
|
||||
description:
|
||||
'هنگام افزایش موجودی کیف پول کاربر (درگاه آنلاین، پنل مدیریت، کشبک یا استرداد)',
|
||||
"هنگام افزایش موجودی کیف پول کاربر (درگاه آنلاین، پنل مدیریت، کشبک یا استرداد)",
|
||||
variables: [
|
||||
{ key: 'customerName', label: 'نام مشتری', sample: 'علی محمدی' },
|
||||
{ key: 'amount', label: 'مبلغ شارژ (تومان)', sample: '۵۰,۰۰۰' },
|
||||
{ key: "customerName", label: "نام مشتری", sample: "علی محمدی" },
|
||||
{ key: "amount", label: "مبلغ شارژ (تومان)", sample: "۵۰,۰۰۰" },
|
||||
{
|
||||
key: 'balance',
|
||||
label: 'موجودی جدید کیف پول (تومان)',
|
||||
sample: '۱۵۰,۰۰۰',
|
||||
key: "balance",
|
||||
label: "موجودی جدید کیف پول (تومان)",
|
||||
sample: "۱۵۰,۰۰۰",
|
||||
},
|
||||
{
|
||||
key: 'reason',
|
||||
label: 'علت / نوع شارژ',
|
||||
sample: 'شارژ آنلاین / پاداش خرید (Cashback)',
|
||||
key: "reason",
|
||||
label: "علت / نوع شارژ",
|
||||
sample: "شارژ آنلاین / پاداش خرید (Cashback)",
|
||||
},
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره همراه مشتری',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره همراه مشتری",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'date', label: 'تاریخ شارژ', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "date", label: "تاریخ شارژ", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const DEFAULT_SMS_RULES: SmsRule[] = [
|
||||
{
|
||||
id: 'default-order-customer',
|
||||
title: 'ارسال فاکتور و تایید سفارش به خریدار',
|
||||
event: 'ORDER_PAID',
|
||||
id: "default-order-customer",
|
||||
title: "ارسال فاکتور و تایید سفارش به خریدار",
|
||||
event: "ORDER_PAID",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 508081,
|
||||
variables: ['customerName', 'orderNumber', 'amount'],
|
||||
variables: ["customerName", "orderNumber", "amount"],
|
||||
description:
|
||||
'ارسال شماره فاکتور و مبلغ سفارش به شماره همراه مشتری بلافاصله پس از پرداخت',
|
||||
"ارسال شماره فاکتور و مبلغ سفارش به شماره همراه مشتری بلافاصله پس از پرداخت",
|
||||
},
|
||||
{
|
||||
id: 'default-order-admin',
|
||||
title: 'اطلاعرسانی سفارش جدید به مدیر سایت',
|
||||
event: 'ORDER_PAID',
|
||||
id: "default-order-admin",
|
||||
title: "اطلاعرسانی سفارش جدید به مدیر سایت",
|
||||
event: "ORDER_PAID",
|
||||
enabled: true,
|
||||
recipientType: 'admin',
|
||||
recipientType: "admin",
|
||||
patternId: 508081,
|
||||
variables: ['customerName', 'orderNumber', 'amount'],
|
||||
description: 'ارسال پیامک سفارش جدید و مبلغ به مدیران فروشگاه',
|
||||
variables: ["customerName", "orderNumber", "amount"],
|
||||
description: "ارسال پیامک سفارش جدید و مبلغ به مدیران فروشگاه",
|
||||
},
|
||||
{
|
||||
id: 'default-shipping-customer',
|
||||
title: 'ارسال کد رهگیری پست به خریدار',
|
||||
event: 'ORDER_SHIPPED',
|
||||
id: "default-shipping-customer",
|
||||
title: "ارسال کد رهگیری پست به خریدار",
|
||||
event: "ORDER_SHIPPED",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 508082,
|
||||
variables: ['orderNumber', 'shippingTrackingCode'],
|
||||
description: 'ارسال بارکد ۲۴ رقمی اداره پست هنگام تحویل مرسوله',
|
||||
variables: ["orderNumber", "shippingTrackingCode"],
|
||||
description: "ارسال بارکد ۲۴ رقمی اداره پست هنگام تحویل مرسوله",
|
||||
},
|
||||
{
|
||||
id: 'default-b2b-customer',
|
||||
title: 'تایید ثبت درخواست همکاری B2B',
|
||||
event: 'B2B_SUBMITTED',
|
||||
id: "default-b2b-customer",
|
||||
title: "تایید ثبت درخواست همکاری B2B",
|
||||
event: "B2B_SUBMITTED",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 508083,
|
||||
variables: ['applicantName'],
|
||||
description: 'پیامک ثبت درخواست متقاضیان عمدهفروشی',
|
||||
variables: ["applicantName"],
|
||||
description: "پیامک ثبت درخواست متقاضیان عمدهفروشی",
|
||||
},
|
||||
{
|
||||
id: 'default-wallet-charged-customer',
|
||||
title: 'اطلاعرسانی شارژ کیف پول به کاربر',
|
||||
event: 'WALLET_CHARGED',
|
||||
id: "default-wallet-charged-customer",
|
||||
title: "اطلاعرسانی شارژ کیف پول به کاربر",
|
||||
event: "WALLET_CHARGED",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 0,
|
||||
variables: ['customerName', 'amount', 'balance'],
|
||||
description: 'ارسال پیامک افزایش موجودی کیف پول (آنلاین، مدیریت یا کشبک)',
|
||||
variables: ["customerName", "amount", "balance"],
|
||||
description: "ارسال پیامک افزایش موجودی کیف پول (آنلاین، مدیریت یا کشبک)",
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { SmsService } from "./sms.service";
|
||||
import { PrismaService } from "../../prisma/prisma.service";
|
||||
|
||||
describe("SmsService", () => {
|
||||
let service: SmsService;
|
||||
|
||||
const mockPrisma = {
|
||||
setting: {
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
smsLog: {
|
||||
create: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [SmsService, { provide: PrismaService, useValue: mockPrisma }],
|
||||
}).compile();
|
||||
|
||||
service = module.get<SmsService>(SmsService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe("getSmsConfig", () => {
|
||||
it("should return configuration from database when available", async () => {
|
||||
mockPrisma.setting.findFirst.mockResolvedValue({
|
||||
category: "sms",
|
||||
value: {
|
||||
enabled: true,
|
||||
username: "custom_user",
|
||||
otpBodyId: 99999,
|
||||
},
|
||||
});
|
||||
|
||||
const config = await service.getSmsConfig();
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.username).toBe("custom_user");
|
||||
expect(config.otpBodyId).toBe(99999);
|
||||
});
|
||||
|
||||
it("should fallback gracefully to defaults if database query fails", async () => {
|
||||
mockPrisma.setting.findFirst.mockRejectedValue(new Error("DB error"));
|
||||
|
||||
const config = await service.getSmsConfig();
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.otpBodyId).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("triggerEvent", () => {
|
||||
it("should skip sending if SMS gateway is disabled in config", async () => {
|
||||
mockPrisma.setting.findFirst.mockResolvedValue({
|
||||
category: "sms",
|
||||
value: { enabled: false },
|
||||
});
|
||||
|
||||
const res = await service.triggerEvent("ORDER_PAID", {
|
||||
orderNumber: "123",
|
||||
});
|
||||
expect(res).toBe(false);
|
||||
});
|
||||
|
||||
it("should execute configured SMS rule and invoke sendPatternSms", async () => {
|
||||
mockPrisma.setting.findFirst.mockResolvedValue({
|
||||
category: "sms",
|
||||
value: {
|
||||
enabled: true,
|
||||
rules: [
|
||||
{
|
||||
id: "rule-1",
|
||||
title: "پیامک پرداخت به مشتری",
|
||||
event: "ORDER_PAID",
|
||||
enabled: true,
|
||||
recipientType: "customer",
|
||||
patternId: 508081,
|
||||
variables: ["orderNumber", "customerName"],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const sendPatternSpy = jest
|
||||
.spyOn(service, "sendPatternSms")
|
||||
.mockResolvedValue({ Value: 100 } as any);
|
||||
|
||||
const res = await service.triggerEvent("ORDER_PAID", {
|
||||
orderNumber: "ORD-999",
|
||||
customerName: "پارسا",
|
||||
customerPhone: "09121111111",
|
||||
});
|
||||
|
||||
expect(res).toBe(true);
|
||||
expect(sendPatternSpy).toHaveBeenCalledWith({
|
||||
to: "09121111111",
|
||||
bodyId: 508081,
|
||||
args: ["ORD-999", "پارسا"],
|
||||
type: "ORDER_PAID_CUSTOMER",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as https from 'https';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import * as https from "https";
|
||||
import { PrismaService } from "../../prisma/prisma.service";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
DEFAULT_SMS_RULES,
|
||||
SMS_EVENT_DEFINITIONS,
|
||||
SmsEventDefinition,
|
||||
} from './sms-events.constants';
|
||||
} from "./sms-events.constants";
|
||||
|
||||
export interface SendPatternSmsOptions {
|
||||
to: string;
|
||||
@@ -20,7 +20,7 @@ export interface SmsRule {
|
||||
title: string;
|
||||
event: string; // ORDER_PAID, ORDER_CREATED, ORDER_SHIPPED, B2B_SUBMITTED, CONTACT_SUBMITTED, OTP
|
||||
enabled: boolean;
|
||||
recipientType: 'customer' | 'admin' | 'custom';
|
||||
recipientType: "customer" | "admin" | "custom";
|
||||
customPhone?: string;
|
||||
patternId: number;
|
||||
variables: string[]; // Ordered parameter keys: e.g. ['orderNumber', 'recipientName', 'address']
|
||||
@@ -57,7 +57,7 @@ export class SmsLogQuery {
|
||||
type?: string;
|
||||
status?: string;
|
||||
sortBy?: string;
|
||||
sortOrder?: 'asc' | 'desc';
|
||||
sortOrder?: "asc" | "desc";
|
||||
}
|
||||
|
||||
export interface MeliPayamakResponse {
|
||||
@@ -78,7 +78,7 @@ export class SmsService {
|
||||
async getSmsConfig(): Promise<SmsConfig> {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms' },
|
||||
where: { category: "sms" },
|
||||
});
|
||||
const dbConfig = (setting?.value as Record<string, unknown>) || {};
|
||||
|
||||
@@ -86,41 +86,41 @@ export class SmsService {
|
||||
enabled:
|
||||
dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||
username:
|
||||
typeof dbConfig.username === 'string' && dbConfig.username
|
||||
typeof dbConfig.username === "string" && dbConfig.username
|
||||
? dbConfig.username
|
||||
: process.env.MELIPAYAMAK_USERNAME || '9364100228',
|
||||
: process.env.MELIPAYAMAK_USERNAME || "9364100228",
|
||||
password:
|
||||
typeof dbConfig.password === 'string' && dbConfig.password
|
||||
typeof dbConfig.password === "string" && dbConfig.password
|
||||
? dbConfig.password
|
||||
: process.env.MELIPAYAMAK_PASSWORD || '',
|
||||
: process.env.MELIPAYAMAK_PASSWORD || "",
|
||||
fromNumber:
|
||||
typeof dbConfig.fromNumber === 'string' && dbConfig.fromNumber
|
||||
typeof dbConfig.fromNumber === "string" && dbConfig.fromNumber
|
||||
? dbConfig.fromNumber
|
||||
: process.env.MELIPAYAMAK_FROM_NUMBER || '',
|
||||
: process.env.MELIPAYAMAK_FROM_NUMBER || "",
|
||||
adminPhone:
|
||||
typeof dbConfig.adminPhone === 'string' && dbConfig.adminPhone
|
||||
typeof dbConfig.adminPhone === "string" && dbConfig.adminPhone
|
||||
? dbConfig.adminPhone
|
||||
: process.env.ADMIN_MOBILE || '09364100228',
|
||||
: process.env.ADMIN_MOBILE || "09364100228",
|
||||
otpBodyId: Number(
|
||||
dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || '508079',
|
||||
dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || "508079",
|
||||
),
|
||||
orderBodyId: Number(
|
||||
dbConfig.orderBodyId ||
|
||||
process.env.MELIPAYAMAK_ORDER_BODY_ID ||
|
||||
'508081',
|
||||
"508081",
|
||||
),
|
||||
shippingBodyId: Number(
|
||||
dbConfig.shippingBodyId ||
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID ||
|
||||
'508082',
|
||||
"508082",
|
||||
),
|
||||
b2bBodyId: Number(
|
||||
dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || '508083',
|
||||
dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || "508083",
|
||||
),
|
||||
petCareBodyId: Number(
|
||||
dbConfig.petCareBodyId ||
|
||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
||||
'0',
|
||||
"0",
|
||||
),
|
||||
rules: Array.isArray(dbConfig.rules)
|
||||
? (dbConfig.rules as SmsRule[])
|
||||
@@ -129,17 +129,17 @@ export class SmsService {
|
||||
} catch {
|
||||
return {
|
||||
enabled: true,
|
||||
username: process.env.MELIPAYAMAK_USERNAME || '9364100228',
|
||||
password: process.env.MELIPAYAMAK_PASSWORD || '',
|
||||
fromNumber: process.env.MELIPAYAMAK_FROM_NUMBER || '',
|
||||
adminPhone: process.env.ADMIN_MOBILE || '09364100228',
|
||||
otpBodyId: Number(process.env.MELIPAYAMAK_OTP_BODY_ID || '508079'),
|
||||
orderBodyId: Number(process.env.MELIPAYAMAK_ORDER_BODY_ID || '508081'),
|
||||
username: process.env.MELIPAYAMAK_USERNAME || "9364100228",
|
||||
password: process.env.MELIPAYAMAK_PASSWORD || "",
|
||||
fromNumber: process.env.MELIPAYAMAK_FROM_NUMBER || "",
|
||||
adminPhone: process.env.ADMIN_MOBILE || "09364100228",
|
||||
otpBodyId: Number(process.env.MELIPAYAMAK_OTP_BODY_ID || "508079"),
|
||||
orderBodyId: Number(process.env.MELIPAYAMAK_ORDER_BODY_ID || "508081"),
|
||||
shippingBodyId: Number(
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '508082',
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || "508082",
|
||||
),
|
||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || '508083'),
|
||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0'),
|
||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
||||
rules: DEFAULT_SMS_RULES,
|
||||
};
|
||||
}
|
||||
@@ -174,19 +174,19 @@ export class SmsService {
|
||||
for (const rule of activeRules) {
|
||||
const phones: string[] = [];
|
||||
|
||||
if (rule.recipientType === 'customer') {
|
||||
if (rule.recipientType === "customer") {
|
||||
const customerPhone =
|
||||
data.customerPhone ||
|
||||
data.phone ||
|
||||
data.mobile ||
|
||||
data.recipientPhone;
|
||||
if (customerPhone) phones.push(String(customerPhone).trim());
|
||||
} else if (rule.recipientType === 'admin') {
|
||||
} else if (rule.recipientType === "admin") {
|
||||
const rawAdminPhones =
|
||||
config.adminPhone ||
|
||||
process.env.ADMIN_MOBILE ||
|
||||
process.env.ADMIN_MOBILE_ALERT ||
|
||||
'';
|
||||
"";
|
||||
const list = rawAdminPhones
|
||||
.split(/[,;\s]+/)
|
||||
.map((p) => p.trim())
|
||||
@@ -194,7 +194,7 @@ export class SmsService {
|
||||
if (list.length > 0) {
|
||||
phones.push(...list);
|
||||
}
|
||||
} else if (rule.recipientType === 'custom' && rule.customPhone) {
|
||||
} else if (rule.recipientType === "custom" && rule.customPhone) {
|
||||
const list = rule.customPhone
|
||||
.split(/[,;\s]+/)
|
||||
.map((p) => p.trim())
|
||||
@@ -213,7 +213,7 @@ export class SmsService {
|
||||
|
||||
const args: string[] = (rule.variables || []).map((varKey) => {
|
||||
const val = data[varKey];
|
||||
if (val === undefined || val === null) return '';
|
||||
if (val === undefined || val === null) return "";
|
||||
return String(val).trim();
|
||||
});
|
||||
|
||||
@@ -237,29 +237,29 @@ export class SmsService {
|
||||
this.logger.log(
|
||||
`[SMS Trigger] No custom rules configured for ${event}. Using standard fallback.`,
|
||||
);
|
||||
if (event === 'ORDER_PAID' || event === 'ORDER_CREATED') {
|
||||
if (event === "ORDER_PAID" || event === "ORDER_CREATED") {
|
||||
const phone = data.customerPhone || data.phone || data.mobile;
|
||||
if (phone && config.orderBodyId) {
|
||||
await this.sendOrderConfirmation(
|
||||
phone,
|
||||
data.customerName || 'مشتری',
|
||||
data.orderNumber || '',
|
||||
data.amount || '',
|
||||
data.customerName || "مشتری",
|
||||
data.orderNumber || "",
|
||||
data.amount || "",
|
||||
);
|
||||
}
|
||||
} else if (event === 'ORDER_SHIPPED') {
|
||||
} else if (event === "ORDER_SHIPPED") {
|
||||
const phone = data.customerPhone || data.phone || data.mobile;
|
||||
if (phone && config.shippingBodyId) {
|
||||
await this.sendShippingNotification(
|
||||
phone,
|
||||
data.orderNumber || '',
|
||||
data.trackingCode || '',
|
||||
data.orderNumber || "",
|
||||
data.trackingCode || "",
|
||||
);
|
||||
}
|
||||
} else if (event === 'B2B_SUBMITTED') {
|
||||
} else if (event === "B2B_SUBMITTED") {
|
||||
const phone = data.applicantPhone || data.phone;
|
||||
if (phone && config.b2bBodyId) {
|
||||
await this.sendB2bNotification(phone, data.applicantName || '');
|
||||
await this.sendB2bNotification(phone, data.applicantName || "");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -296,26 +296,26 @@ export class SmsService {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
'مشخصات نام کاربری و رمز عبور سامانه ملی پیامک تنظیم نشده است.',
|
||||
"مشخصات نام کاربری و رمز عبور سامانه ملی پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
if (!rule.patternId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'کد پترن (Body ID) برای این سناریو مشخص نشده است.',
|
||||
message: "کد پترن (Body ID) برای این سناریو مشخص نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
// Determine target recipient phone
|
||||
let phone = testPhone ? testPhone.trim() : '';
|
||||
let phone = testPhone ? testPhone.trim() : "";
|
||||
if (!phone) {
|
||||
if (rule.recipientType === 'customer') {
|
||||
phone = config.adminPhone || '09123456789';
|
||||
} else if (rule.recipientType === 'admin') {
|
||||
phone = config.adminPhone || process.env.ADMIN_MOBILE || '09123456789';
|
||||
} else if (rule.recipientType === 'custom') {
|
||||
phone = (rule.customPhone || '').split(/[,;\s]+/)[0] || '';
|
||||
if (rule.recipientType === "customer") {
|
||||
phone = config.adminPhone || "09123456789";
|
||||
} else if (rule.recipientType === "admin") {
|
||||
phone = config.adminPhone || process.env.ADMIN_MOBILE || "09123456789";
|
||||
} else if (rule.recipientType === "custom") {
|
||||
phone = (rule.customPhone || "").split(/[,;\s]+/)[0] || "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,7 +323,7 @@ export class SmsService {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
'شماره گیرنده جهت ارسال تست یافت نشد. لطفاً یک شماره موبایل وارد کنید.',
|
||||
"شماره گیرنده جهت ارسال تست یافت نشد. لطفاً یک شماره موبایل وارد کنید.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -361,26 +361,26 @@ export class SmsService {
|
||||
.map(
|
||||
([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`,
|
||||
)
|
||||
.join('&');
|
||||
.join("&");
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.request(
|
||||
`https://api.payamak-panel.com/post/SharedService.asmx/${endpoint}`,
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': Buffer.byteLength(postData),
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Content-Length": Buffer.byteLength(postData),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => resolve(data));
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => resolve(data));
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => reject(err));
|
||||
req.on("error", (err: Error) => reject(err));
|
||||
req.write(postData);
|
||||
req.end();
|
||||
});
|
||||
@@ -403,7 +403,7 @@ export class SmsService {
|
||||
await this.prisma.smsLog.create({
|
||||
data: {
|
||||
receptor: entry.receptor,
|
||||
type: entry.type || 'GENERIC',
|
||||
type: entry.type || "GENERIC",
|
||||
patternId: entry.patternId || null,
|
||||
args: entry.args || [],
|
||||
messageText: entry.messageText || null,
|
||||
@@ -431,22 +431,22 @@ export class SmsService {
|
||||
if (query.search) {
|
||||
const s = query.search.trim();
|
||||
where.OR = [
|
||||
{ receptor: { contains: s, mode: 'insensitive' } },
|
||||
{ recId: { contains: s, mode: 'insensitive' } },
|
||||
{ errorMessage: { contains: s, mode: 'insensitive' } },
|
||||
{ receptor: { contains: s, mode: "insensitive" } },
|
||||
{ recId: { contains: s, mode: "insensitive" } },
|
||||
{ errorMessage: { contains: s, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
if (query.type && query.type !== 'ALL') {
|
||||
if (query.type && query.type !== "ALL") {
|
||||
where.type = query.type;
|
||||
}
|
||||
|
||||
if (query.status && query.status !== 'ALL') {
|
||||
if (query.status && query.status !== "ALL") {
|
||||
where.status = query.status;
|
||||
}
|
||||
|
||||
const sortField = query.sortBy || 'createdAt';
|
||||
const sortOrder = query.sortOrder === 'asc' ? 'asc' : 'desc';
|
||||
const sortField = query.sortBy || "createdAt";
|
||||
const sortOrder = query.sortOrder === "asc" ? "asc" : "desc";
|
||||
|
||||
const [logs, total, totalSuccess, totalFailed] = await Promise.all([
|
||||
this.prisma.smsLog.findMany({
|
||||
@@ -456,8 +456,8 @@ export class SmsService {
|
||||
orderBy: { [sortField]: sortOrder },
|
||||
}),
|
||||
this.prisma.smsLog.count({ where }),
|
||||
this.prisma.smsLog.count({ where: { status: 'SUCCESS' } }),
|
||||
this.prisma.smsLog.count({ where: { status: 'FAILED' } }),
|
||||
this.prisma.smsLog.count({ where: { status: "SUCCESS" } }),
|
||||
this.prisma.smsLog.count({ where: { status: "FAILED" } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -511,21 +511,21 @@ export class SmsService {
|
||||
|
||||
if (idMatch) {
|
||||
const id = parseInt(idMatch[1], 10);
|
||||
const title = (titleMatch ? titleMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&')
|
||||
const title = (titleMatch ? titleMatch[1] : "")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/&/g, "&")
|
||||
.trim();
|
||||
const body = (bodyMatch ? bodyMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&')
|
||||
const body = (bodyMatch ? bodyMatch[1] : "")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/&/g, "&")
|
||||
.trim();
|
||||
const status = statusMatch ? parseInt(statusMatch[1], 10) : 0;
|
||||
|
||||
let statusText = 'در انتظار تایید';
|
||||
if (status === 1) statusText = 'تایید شده';
|
||||
else if (status === 2 || status === -1) statusText = 'نیاز به ویرایش';
|
||||
let statusText = "در انتظار تایید";
|
||||
if (status === 1) statusText = "تایید شده";
|
||||
else if (status === 2 || status === -1) statusText = "نیاز به ویرایش";
|
||||
|
||||
patterns.push({ id, title, body, status, statusText });
|
||||
}
|
||||
@@ -548,7 +548,7 @@ export class SmsService {
|
||||
return {
|
||||
success: false,
|
||||
credit: 0,
|
||||
message: 'نام کاربری و کلمه عبور ملی پیامک تنظیم نشده است.',
|
||||
message: "نام کاربری و کلمه عبور ملی پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -559,18 +559,18 @@ export class SmsService {
|
||||
});
|
||||
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/GetCredit',
|
||||
"https://rest.payamak-panel.com/api/SendSMS/GetCredit",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => {
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
const val = Number(json.Value ?? json.value ?? 0);
|
||||
@@ -591,7 +591,7 @@ export class SmsService {
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
req.on("error", (err: Error) => {
|
||||
resolve({
|
||||
success: false,
|
||||
credit: 0,
|
||||
@@ -612,7 +612,7 @@ export class SmsService {
|
||||
args: string[] = [],
|
||||
): Promise<string> {
|
||||
if (!patternId) {
|
||||
return args.join(' ');
|
||||
return args.join(" ");
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -620,19 +620,19 @@ export class SmsService {
|
||||
const target = patterns.find((p) => p.id === patternId);
|
||||
if (!target || !target.body) {
|
||||
return args.length > 0
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(' ، ')}`
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(" ، ")}`
|
||||
: `الگو ${patternId}`;
|
||||
}
|
||||
|
||||
let rendered = target.body;
|
||||
args.forEach((val, idx) => {
|
||||
const regex = new RegExp(`\\{${idx}\\}`, 'g');
|
||||
rendered = rendered.replace(regex, val || '');
|
||||
const regex = new RegExp(`\\{${idx}\\}`, "g");
|
||||
rendered = rendered.replace(regex, val || "");
|
||||
});
|
||||
return rendered;
|
||||
} catch {
|
||||
return args.length > 0
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(' ، ')}`
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(" ، ")}`
|
||||
: `الگو ${patternId}`;
|
||||
}
|
||||
}
|
||||
@@ -646,7 +646,7 @@ export class SmsService {
|
||||
let remotePatterns: MeliPayamakPattern[] = [];
|
||||
if (config.username && config.password) {
|
||||
try {
|
||||
const rawXml = await this.postAsmx('GetSharedServiceBody', {
|
||||
const rawXml = await this.postAsmx("GetSharedServiceBody", {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
});
|
||||
@@ -655,11 +655,11 @@ export class SmsService {
|
||||
// Cache patterns asynchronously in database
|
||||
this.prisma.setting
|
||||
.upsert({
|
||||
where: { key: 'sms_patterns_cache' },
|
||||
where: { key: "sms_patterns_cache" },
|
||||
update: { value: remotePatterns as any },
|
||||
create: {
|
||||
key: 'sms_patterns_cache',
|
||||
category: 'sms_patterns',
|
||||
key: "sms_patterns_cache",
|
||||
category: "sms_patterns",
|
||||
value: remotePatterns as any,
|
||||
},
|
||||
})
|
||||
@@ -678,10 +678,10 @@ export class SmsService {
|
||||
// Load cached patterns from settings table
|
||||
const storedSetting = await this.prisma.setting.findFirst({
|
||||
where: {
|
||||
category: 'sms_patterns',
|
||||
key: { in: ['sms_patterns_cache', 'sms_patterns_config'] },
|
||||
category: "sms_patterns",
|
||||
key: { in: ["sms_patterns_cache", "sms_patterns_config"] },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
const cachedPatterns: MeliPayamakPattern[] = Array.isArray(
|
||||
storedSetting?.value,
|
||||
@@ -717,23 +717,23 @@ export class SmsService {
|
||||
}> = [
|
||||
{
|
||||
id: config.otpBodyId,
|
||||
title: 'کد تایید ورود و ثبتنام (OTP)',
|
||||
body: 'کد تایید ورود به کنینا ایران: {0} میباشد. @canina.ir #{0}',
|
||||
title: "کد تایید ورود و ثبتنام (OTP)",
|
||||
body: "کد تایید ورود به کنینا ایران: {0} میباشد. @canina.ir #{0}",
|
||||
},
|
||||
{
|
||||
id: config.orderBodyId,
|
||||
title: 'تایید و ثبت فاکتور سفارش',
|
||||
body: '{0} عزیز ، سفارش شما به شماره {1} به مبلغ {2} با موفقیت ثبت شد.\nکنینا ایران',
|
||||
title: "تایید و ثبت فاکتور سفارش",
|
||||
body: "{0} عزیز ، سفارش شما به شماره {1} به مبلغ {2} با موفقیت ثبت شد.\nکنینا ایران",
|
||||
},
|
||||
{
|
||||
id: config.shippingBodyId,
|
||||
title: 'ارسال کد رهگیری پستی',
|
||||
body: 'مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.',
|
||||
title: "ارسال کد رهگیری پستی",
|
||||
body: "مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.",
|
||||
},
|
||||
{
|
||||
id: config.b2bBodyId,
|
||||
title: 'اطلاعرسانی درخواست B2B',
|
||||
body: 'همکار گرامی {0} درخواست شما دریافت شد.',
|
||||
title: "اطلاعرسانی درخواست B2B",
|
||||
body: "همکار گرامی {0} درخواست شما دریافت شد.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -744,7 +744,7 @@ export class SmsService {
|
||||
title: d.title,
|
||||
body: d.body,
|
||||
status: 1,
|
||||
statusText: 'تایید شده',
|
||||
statusText: "تایید شده",
|
||||
assignedTo: [],
|
||||
});
|
||||
}
|
||||
@@ -770,33 +770,33 @@ export class SmsService {
|
||||
// Check legacy default bindings
|
||||
if (
|
||||
p.id === config.otpBodyId &&
|
||||
!assigned.some((a) => a.includes('OTP'))
|
||||
!assigned.some((a) => a.includes("OTP"))
|
||||
) {
|
||||
assigned.push('کد تایید OTP');
|
||||
assigned.push("کد تایید OTP");
|
||||
}
|
||||
if (
|
||||
p.id === config.orderBodyId &&
|
||||
!assigned.some((a) => a.includes('سفارش'))
|
||||
!assigned.some((a) => a.includes("سفارش"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض سفارش');
|
||||
assigned.push("پترن پیشفرض سفارش");
|
||||
}
|
||||
if (
|
||||
p.id === config.shippingBodyId &&
|
||||
!assigned.some((a) => a.includes('پست'))
|
||||
!assigned.some((a) => a.includes("پست"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض پست');
|
||||
assigned.push("پترن پیشفرض پست");
|
||||
}
|
||||
if (
|
||||
p.id === config.b2bBodyId &&
|
||||
!assigned.some((a) => a.includes('B2B'))
|
||||
!assigned.some((a) => a.includes("B2B"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض B2B');
|
||||
assigned.push("پترن پیشفرض B2B");
|
||||
}
|
||||
if (
|
||||
p.id === config.petCareBodyId &&
|
||||
!assigned.some((a) => a.includes('پت'))
|
||||
!assigned.some((a) => a.includes("پت"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض پرونده پت');
|
||||
assigned.push("پترن پیشفرض پرونده پت");
|
||||
}
|
||||
|
||||
return { ...p, assignedTo: assigned };
|
||||
@@ -818,12 +818,12 @@ export class SmsService {
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
message: "مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyAdd', {
|
||||
const rawXml = await this.postAsmx("SharedServiceBodyAdd", {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
title,
|
||||
@@ -841,7 +841,7 @@ export class SmsService {
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
statusText: "در انتظار تایید",
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -852,12 +852,12 @@ export class SmsService {
|
||||
} else if (code === 0) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'نام کاربری یا کلمه عبور ملی پیامک اشتباه است.',
|
||||
message: "نام کاربری یا کلمه عبور ملی پیامک اشتباه است.",
|
||||
};
|
||||
} else if (code === -2) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'شناسه لیست سیاه ویژه اشتباه است.',
|
||||
message: "شناسه لیست سیاه ویژه اشتباه است.",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -873,7 +873,7 @@ export class SmsService {
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'ثبت محلی (در انتظار اتصال سرور)',
|
||||
statusText: "ثبت محلی (در انتظار اتصال سرور)",
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -896,12 +896,12 @@ export class SmsService {
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
message: "مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyEdit', {
|
||||
const rawXml = await this.postAsmx("SharedServiceBodyEdit", {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
bodyId,
|
||||
@@ -917,14 +917,14 @@ export class SmsService {
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر میباشد.',
|
||||
"ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر میباشد.",
|
||||
};
|
||||
} else if (code === -1) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وبسرویس اصلاح میشوند).',
|
||||
"متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وبسرویس اصلاح میشوند).",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -945,7 +945,7 @@ export class SmsService {
|
||||
private async saveLocalPattern(pattern: MeliPayamakPattern) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
where: { category: "sms_patterns" },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
|
||||
? (setting.value as unknown as MeliPayamakPattern[])
|
||||
@@ -953,14 +953,14 @@ export class SmsService {
|
||||
const updated = [pattern, ...list.filter((p) => p.id !== pattern.id)];
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
where: { key: "sms_patterns_config" },
|
||||
update: {
|
||||
category: 'sms_patterns',
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
create: {
|
||||
key: 'sms_patterns_config',
|
||||
category: 'sms_patterns',
|
||||
key: "sms_patterns_config",
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
@@ -973,7 +973,7 @@ export class SmsService {
|
||||
private async updateLocalPattern(bodyId: number, newBody: string) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
where: { category: "sms_patterns" },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
|
||||
? (setting.value as unknown as MeliPayamakPattern[])
|
||||
@@ -984,20 +984,20 @@ export class SmsService {
|
||||
...p,
|
||||
body: newBody,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
statusText: "در انتظار تایید",
|
||||
}
|
||||
: p,
|
||||
);
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
where: { key: "sms_patterns_config" },
|
||||
update: {
|
||||
category: 'sms_patterns',
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
create: {
|
||||
key: 'sms_patterns_config',
|
||||
category: 'sms_patterns',
|
||||
key: "sms_patterns_config",
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
@@ -1012,7 +1012,7 @@ export class SmsService {
|
||||
*/
|
||||
async sendPatternSms(options: SendPatternSmsOptions): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
const msgType = options.type || 'GENERIC_PATTERN';
|
||||
const msgType = options.type || "GENERIC_PATTERN";
|
||||
|
||||
if (!config.enabled) {
|
||||
this.logger.warn(`[SMS Disabled] SMS dispatch skipped for ${options.to}`);
|
||||
@@ -1021,21 +1021,21 @@ export class SmsService {
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک از پنل ادمین غیرفعال شده است.',
|
||||
status: "DISABLED",
|
||||
errorMessage: "ارسال پیامک از پنل ادمین غیرفعال شده است.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
const err = 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.';
|
||||
const err = "مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.";
|
||||
this.logger.error(`[SMS MISCONFIGURED] ${err}`);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: err,
|
||||
});
|
||||
return false;
|
||||
@@ -1045,7 +1045,7 @@ export class SmsService {
|
||||
const payload = JSON.stringify({
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
text: options.args.join(';'),
|
||||
text: options.args.join(";"),
|
||||
to: options.to,
|
||||
bodyId: options.bodyId,
|
||||
});
|
||||
@@ -1054,21 +1054,21 @@ export class SmsService {
|
||||
void this.renderPatternMessage(options.bodyId, options.args).then(
|
||||
(renderedText) => {
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
|
||||
"https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
let data = "";
|
||||
res.on(
|
||||
'data',
|
||||
"data",
|
||||
(chunk: Buffer | string) => (data += String(chunk)),
|
||||
);
|
||||
res.on('end', () => {
|
||||
res.on("end", () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
@@ -1083,7 +1083,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'SUCCESS',
|
||||
status: "SUCCESS",
|
||||
recId: String(val),
|
||||
});
|
||||
resolve(true);
|
||||
@@ -1098,7 +1098,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
@@ -1113,7 +1113,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: `خطای پارس پاسخ سرور: ${data || msg}`,
|
||||
});
|
||||
resolve(false);
|
||||
@@ -1123,7 +1123,7 @@ export class SmsService {
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
req.on("error", (err: Error) => {
|
||||
void (async () => {
|
||||
this.logger.error(
|
||||
`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`,
|
||||
@@ -1134,7 +1134,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: `خطای شبکه: ${err.message}`,
|
||||
});
|
||||
resolve(false);
|
||||
@@ -1163,44 +1163,44 @@ export class SmsService {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
const msg = 'نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.';
|
||||
const msg = "نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.";
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: testPatternId,
|
||||
args: testArgs,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: msg,
|
||||
});
|
||||
return { success: false, message: msg };
|
||||
}
|
||||
|
||||
const bodyId = testPatternId || config.otpBodyId || 508079;
|
||||
const args = testArgs && testArgs.length > 0 ? testArgs : ['123456'];
|
||||
const args = testArgs && testArgs.length > 0 ? testArgs : ["123456"];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
text: args.join(';'),
|
||||
text: args.join(";"),
|
||||
to: targetPhone,
|
||||
bodyId: bodyId,
|
||||
});
|
||||
|
||||
void this.renderPatternMessage(bodyId, args).then((renderedText) => {
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
|
||||
"https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => {
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
@@ -1208,11 +1208,11 @@ export class SmsService {
|
||||
if (json && (val > 15 || json.RetStatus === 1)) {
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'SUCCESS',
|
||||
status: "SUCCESS",
|
||||
recId: String(val),
|
||||
});
|
||||
resolve({
|
||||
@@ -1224,11 +1224,11 @@ export class SmsService {
|
||||
const errMsg = `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
@@ -1243,11 +1243,11 @@ export class SmsService {
|
||||
const errMsg = `پاسخ نامعتبر از سرور ملی پیامک: ${data || msg}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({ success: false, message: errMsg });
|
||||
@@ -1257,16 +1257,16 @@ export class SmsService {
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
req.on("error", (err: Error) => {
|
||||
void (async () => {
|
||||
const errMsg = `خطای برقراری ارتباط با وبسرویس ملی پیامک: ${err.message}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({ success: false, message: errMsg });
|
||||
@@ -1288,7 +1288,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.otpBodyId,
|
||||
args: [otpCode, otpCode],
|
||||
type: 'OTP',
|
||||
type: "OTP",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1302,12 +1302,12 @@ export class SmsService {
|
||||
amount: string,
|
||||
): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
const cleanName = (customerName || 'مشتری').trim();
|
||||
const cleanName = (customerName || "مشتری").trim();
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId: config.orderBodyId,
|
||||
args: [cleanName, orderNumber, amount],
|
||||
type: 'ORDER_CONFIRMATION',
|
||||
type: "ORDER_CONFIRMATION",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1324,7 +1324,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.shippingBodyId,
|
||||
args: [orderNumber, trackingCode],
|
||||
type: 'SHIPPING_TRACKING',
|
||||
type: "SHIPPING_TRACKING",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1340,7 +1340,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.b2bBodyId,
|
||||
args: [applicantName],
|
||||
type: 'B2B_NOTIFICATION',
|
||||
type: "B2B_NOTIFICATION",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1358,7 +1358,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.petCareBodyId,
|
||||
args: [petName, reminderType],
|
||||
type: 'PET_CARE_REMINDER',
|
||||
type: "PET_CARE_REMINDER",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1370,19 +1370,19 @@ export class SmsService {
|
||||
if (!config.enabled) {
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک غیرفعال است.',
|
||||
status: "DISABLED",
|
||||
errorMessage: "ارسال پیامک غیرفعال است.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: 'SUCCESS',
|
||||
status: "SUCCESS",
|
||||
});
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { SmsService } from './services/sms.service';
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { SmsService } from "./services/sms.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
|
||||
@@ -5,31 +5,31 @@
|
||||
* 3. Converts +98 or 0098 prefixes to 0
|
||||
*/
|
||||
export function normalizeMobile(mobile: string | undefined | null): string {
|
||||
if (!mobile) return '';
|
||||
if (!mobile) return "";
|
||||
|
||||
const persianDigits = '۰۱۲۳۴۵۶۷۸۹';
|
||||
const arabicDigits = '٠١٢٣٤٥٦٧٨٩';
|
||||
const persianDigits = "۰۱۲۳۴۵۶۷۸۹";
|
||||
const arabicDigits = "٠١٢٣٤٥٦٧٨٩";
|
||||
|
||||
let clean = String(mobile).trim();
|
||||
|
||||
// Convert Persian & Arabic numbers
|
||||
for (let i = 0; i < 10; i++) {
|
||||
clean = clean.replace(new RegExp(persianDigits[i], 'g'), String(i));
|
||||
clean = clean.replace(new RegExp(arabicDigits[i], 'g'), String(i));
|
||||
clean = clean.replace(new RegExp(persianDigits[i], "g"), String(i));
|
||||
clean = clean.replace(new RegExp(arabicDigits[i], "g"), String(i));
|
||||
}
|
||||
|
||||
// Remove non-digits except +
|
||||
clean = clean.replace(/[^\d+]/g, '');
|
||||
clean = clean.replace(/[^\d+]/g, "");
|
||||
|
||||
// Normalize prefix
|
||||
if (clean.startsWith('+98')) {
|
||||
clean = '0' + clean.slice(3);
|
||||
} else if (clean.startsWith('0098')) {
|
||||
clean = '0' + clean.slice(4);
|
||||
} else if (clean.startsWith('98') && clean.length === 12) {
|
||||
clean = '0' + clean.slice(2);
|
||||
} else if (clean.length === 10 && !clean.startsWith('0')) {
|
||||
clean = '0' + clean;
|
||||
if (clean.startsWith("+98")) {
|
||||
clean = "0" + clean.slice(3);
|
||||
} else if (clean.startsWith("0098")) {
|
||||
clean = "0" + clean.slice(4);
|
||||
} else if (clean.startsWith("98") && clean.length === 12) {
|
||||
clean = "0" + clean.slice(2);
|
||||
} else if (clean.length === 10 && !clean.startsWith("0")) {
|
||||
clean = "0" + clean;
|
||||
}
|
||||
|
||||
return clean;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type RoundingMode = 'UP' | 'DOWN' | 'NEAREST';
|
||||
export type RoundingMode = "UP" | "DOWN" | "NEAREST";
|
||||
|
||||
export interface PricingSettings {
|
||||
roundingStep: number;
|
||||
@@ -9,7 +9,7 @@ export interface PricingSettings {
|
||||
|
||||
export const DEFAULT_PRICING_SETTINGS: PricingSettings = {
|
||||
roundingStep: 5000,
|
||||
roundingMode: 'UP',
|
||||
roundingMode: "UP",
|
||||
defaultRetailMarginPercent: 30,
|
||||
defaultWholesaleMarginPercent: 15,
|
||||
};
|
||||
@@ -23,14 +23,14 @@ export const DEFAULT_PRICING_SETTINGS: PricingSettings = {
|
||||
export function applyRounding(
|
||||
price: number,
|
||||
step: number = 5000,
|
||||
mode: RoundingMode = 'UP',
|
||||
mode: RoundingMode = "UP",
|
||||
): number {
|
||||
if (isNaN(price) || price <= 0) return 0;
|
||||
if (!step || step <= 1) return Math.round(price);
|
||||
|
||||
if (mode === 'UP') {
|
||||
if (mode === "UP") {
|
||||
return Math.ceil(price / step) * step;
|
||||
} else if (mode === 'DOWN') {
|
||||
} else if (mode === "DOWN") {
|
||||
return Math.floor(price / step) * step;
|
||||
} else {
|
||||
return Math.round(price / step) * step;
|
||||
@@ -44,7 +44,7 @@ export function calculateSellingPrice(
|
||||
buyPrice: number,
|
||||
marginPercent: number,
|
||||
roundingStep: number = 5000,
|
||||
roundingMode: RoundingMode = 'UP',
|
||||
roundingMode: RoundingMode = "UP",
|
||||
): number {
|
||||
if (isNaN(buyPrice) || buyPrice <= 0) return 0;
|
||||
const rawPrice = buyPrice * (1 + (marginPercent || 0) / 100);
|
||||
|
||||
Reference in new issue
Block a user