fix(types,lint): resolve all TypeScript type check and eslint errors across backend and sms suite

This commit is contained in:
parsa aghaei committed 2026-08-16 12:00:49 +03:30
1 parent d8c6aa8d8e
commit 8de1351349
19 files changed
+11299 -8849

No files matched your search

+8 -3
View File
@@ -29,6 +29,8 @@ import { PrescriptionsModule } from './prescriptions/prescriptions.module';
import { B2BModule } from './b2b/b2b.module';
import { PaymentModule } from './payment/payment.module';
import { Request, Response, NextFunction } from 'express';
@Module({
imports: [
SmsModule,
@@ -77,15 +79,18 @@ export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply((req: any, res: any, next: () => void) => {
.apply((req: Request, res: Response, next: NextFunction) => {
MetricsController.incrementRequestCount();
const url: string = req.originalUrl || req.url || '';
const method: string = req.method || '';
// Exclude options, admin panel requests, static assets, and health metrics from visit counter
const isAdminPath = url.includes('/admin') || url.includes('/api/admin');
const isStaticAsset = url.match(/\.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|map)$/i);
const isAdminPath =
url.includes('/admin') || url.includes('/api/admin');
const isStaticAsset = url.match(
/\.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|map)$/i,
);
const isIgnoredMethod = method === 'OPTIONS' || method === 'HEAD';
if (!isAdminPath && !isStaticAsset && !isIgnoredMethod) {
+2 -1
View File
@@ -49,7 +49,8 @@ export class AuthService {
// Remove OTP from Redis if SMS failed to avoid phantom codes
await this.redisService.del(`otp:${phoneNumber}`);
throw new BadRequestException({
message: 'ارسال پیامک با خطا مواجه شد. لطفاً چند لحظه دیگر دوباره تلاش کنید.',
message:
'ارسال پیامک با خطا مواجه شد. لطفاً چند لحظه دیگر دوباره تلاش کنید.',
error: 'SMS_DELIVERY_FAILED',
});
}
+300 -152
View File
@@ -31,7 +31,7 @@ export interface MeliPayamakPattern {
assignedTo?: string[];
}
export interface SmsLogQuery {
export class SmsLogQuery {
page?: number;
limit?: number;
search?: string;
@@ -41,7 +41,7 @@ export interface SmsLogQuery {
sortOrder?: 'asc' | 'desc';
}
interface MeliPayamakResponse {
export interface MeliPayamakResponse {
Value?: number;
RetStatus?: number;
StrRetStatus?: string;
@@ -61,18 +61,44 @@ export class SmsService {
const setting = await this.prisma.setting.findFirst({
where: { category: 'sms' },
});
const dbConfig = (setting?.value as Record<string, any>) || {};
const dbConfig = (setting?.value as Record<string, unknown>) || {};
return {
enabled: dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
username: dbConfig.username || process.env.MELIPAYAMAK_USERNAME || '9364100228',
password: dbConfig.password || process.env.MELIPAYAMAK_PASSWORD || '',
fromNumber: dbConfig.fromNumber || process.env.MELIPAYAMAK_FROM_NUMBER || '',
otpBodyId: Number(dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || '508079'),
orderBodyId: Number(dbConfig.orderBodyId || process.env.MELIPAYAMAK_ORDER_BODY_ID || '508081'),
shippingBodyId: Number(dbConfig.shippingBodyId || process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '508082'),
b2bBodyId: Number(dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || '508083'),
petCareBodyId: Number(dbConfig.petCareBodyId || process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0'),
enabled:
dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
username:
typeof dbConfig.username === 'string' && dbConfig.username
? dbConfig.username
: process.env.MELIPAYAMAK_USERNAME || '9364100228',
password:
typeof dbConfig.password === 'string' && dbConfig.password
? dbConfig.password
: process.env.MELIPAYAMAK_PASSWORD || '',
fromNumber:
typeof dbConfig.fromNumber === 'string' && dbConfig.fromNumber
? dbConfig.fromNumber
: process.env.MELIPAYAMAK_FROM_NUMBER || '',
otpBodyId: Number(
dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || '508079',
),
orderBodyId: Number(
dbConfig.orderBodyId ||
process.env.MELIPAYAMAK_ORDER_BODY_ID ||
'508081',
),
shippingBodyId: Number(
dbConfig.shippingBodyId ||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID ||
'508082',
),
b2bBodyId: Number(
dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || '508083',
),
petCareBodyId: Number(
dbConfig.petCareBodyId ||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
'0',
),
};
} catch {
return {
@@ -82,7 +108,9 @@ export class SmsService {
fromNumber: process.env.MELIPAYAMAK_FROM_NUMBER || '',
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'),
shippingBodyId: Number(
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'),
};
@@ -92,9 +120,14 @@ export class SmsService {
/**
* Helper HTTP POST request to Payamak-Panel ASMX endpoints
*/
private async postAsmx(endpoint: string, params: Record<string, string | number>): Promise<string> {
private async postAsmx(
endpoint: string,
params: Record<string, string | number>,
): Promise<string> {
const postData = Object.entries(params)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
.map(
([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`,
)
.join('&');
return new Promise((resolve, reject) => {
@@ -109,12 +142,12 @@ export class SmsService {
},
(res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
res.on('end', () => resolve(data));
},
);
req.on('error', (err) => reject(err));
req.on('error', (err: Error) => reject(err));
req.write(postData);
req.end();
});
@@ -132,7 +165,7 @@ export class SmsService {
status: string;
recId?: string;
errorMessage?: string;
}) {
}): Promise<void> {
try {
await this.prisma.smsLog.create({
data: {
@@ -146,8 +179,9 @@ export class SmsService {
errorMessage: entry.errorMessage || null,
},
});
} catch (err: any) {
this.logger.error(`[SMS Log Save Failed]: ${err.message}`);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
this.logger.error(`[SMS Log Save Failed]: ${msg}`);
}
}
@@ -239,8 +273,14 @@ export class SmsService {
if (idMatch) {
const id = parseInt(idMatch[1], 10);
const title = (titleMatch ? titleMatch[1] : '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
const body = (bodyMatch ? bodyMatch[1] : '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
const title = (titleMatch ? titleMatch[1] : '')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
const body = (bodyMatch ? bodyMatch[1] : '')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
const status = statusMatch ? parseInt(statusMatch[1], 10) : 0;
let statusText = 'در انتظار تایید';
@@ -268,8 +308,11 @@ export class SmsService {
password: config.password,
});
remotePatterns = this.parsePatternsXml(rawXml);
} catch (err: any) {
this.logger.warn(`[SMS Patterns] Remote fetch failed: ${err.message}. Using stored patterns.`);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
this.logger.warn(
`[SMS Patterns] Remote fetch failed: ${msg}. Using stored patterns.`,
);
}
}
@@ -277,17 +320,46 @@ export class SmsService {
const storedSetting = await this.prisma.setting.findFirst({
where: { category: 'sms_patterns' },
});
const localPatterns: MeliPayamakPattern[] = (storedSetting?.value as any) || [];
const localPatterns: MeliPayamakPattern[] = Array.isArray(
storedSetting?.value,
)
? (storedSetting.value as unknown as MeliPayamakPattern[])
: [];
// Merge remote and local (remote takes precedence on ID match)
const map = new Map<number, MeliPayamakPattern>();
// Add configured system patterns by default if map is empty
const defaultConfigs: Array<{ id: number; title: string; body: string; assigned: string }> = [
{ id: config.otpBodyId, title: 'کد تایید ورود و ثبت‌نام (OTP)', body: 'کد ورود به کانینا: {0}', assigned: 'otp' },
{ id: config.orderBodyId, title: 'تایید و ثبت فاکتور سفارش', body: 'سفارش شما به شماره {0} با مبلغ {1} ثبت گردید.', assigned: 'order' },
{ id: config.shippingBodyId, title: 'ارسال کد رهگیری پستی', body: 'مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.', assigned: 'shipping' },
{ id: config.b2bBodyId, title: 'اطلاع‌رسانی درخواست B2B', body: 'همکار گرامی {0} درخواست شما دریافت شد.', assigned: 'b2b' },
const defaultConfigs: Array<{
id: number;
title: string;
body: string;
assigned: string;
}> = [
{
id: config.otpBodyId,
title: 'کد تایید ورود و ثبت‌نام (OTP)',
body: 'کد ورود به کانینا: {0}',
assigned: 'otp',
},
{
id: config.orderBodyId,
title: 'تایید و ثبت فاکتور سفارش',
body: 'سفارش شما به شماره {0} با مبلغ {1} ثبت گردید.',
assigned: 'order',
},
{
id: config.shippingBodyId,
title: 'ارسال کد رهگیری پستی',
body: 'مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.',
assigned: 'shipping',
},
{
id: config.b2bBodyId,
title: 'اطلاع‌رسانی درخواست B2B',
body: 'همکار گرامی {0} درخواست شما دریافت شد.',
assigned: 'b2b',
},
];
for (const d of defaultConfigs) {
@@ -304,7 +376,7 @@ export class SmsService {
}
for (const lp of localPatterns) {
if (lp.id) map.set(lp.id, { ...lp });
if (lp && lp.id) map.set(lp.id, { ...lp });
}
for (const rp of remotePatterns) {
@@ -332,7 +404,11 @@ export class SmsService {
/**
* Add a new pattern to MeliPayamak
*/
async addPattern(title: string, body: string, blackListId: number = 0): Promise<{ success: boolean; bodyId?: number; message: string }> {
async addPattern(
title: string,
body: string,
blackListId: number = 0,
): Promise<{ success: boolean; bodyId?: number; message: string }> {
const config = await this.getSmsConfig();
if (!config.username || !config.password) {
@@ -351,7 +427,8 @@ export class SmsService {
blackListId,
});
const match = rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
const match =
rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
const code = match ? parseInt(match[1], 10) : 0;
if (code > 0) {
@@ -369,13 +446,23 @@ export class SmsService {
message: `الگو با موفقیت ثبت شد و شناسه اختصاصی ${code} دریافت گردید. (وضعیت: در انتظار تایید ناظر)`,
};
} else if (code === 0) {
return { success: false, message: 'نام کاربری یا کلمه عبور ملی پیامک اشتباه است.' };
return {
success: false,
message: 'نام کاربری یا کلمه عبور ملی پیامک اشتباه است.',
};
} else if (code === -2) {
return { success: false, message: 'شناسه لیست سیاه ویژه اشتباه است.' };
return {
success: false,
message: 'شناسه لیست سیاه ویژه اشتباه است.',
};
} else {
return { success: false, message: `خطا در ثبت پترن با کد پاسخ: ${code}` };
return {
success: false,
message: `خطا در ثبت پترن با کد پاسخ: ${code}`,
};
}
} catch (err: any) {
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
const generatedId = Math.floor(500000 + Math.random() * 90000);
await this.saveLocalPattern({
id: generatedId,
@@ -388,7 +475,7 @@ export class SmsService {
return {
success: true,
bodyId: generatedId,
message: `الگو به صورت محلی با شناسه موقت ${generatedId} ذخیره شد (${err.message}).`,
message: `الگو به صورت محلی با شناسه موقت ${generatedId} ذخیره شد (${msg}).`,
};
}
}
@@ -396,7 +483,10 @@ export class SmsService {
/**
* Edit an existing pattern in MeliPayamak
*/
async editPattern(bodyId: number, body: string): Promise<{ success: boolean; message: string }> {
async editPattern(
bodyId: number,
body: string,
): Promise<{ success: boolean; message: string }> {
const config = await this.getSmsConfig();
if (!config.username || !config.password) {
@@ -414,29 +504,36 @@ export class SmsService {
body,
});
const match = rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
const match =
rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
const code = match ? parseInt(match[1], 10) : 0;
if (code === 1) {
await this.updateLocalPattern(bodyId, body);
return {
success: true,
message: 'ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر می‌باشد.',
message:
'ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر می‌باشد.',
};
} else if (code === -1) {
await this.updateLocalPattern(bodyId, body);
return {
success: true,
message: 'متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وب‌سرویس اصلاح می‌شوند).',
message:
'متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وب‌سرویس اصلاح می‌شوند).',
};
} else {
return { success: false, message: `خطا در ویرایش الگو با کد پاسخ: ${code}` };
return {
success: false,
message: `خطا در ویرایش الگو با کد پاسخ: ${code}`,
};
}
} catch (err: any) {
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
await this.updateLocalPattern(bodyId, body);
return {
success: true,
message: `متن الگو در دیتابیس داخلی بروز شد (${err.message}).`,
message: `متن الگو در دیتابیس داخلی بروز شد (${msg}).`,
};
}
}
@@ -446,16 +543,26 @@ export class SmsService {
const setting = await this.prisma.setting.findFirst({
where: { category: 'sms_patterns' },
});
const list: MeliPayamakPattern[] = (setting?.value as any) || [];
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
? (setting.value as unknown as MeliPayamakPattern[])
: [];
const updated = [pattern, ...list.filter((p) => p.id !== pattern.id)];
await this.prisma.setting.upsert({
where: { key: 'sms_patterns_config' },
update: { category: 'sms_patterns', value: updated as any },
create: { key: 'sms_patterns_config', category: 'sms_patterns', value: updated as any },
update: {
category: 'sms_patterns',
value: updated as unknown as Prisma.InputJsonValue,
},
create: {
key: 'sms_patterns_config',
category: 'sms_patterns',
value: updated as unknown as Prisma.InputJsonValue,
},
});
} catch (err: any) {
this.logger.error(`Failed to save local pattern: ${err.message}`);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
this.logger.error(`Failed to save local pattern: ${msg}`);
}
}
@@ -464,16 +571,35 @@ export class SmsService {
const setting = await this.prisma.setting.findFirst({
where: { category: 'sms_patterns' },
});
const list: MeliPayamakPattern[] = (setting?.value as any) || [];
const updated = list.map((p) => (p.id === bodyId ? { ...p, body: newBody, status: 0, statusText: 'در انتظار تایید' } : p));
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
? (setting.value as unknown as MeliPayamakPattern[])
: [];
const updated = list.map((p) =>
p.id === bodyId
? {
...p,
body: newBody,
status: 0,
statusText: 'در انتظار تایید',
}
: p,
);
await this.prisma.setting.upsert({
where: { key: 'sms_patterns_config' },
update: { category: 'sms_patterns', value: updated as any },
create: { key: 'sms_patterns_config', category: 'sms_patterns', value: updated as any },
update: {
category: 'sms_patterns',
value: updated as unknown as Prisma.InputJsonValue,
},
create: {
key: 'sms_patterns_config',
category: 'sms_patterns',
value: updated as unknown as Prisma.InputJsonValue,
},
});
} catch (err: any) {
this.logger.error(`Failed to update local pattern: ${err.message}`);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
this.logger.error(`Failed to update local pattern: ${msg}`);
}
}
@@ -531,64 +657,73 @@ export class SmsService {
},
(res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', async () => {
try {
const json = JSON.parse(data) as MeliPayamakResponse;
const val = json.Value ?? 0;
if (json && (val > 15 || json.RetStatus === 1)) {
this.logger.log(
`[SMS Sent] Pattern SMS ${options.bodyId} dispatched to ${options.to} (RecId: ${val})`,
);
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'SUCCESS',
recId: String(val),
});
resolve(true);
} else {
const errMsg = `خطای درگاه ملی پیامک با کد بازگشتی: ${val}`;
this.logger.error(`[SMS Error] Failed sending to ${options.to}. Code: ${val}`);
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
res.on('end', () => {
void (async () => {
try {
const json = JSON.parse(data) as MeliPayamakResponse;
const val = json.Value ?? 0;
if (json && (val > 15 || json.RetStatus === 1)) {
this.logger.log(
`[SMS Sent] Pattern SMS ${options.bodyId} dispatched to ${options.to} (RecId: ${val})`,
);
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'SUCCESS',
recId: String(val),
});
resolve(true);
} else {
const errMsg = `خطای درگاه ملی پیامک با کد بازگشتی: ${val}`;
this.logger.error(
`[SMS Error] Failed sending to ${options.to}. Code: ${val}`,
);
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'FAILED',
recId: String(val),
errorMessage: errMsg,
});
resolve(false);
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'FAILED',
recId: String(val),
errorMessage: errMsg,
errorMessage: `خطای پارس پاسخ سرور: ${data || msg}`,
});
resolve(false);
}
} catch (err: any) {
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'FAILED',
errorMessage: `خطای پارس پاسخ سرور: ${data || err.message}`,
});
resolve(false);
}
})();
});
},
);
req.on('error', async (err) => {
this.logger.error(`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`);
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'FAILED',
errorMessage: `خطای شبکه: ${err.message}`,
});
resolve(false);
req.on('error', (err: Error) => {
void (async () => {
this.logger.error(
`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`,
);
await this.recordLog({
receptor: options.to,
type: msgType,
patternId: options.bodyId,
args: options.args,
status: 'FAILED',
errorMessage: `خطای شبکه: ${err.message}`,
});
resolve(false);
})();
});
req.write(payload);
@@ -599,7 +734,15 @@ export class SmsService {
/**
* Test SMS Dispatch from Admin Panel
*/
async testSms(targetPhone: string, testPatternId?: number, testArgs?: string[]): Promise<{ success: boolean; message: string; rawResponse?: any }> {
async testSms(
targetPhone: string,
testPatternId?: number,
testArgs?: string[],
): Promise<{
success: boolean;
message: string;
rawResponse?: MeliPayamakResponse;
}> {
const config = await this.getSmsConfig();
if (!config.username || !config.password) {
@@ -638,69 +781,74 @@ export class SmsService {
},
(res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', async () => {
try {
const json = JSON.parse(data) as MeliPayamakResponse;
const val = json.Value ?? 0;
if (json && (val > 15 || json.RetStatus === 1)) {
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'SUCCESS',
recId: String(val),
});
resolve({
success: true,
message: `پیامک تستی پترن با موفقیت ارسال شد (شناسه پیگیری ملی پیامک: ${val})`,
rawResponse: json,
});
} else {
const errMsg = `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`;
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
res.on('end', () => {
void (async () => {
try {
const json = JSON.parse(data) as MeliPayamakResponse;
const val = json.Value ?? 0;
if (json && (val > 15 || json.RetStatus === 1)) {
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'SUCCESS',
recId: String(val),
});
resolve({
success: true,
message: `پیامک تستی پترن با موفقیت ارسال شد (شناسه پیگیری ملی پیامک: ${val})`,
rawResponse: json,
});
} else {
const errMsg = `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`;
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'FAILED',
recId: String(val),
errorMessage: errMsg,
});
resolve({
success: false,
message: errMsg,
rawResponse: json,
});
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
const errMsg = `پاسخ نامعتبر از سرور ملی پیامک: ${data || msg}`;
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'FAILED',
recId: String(val),
errorMessage: errMsg,
});
resolve({
success: false,
message: errMsg,
rawResponse: json,
});
resolve({ success: false, message: errMsg });
}
} catch (err: any) {
const errMsg = `پاسخ نامعتبر از سرور ملی پیامک: ${data || err.message}`;
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'FAILED',
errorMessage: errMsg,
});
resolve({ success: false, message: errMsg });
}
})();
});
},
);
req.on('error', async (err) => {
const errMsg = `خطای برقراری ارتباط با وب‌سرویس ملی پیامک: ${err.message}`;
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'FAILED',
errorMessage: errMsg,
});
resolve({ success: false, message: errMsg });
req.on('error', (err: Error) => {
void (async () => {
const errMsg = `خطای برقراری ارتباط با وب‌سرویس ملی پیامک: ${err.message}`;
await this.recordLog({
receptor: targetPhone,
type: 'TEST',
patternId: bodyId,
args,
status: 'FAILED',
errorMessage: errMsg,
});
resolve({ success: false, message: errMsg });
})();
});
req.write(payload);
+12 -6
View File
@@ -23,7 +23,6 @@ import {
ApiTags,
ApiOperation,
ApiBearerAuth,
ApiResponse,
ApiOkResponse,
ApiBadRequestResponse,
} from '@nestjs/swagger';
@@ -52,7 +51,9 @@ export class PaymentController {
},
},
})
@ApiBadRequestResponse({ description: 'خطا در ایجاد تراکنش یا نامعتبر بودن سفارش' })
@ApiBadRequestResponse({
description: 'خطا در ایجاد تراکنش یا نامعتبر بودن سفارش',
})
async initiateOrderPayment(
@Req() req: { user: { id: string } },
@Body() body: InitiatePaymentDto,
@@ -91,7 +92,9 @@ export class PaymentController {
}
@Get('zibal/callback')
@ApiOperation({ summary: 'دریافت کال‌بک بازگشت از درگاه زیبال و تایید تراکنش' })
@ApiOperation({
summary: 'دریافت کال‌بک بازگشت از درگاه زیبال و تایید تراکنش',
})
async handleZibalCallback(
@Query() query: ZibalCallbackQueryDto,
@Res() res: Response,
@@ -130,9 +133,10 @@ export class PaymentController {
});
return res.redirect(`${frontendUrl}/payment/verify?${params.toString()}`);
} catch (err: any) {
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'خطا در پردازش پرداخت';
return res.redirect(
`${frontendUrl}/payment/verify?success=0&trackId=${trackId}&message=${encodeURIComponent(err.message || 'خطا در پردازش پرداخت')}`,
`${frontendUrl}/payment/verify?success=0&trackId=${trackId}&message=${encodeURIComponent(msg)}`,
);
}
}
@@ -149,7 +153,9 @@ export class PaymentController {
const orderId = body.orderId;
if (!trackId) {
return res.status(HttpStatus.BAD_REQUEST).json({ success: false, message: 'trackId is required' });
return res
.status(HttpStatus.BAD_REQUEST)
.json({ success: false, message: 'trackId is required' });
}
const result = await this.paymentService.verifyAndProcess(
+39 -17
View File
@@ -46,7 +46,9 @@ export class PaymentService {
const amountRials = Math.round(amountTomans * 10);
if (amountRials < 1000) {
throw new BadRequestException('مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است');
throw new BadRequestException(
'مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است',
);
}
const frontendUrl = await this.zibalService.getFrontendUrl();
@@ -111,9 +113,11 @@ export class PaymentService {
orderId: order.id,
amount: amountTomans,
};
} catch (err: any) {
this.logger.error(`Error requesting payment from Zibal: ${err.message}`, err.stack);
throw new BadRequestException(err.message || 'خطا در اتصال به درگاه پرداخت');
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
const stack = err instanceof Error ? err.stack : undefined;
this.logger.error(`Error requesting payment from Zibal: ${msg}`, stack);
throw new BadRequestException(msg || 'خطا در اتصال به درگاه پرداخت');
}
}
@@ -189,9 +193,10 @@ export class PaymentService {
paymentUrl: this.zibalService.getStartUrl(trackId),
amount: amountTomans,
};
} catch (err: any) {
this.logger.error(`Error requesting wallet topup from Zibal: ${err.message}`);
throw new BadRequestException(err.message || 'خطا در ارتباط با درگاه بانکی');
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
this.logger.error(`Error requesting wallet topup from Zibal: ${msg}`);
throw new BadRequestException(msg || 'خطا در ارتباط با درگاه بانکی');
}
}
@@ -226,7 +231,10 @@ export class PaymentService {
orderBy: { createdAt: 'desc' },
include: {
order: {
include: { user: true, orderItems: { include: { product: true } } },
include: {
user: true,
orderItems: { include: { product: true } },
},
},
user: true,
},
@@ -255,7 +263,9 @@ export class PaymentService {
// If user cancelled or Zibal signaled failure at the gate
if (successParam === '0' || statusParam === '3') {
const statusMessage = this.zibalService.getStatusMessage(statusParam || 3);
const statusMessage = this.zibalService.getStatusMessage(
statusParam || 3,
);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
@@ -301,9 +311,13 @@ export class PaymentService {
}
// SUCCESSFUL PAYMENT!
const refNumber = verifyRes.refNumber ? String(verifyRes.refNumber) : undefined;
const refNumber = verifyRes.refNumber
? String(verifyRes.refNumber)
: undefined;
const cardNumber = verifyRes.cardNumber || undefined;
const paidDate = verifyRes.paidAt ? new Date(verifyRes.paidAt) : new Date();
const paidDate = verifyRes.paidAt
? new Date(verifyRes.paidAt)
: new Date();
await this.prisma.$transaction(async (tx) => {
// 1. Mark transaction as VERIFIED
@@ -330,7 +344,10 @@ export class PaymentService {
});
// If charity donation was made, update user's total charity
if (transaction.order && Number(transaction.order.charityDonation) > 0) {
if (
transaction.order &&
Number(transaction.order.charityDonation) > 0
) {
await tx.user.update({
where: { id: transaction.userId },
data: {
@@ -369,8 +386,11 @@ export class PaymentService {
// Send SMS notification if order payment
if (transaction.type === 'ORDER' && transaction.order?.user?.mobile) {
const mobile = transaction.order.user.mobile;
const trackingNum = transaction.order.trackingNumber || transaction.order.id;
const formattedAmount = Number(transaction.amount).toLocaleString('fa-IR');
const trackingNum =
transaction.order.trackingNumber || transaction.order.id;
const formattedAmount = Number(transaction.amount).toLocaleString(
'fa-IR',
);
this.smsService
.sendOrderConfirmation(mobile, trackingNum, formattedAmount)
@@ -390,13 +410,15 @@ export class PaymentService {
type: transaction.type,
message: 'پرداخت با موفقیت انجام شد',
};
} catch (err: any) {
this.logger.error(`Error during verify: ${err.message}`, err.stack);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
const stack = err instanceof Error ? err.stack : undefined;
this.logger.error(`Error during verify: ${msg}`, stack);
return {
success: false,
status: 'ERROR',
trackId,
message: err.message || 'خطا در فرایند تایید تراکنش',
message: msg || 'خطا در فرایند تایید تراکنش',
orderId: transaction.orderId,
};
}
+24 -8
View File
@@ -115,8 +115,12 @@ export class ZibalService {
if (!response.ok) {
const errorText = await response.text();
this.logger.error(`Zibal request HTTP error ${response.status}: ${errorText}`);
throw new Error(`خطا در اتصال به درگاه زیبال: کد وضعیت ${response.status}`);
this.logger.error(
`Zibal request HTTP error ${response.status}: ${errorText}`,
);
throw new Error(
`خطا در اتصال به درگاه زیبال: کد وضعیت ${response.status}`,
);
}
const data = (await response.json()) as ZibalRequestResponse;
@@ -142,7 +146,9 @@ export class ZibalService {
trackId: String(trackId),
};
this.logger.log(`Verifying payment on Zibal for trackId=${trackId}, merchant=${merchant}`);
this.logger.log(
`Verifying payment on Zibal for trackId=${trackId}, merchant=${merchant}`,
);
const response = await fetch(`${this.baseUrl}/v1/verify`, {
method: 'POST',
@@ -154,8 +160,12 @@ export class ZibalService {
if (!response.ok) {
const errorText = await response.text();
this.logger.error(`Zibal verify HTTP error ${response.status}: ${errorText}`);
throw new Error(`خطا در تایید تراکنش درگاه زیبال: کد وضعیت ${response.status}`);
this.logger.error(
`Zibal verify HTTP error ${response.status}: ${errorText}`,
);
throw new Error(
`خطا در تایید تراکنش درگاه زیبال: کد وضعیت ${response.status}`,
);
}
const data = (await response.json()) as ZibalVerifyResponse;
@@ -166,7 +176,9 @@ export class ZibalService {
/**
* 4. Inquiry Payment (استعلام وضعیت تراکنش)
*/
async inquiryPayment(trackId: string | number): Promise<ZibalInquiryResponse> {
async inquiryPayment(
trackId: string | number,
): Promise<ZibalInquiryResponse> {
const merchant = await this.getMerchant();
const payload = {
@@ -186,8 +198,12 @@ export class ZibalService {
if (!response.ok) {
const errorText = await response.text();
this.logger.error(`Zibal inquiry HTTP error ${response.status}: ${errorText}`);
throw new Error(`خطا در استعلام تراکنش زیبال: کد وضعیت ${response.status}`);
this.logger.error(
`Zibal inquiry HTTP error ${response.status}: ${errorText}`,
);
throw new Error(
`خطا در استعلام تراکنش زیبال: کد وضعیت ${response.status}`,
);
}
const data = (await response.json()) as ZibalInquiryResponse;
+12 -10
View File
@@ -12,6 +12,7 @@ import {
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { SettingsService, ScientificTermData } from './settings.service';
import { SmsLogQuery } from '../common/services/sms.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
@@ -164,7 +165,9 @@ export class SettingsController {
@Roles('Admin')
@ApiBearerAuth()
@Get('sms/patterns')
@ApiOperation({ summary: 'دریافت لیست تمامی پترن‌های تعریف شده در ملی پیامک' })
@ApiOperation({
summary: 'دریافت لیست تمامی پترن‌های تعریف شده در ملی پیامک',
})
getPatterns() {
return this.settingsService.getPatterns();
}
@@ -186,11 +189,10 @@ export class SettingsController {
@Roles('Admin')
@ApiBearerAuth()
@Put('sms/patterns/:bodyId')
@ApiOperation({ summary: 'ویرایش الگوی رد شده یا در حال ویرایش در ملی پیامک' })
editPattern(
@Param('bodyId') bodyId: string,
@Body('body') body: string,
) {
@ApiOperation({
summary: 'ویرایش الگوی رد شده یا در حال ویرایش در ملی پیامک',
})
editPattern(@Param('bodyId') bodyId: string, @Body('body') body: string) {
return this.settingsService.editPattern(Number(bodyId), body);
}
@@ -199,8 +201,10 @@ export class SettingsController {
@Roles('Admin')
@ApiBearerAuth()
@Get('sms/logs')
@ApiOperation({ summary: 'دریافت گزارشات و لاگ‌های کامل پیامک‌های ارسالی با فیلتر و جستجو' })
getSmsLogs(@Query() query: any) {
@ApiOperation({
summary: 'دریافت گزارشات و لاگ‌های کامل پیامک‌های ارسالی با فیلتر و جستجو',
})
getSmsLogs(@Query() query: SmsLogQuery) {
return this.settingsService.getSmsLogs(query);
}
@@ -222,5 +226,3 @@ export class SettingsController {
return this.settingsService.clearAllSmsLogs();
}
}
+2 -3
View File
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/services/sms.service';
import { SmsService, SmsLogQuery } from '../common/services/sms.service';
export class ScientificTermData {
term?: string;
@@ -116,7 +116,7 @@ export class SettingsService {
return this.smsService.editPattern(bodyId, body);
}
async getSmsLogs(query: any) {
async getSmsLogs(query: SmsLogQuery) {
return this.smsService.getSmsLogs(query);
}
@@ -128,4 +128,3 @@ export class SettingsService {
return this.smsService.clearAllSmsLogs();
}
}