feat(admin,sms): add dynamic sms settings management and live tester in admin panel

This commit is contained in:
parsa aghaei committed 2026-08-16 11:48:40 +03:30
1 parent 8992060cb7
commit 09fd339e89
7 files changed
+755 -40

No files matched your search

+157 -36
View File
@@ -1,5 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';
import * as https from 'https';
import { PrismaService } from '../../prisma/prisma.service';
export interface SendPatternSmsOptions {
to: string;
@@ -7,34 +8,90 @@ export interface SendPatternSmsOptions {
args: string[]; // Dynamic variables inside pattern
}
export interface SmsConfig {
enabled: boolean;
username: string;
password: string;
fromNumber?: string;
otpBodyId: number;
orderBodyId: number;
shippingBodyId: number;
b2bBodyId: number;
petCareBodyId: number;
}
interface MeliPayamakResponse {
Value?: number;
RetStatus?: number;
StrRetStatus?: string;
}
@Injectable()
export class SmsService {
private readonly logger = new Logger(SmsService.name);
private readonly username = process.env.MELIPAYAMAK_USERNAME || '9364100228';
private readonly password = process.env.MELIPAYAMAK_PASSWORD || '';
constructor(private readonly prisma: PrismaService) {}
/**
* Get active SMS configuration from database (fallback to .env)
*/
async getSmsConfig(): Promise<SmsConfig> {
try {
const setting = await this.prisma.setting.findFirst({
where: { category: 'sms' },
});
const dbConfig = (setting?.value as Record<string, any>) || {};
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'),
};
} catch {
return {
enabled: true,
username: process.env.MELIPAYAMAK_USERNAME || '9364100228',
password: process.env.MELIPAYAMAK_PASSWORD || '',
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'),
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || '508083'),
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0'),
};
}
}
/**
* Send Pattern SMS using MeliPayamak Shared Service Line (Bypasses Blacklist)
*/
async sendPatternSms(options: SendPatternSmsOptions): Promise<boolean> {
if (!this.username || !this.password) {
const config = await this.getSmsConfig();
if (!config.enabled) {
this.logger.warn(`[SMS Disabled] SMS dispatch skipped for ${options.to}`);
return false;
}
if (!config.username || !config.password) {
this.logger.error(
`[SMS MISCONFIGURED] MELIPAYAMAK_PASSWORD is not set! ` +
`[SMS MISCONFIGURED] MELIPAYAMAK username/password is not configured! ` +
`SMS to ${options.to} (Pattern: ${options.bodyId}) was NOT sent. ` +
`Set MELIPAYAMAK_USERNAME and MELIPAYAMAK_PASSWORD environment variables.`,
`Please configure MeliPayamak settings in Admin Panel.`,
);
return false;
}
return new Promise((resolve) => {
const payload = JSON.stringify({
username: this.username,
password: this.password,
username: config.username,
password: config.password,
text: options.args.join(';'),
to: options.to,
bodyId: options.bodyId,
@@ -87,72 +144,136 @@ export class SmsService {
}
/**
* Send OTP Verification Code (Pattern 508079)
* Test SMS Dispatch from Admin Panel
*/
async testSms(targetPhone: string, testPatternId?: number, testArgs?: string[]): Promise<{ success: boolean; message: string; rawResponse?: any }> {
const config = await this.getSmsConfig();
if (!config.username || !config.password) {
return {
success: false,
message: 'نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.',
};
}
const bodyId = testPatternId || config.otpBodyId || 508079;
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(';'),
to: targetPhone,
bodyId: bodyId,
});
const req = https.request(
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
},
},
(res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
try {
const json = JSON.parse(data) as MeliPayamakResponse;
const val = json.Value ?? 0;
if (json && (val > 15 || json.RetStatus === 1)) {
resolve({
success: true,
message: `پیامک تستی پترن با موفقیت ارسال شد (شناسه پیگیری ملی پیامک: ${val})`,
rawResponse: json,
});
} else {
resolve({
success: false,
message: `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`,
rawResponse: json,
});
}
} catch (err: any) {
resolve({
success: false,
message: `پاسخ نامعتبر از سرور ملی پیامک: ${data || err.message}`,
});
}
});
},
);
req.on('error', (err) => {
resolve({
success: false,
message: `خطای برقراری ارتباط با وب‌سرویس ملی پیامک: ${err.message}`,
});
});
req.write(payload);
req.end();
});
}
/**
* Send OTP Verification Code
*/
async sendOtp(phone: string, otpCode: string): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_OTP_BODY_ID || '508079',
10,
);
const config = await this.getSmsConfig();
return this.sendPatternSms({
to: phone,
bodyId,
bodyId: config.otpBodyId,
args: [otpCode],
});
}
/**
* Send Order Confirmation SMS (Pattern 508081)
* Send Order Confirmation SMS
*/
async sendOrderConfirmation(
phone: string,
orderNumber: string,
amount: string,
): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_ORDER_BODY_ID || '508081',
10,
);
const config = await this.getSmsConfig();
return this.sendPatternSms({
to: phone,
bodyId,
bodyId: config.orderBodyId,
args: [orderNumber, amount],
});
}
/**
* Send Shipping Status SMS with Tracking Code (Pattern 508082)
* Send Shipping Status SMS with Tracking Code
*/
async sendShippingNotification(
phone: string,
orderNumber: string,
trackingCode: string,
): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '508082',
10,
);
const config = await this.getSmsConfig();
return this.sendPatternSms({
to: phone,
bodyId,
bodyId: config.shippingBodyId,
args: [orderNumber, trackingCode],
});
}
/**
* Send B2B Application Notification SMS (Pattern 508083)
* Send B2B Application Notification SMS
*/
async sendB2bNotification(
phone: string,
applicantName: string,
): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_B2B_BODY_ID || '508083',
10,
);
const config = await this.getSmsConfig();
return this.sendPatternSms({
to: phone,
bodyId,
bodyId: config.b2bBodyId,
args: [applicantName],
});
}
@@ -165,13 +286,11 @@ export class SmsService {
petName: string,
reminderType: string,
): Promise<boolean> {
const bodyId = parseInt(
process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0',
10,
);
const config = await this.getSmsConfig();
if (!config.petCareBodyId) return false;
return this.sendPatternSms({
to: phone,
bodyId,
bodyId: config.petCareBodyId,
args: [petName, reminderType],
});
}
@@ -180,6 +299,8 @@ export class SmsService {
* Generic text SMS dispatch
*/
async sendSms(phone: string, message: string): Promise<boolean> {
const config = await this.getSmsConfig();
if (!config.enabled) return false;
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
return Promise.resolve(true);
}
+35 -1
View File
@@ -1,6 +1,7 @@
import {
Controller,
Get,
Post,
Patch,
Put,
Delete,
@@ -20,7 +21,7 @@ import {
ApiOkResponse,
} from '@nestjs/swagger';
@ApiTags('Settings - تنظیمات متون پویا، تنظیمات سئو، مالی و سیستم')
@ApiTags('Settings - تنظیمات متون پویا، تنظیمات سئو، مالی، سیستم و پیامک')
@Controller('settings')
export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
@@ -125,4 +126,37 @@ export class SettingsController {
updateSystemSettings(@Body() body: Prisma.InputJsonValue) {
return this.settingsService.updateCategorySetting('system', body);
}
// SMS Gateway Settings
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Get('sms')
@ApiOperation({ summary: 'دریافت تنظیمات درگاه پیامک و کدهای پترن' })
getSmsSettings() {
return this.settingsService.getSmsSettings();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Patch('sms')
@ApiOperation({ summary: 'به‌روزرسانی تنظیمات درگاه پیامک و کدهای پترن' })
updateSmsSettings(@Body() body: Prisma.InputJsonValue) {
return this.settingsService.updateSmsSettings(body);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Post('sms/test')
@ApiOperation({ summary: 'ارسال پیامک آزمایشی پترن به شماره دلخواه' })
testSms(
@Body('phone') phone: string,
@Body('patternId') patternId?: number,
@Body('args') args?: string[],
) {
return this.settingsService.testSms(phone, patternId, args);
}
}
+23 -1
View File
@@ -1,6 +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';
export class ScientificTermData {
term?: string;
@@ -10,7 +11,10 @@ export class ScientificTermData {
@Injectable()
export class SettingsService {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private smsService: SmsService,
) {}
async getUiTexts() {
const [uiTexts, settings] = await Promise.all([
@@ -82,4 +86,22 @@ export class SettingsService {
create: { key, category, value },
});
}
async getSmsSettings() {
return this.smsService.getSmsConfig();
}
async updateSmsSettings(value: Prisma.InputJsonValue) {
const key = 'sms_config';
return this.prisma.setting.upsert({
where: { key },
update: { category: 'sms', value },
create: { key, category: 'sms', value },
});
}
async testSms(targetPhone: string, patternId?: number, args?: string[]) {
return this.smsService.testSms(targetPhone, patternId, args);
}
}