feat(sms,admin): implement full sms logging, tracking, filtering, and analytics system
This commit is contained in:
1 parent
6a476fab1a
commit
d8c6aa8d8e
5 files changed
+895
-49
No files matched your search
@@ -1,11 +1,13 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as https from 'https';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
export interface SendPatternSmsOptions {
|
||||
to: string;
|
||||
bodyId: number; // MeliPayamak Shared Pattern Body ID
|
||||
args: string[]; // Dynamic variables inside pattern
|
||||
type?: string; // OTP, ORDER_CONFIRMATION, SHIPPING_TRACKING, B2B_NOTIFICATION, PET_CARE_REMINDER, TEST, GENERIC
|
||||
}
|
||||
|
||||
export interface SmsConfig {
|
||||
@@ -29,6 +31,16 @@ export interface MeliPayamakPattern {
|
||||
assignedTo?: string[];
|
||||
}
|
||||
|
||||
export interface SmsLogQuery {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
type?: string;
|
||||
status?: string;
|
||||
sortBy?: string;
|
||||
sortOrder?: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
interface MeliPayamakResponse {
|
||||
Value?: number;
|
||||
RetStatus?: number;
|
||||
@@ -108,6 +120,108 @@ export class SmsService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to write an SMS Log to PostgreSQL safely
|
||||
*/
|
||||
private async recordLog(entry: {
|
||||
receptor: string;
|
||||
type: string;
|
||||
patternId?: number;
|
||||
args?: string[];
|
||||
messageText?: string;
|
||||
status: string;
|
||||
recId?: string;
|
||||
errorMessage?: string;
|
||||
}) {
|
||||
try {
|
||||
await this.prisma.smsLog.create({
|
||||
data: {
|
||||
receptor: entry.receptor,
|
||||
type: entry.type || 'GENERIC',
|
||||
patternId: entry.patternId || null,
|
||||
args: entry.args || [],
|
||||
messageText: entry.messageText || null,
|
||||
status: entry.status,
|
||||
recId: entry.recId ? String(entry.recId) : null,
|
||||
errorMessage: entry.errorMessage || null,
|
||||
},
|
||||
});
|
||||
} catch (err: any) {
|
||||
this.logger.error(`[SMS Log Save Failed]: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query paginated SMS Logs with Search, Filter and Sorting
|
||||
*/
|
||||
async getSmsLogs(query: SmsLogQuery = {}) {
|
||||
const page = Math.max(1, Number(query.page) || 1);
|
||||
const limit = Math.max(1, Math.min(100, Number(query.limit) || 15));
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: Prisma.SmsLogWhereInput = {};
|
||||
|
||||
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' } },
|
||||
];
|
||||
}
|
||||
|
||||
if (query.type && query.type !== 'ALL') {
|
||||
where.type = query.type;
|
||||
}
|
||||
|
||||
if (query.status && query.status !== 'ALL') {
|
||||
where.status = query.status;
|
||||
}
|
||||
|
||||
const sortField = query.sortBy || 'createdAt';
|
||||
const sortOrder = query.sortOrder === 'asc' ? 'asc' : 'desc';
|
||||
|
||||
const [logs, total, totalSuccess, totalFailed] = await Promise.all([
|
||||
this.prisma.smsLog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortOrder },
|
||||
}),
|
||||
this.prisma.smsLog.count({ where }),
|
||||
this.prisma.smsLog.count({ where: { status: 'SUCCESS' } }),
|
||||
this.prisma.smsLog.count({ where: { status: 'FAILED' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
logs,
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
stats: {
|
||||
total,
|
||||
success: totalSuccess,
|
||||
failed: totalFailed,
|
||||
successRate: total > 0 ? Math.round((totalSuccess / total) * 100) : 100,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete specific SMS log entry
|
||||
*/
|
||||
async deleteSmsLog(id: string) {
|
||||
return this.prisma.smsLog.delete({ where: { id } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all SMS logs
|
||||
*/
|
||||
async clearAllSmsLogs() {
|
||||
return this.prisma.smsLog.deleteMany();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse XML response for GetSharedServiceBody into structured pattern array
|
||||
*/
|
||||
@@ -241,7 +355,6 @@ export class SmsService {
|
||||
const code = match ? parseInt(match[1], 10) : 0;
|
||||
|
||||
if (code > 0) {
|
||||
// Store locally
|
||||
await this.saveLocalPattern({
|
||||
id: code,
|
||||
title,
|
||||
@@ -369,18 +482,32 @@ export class SmsService {
|
||||
*/
|
||||
async sendPatternSms(options: SendPatternSmsOptions): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
const msgType = options.type || 'GENERIC_PATTERN';
|
||||
|
||||
if (!config.enabled) {
|
||||
this.logger.warn(`[SMS Disabled] SMS dispatch skipped for ${options.to}`);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک از پنل ادمین غیرفعال شده است.',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
this.logger.error(
|
||||
`[SMS MISCONFIGURED] MELIPAYAMAK username/password is not configured! ` +
|
||||
`SMS to ${options.to} (Pattern: ${options.bodyId}) was NOT sent. ` +
|
||||
`Please configure MeliPayamak settings in Admin Panel.`,
|
||||
);
|
||||
const err = 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.';
|
||||
this.logger.error(`[SMS MISCONFIGURED] ${err}`);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
errorMessage: err,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -405,7 +532,7 @@ export class SmsService {
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('end', () => {
|
||||
res.on('end', async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
const val = json.Value ?? 0;
|
||||
@@ -413,24 +540,54 @@ export class SmsService {
|
||||
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 {
|
||||
this.logger.error(
|
||||
`[SMS Error] Failed sending pattern SMS to ${options.to}. Code: ${val}`,
|
||||
);
|
||||
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 {
|
||||
} 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', (err) => {
|
||||
this.logger.error(
|
||||
`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`,
|
||||
);
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -446,10 +603,16 @@ export class SmsService {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.',
|
||||
};
|
||||
const msg = 'نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.';
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: testPatternId,
|
||||
args: testArgs,
|
||||
status: 'FAILED',
|
||||
errorMessage: msg,
|
||||
});
|
||||
return { success: false, message: msg };
|
||||
}
|
||||
|
||||
const bodyId = testPatternId || config.otpBodyId || 508079;
|
||||
@@ -476,38 +639,68 @@ export class SmsService {
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('end', () => {
|
||||
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}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: bodyId,
|
||||
args,
|
||||
status: 'FAILED',
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({
|
||||
success: false,
|
||||
message: `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`,
|
||||
message: errMsg,
|
||||
rawResponse: json,
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `پاسخ نامعتبر از سرور ملی پیامک: ${data || err.message}`,
|
||||
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', (err) => {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `خطای برقراری ارتباط با وبسرویس ملی پیامک: ${err.message}`,
|
||||
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.write(payload);
|
||||
@@ -524,6 +717,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.otpBodyId,
|
||||
args: [otpCode],
|
||||
type: 'OTP',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -540,6 +734,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.orderBodyId,
|
||||
args: [orderNumber, amount],
|
||||
type: 'ORDER_CONFIRMATION',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -556,6 +751,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.shippingBodyId,
|
||||
args: [orderNumber, trackingCode],
|
||||
type: 'SHIPPING_TRACKING',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -571,6 +767,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.b2bBodyId,
|
||||
args: [applicantName],
|
||||
type: 'B2B_NOTIFICATION',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -588,6 +785,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.petCareBodyId,
|
||||
args: [petName, reminderType],
|
||||
type: 'PET_CARE_REMINDER',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -596,8 +794,23 @@ export class SmsService {
|
||||
*/
|
||||
async sendSms(phone: string, message: string): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
if (!config.enabled) return false;
|
||||
if (!config.enabled) {
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
messageText: message,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک غیرفعال است.',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
messageText: message,
|
||||
status: 'SUCCESS',
|
||||
});
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user