fix(types,lint): resolve all TypeScript type check and eslint errors across backend and sms suite
This commit is contained in:
1 parent
d8c6aa8d8e
commit
8de1351349
19 files changed
+11299
-8849
No files matched your search
@@ -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(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
const body = (bodyMatch ? bodyMatch[1] : '').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
const title = (titleMatch ? titleMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&');
|
||||
const body = (bodyMatch ? bodyMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/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);
|
||||
|
||||
Reference in new issue
Block a user