feat(admin,sms): add dynamic sms settings management and live tester in admin panel
This commit is contained in:
1 parent
8992060cb7
commit
09fd339e89
7 files changed
+755
-40
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Users, ShoppingCart, Tag, Settings, LogOut, TrendingUp, FolderTree, FileText, BookOpen, Heart, Package, LayoutDashboard, Languages, Image, Video, PhoneCall, Sparkles, MessageSquareQuote, FlaskConical, Building2, Globe, DollarSign, Sliders } from 'lucide-react';
|
||||
import { Users, ShoppingCart, Tag, Settings, LogOut, TrendingUp, FolderTree, FileText, BookOpen, Heart, Package, LayoutDashboard, Languages, Image, Video, PhoneCall, Sparkles, MessageSquareQuote, FlaskConical, Building2, Globe, DollarSign, Sliders, MessageSquare } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
@@ -47,6 +47,7 @@ const menuGroups = [
|
||||
title: 'سیستم و تنظیمات',
|
||||
items: [
|
||||
{ icon: Settings, label: 'تنظیمات کلی', path: '/settings' },
|
||||
{ icon: MessageSquare, label: 'تنظیمات پیامک', path: '/settings/sms' },
|
||||
{ icon: Globe, label: 'تنظیمات سئو', path: '/settings/seo' },
|
||||
{ icon: DollarSign, label: 'تنظیمات مالی & ارسال', path: '/settings/financial' },
|
||||
{ icon: Sliders, label: 'تنظیمات سیستمی', path: '/settings/system' },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Settings as SettingsIcon, Save, Truck, ShieldAlert, Percent, AlertCircle, CreditCard, Share2 } from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Settings as SettingsIcon, Save, Truck, ShieldAlert, Percent, AlertCircle, CreditCard, Share2, MessageSquare } from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
@@ -106,6 +107,15 @@ export default function Settings() {
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">مدیریت پارامترهای اصلی و سیستمی کانینا</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Link
|
||||
to="/settings/sms"
|
||||
className="bg-purple-50 text-purple-700 hover:bg-purple-100 border border-purple-200 text-xs font-bold px-4 py-2.5 rounded-xl transition-all flex items-center gap-2"
|
||||
>
|
||||
<MessageSquare className="w-4 h-4 text-purple-600" />
|
||||
تنظیمات درگاه پیامک (MeliPayamak)
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
MessageSquare,
|
||||
Save,
|
||||
Send,
|
||||
ShieldCheck,
|
||||
KeyRound,
|
||||
User,
|
||||
Hash,
|
||||
HelpCircle,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Sparkles,
|
||||
Smartphone,
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
|
||||
interface SmsConfigState {
|
||||
enabled: boolean;
|
||||
username: string;
|
||||
password: string;
|
||||
fromNumber: string;
|
||||
otpBodyId: number | string;
|
||||
orderBodyId: number | string;
|
||||
shippingBodyId: number | string;
|
||||
b2bBodyId: number | string;
|
||||
petCareBodyId: number | string;
|
||||
}
|
||||
|
||||
export default function SmsSettingsPage() {
|
||||
const [config, setConfig] = useState<SmsConfigState>({
|
||||
enabled: true,
|
||||
username: '',
|
||||
password: '',
|
||||
fromNumber: '',
|
||||
otpBodyId: '508079',
|
||||
orderBodyId: '508081',
|
||||
shippingBodyId: '508082',
|
||||
b2bBodyId: '508083',
|
||||
petCareBodyId: '0',
|
||||
});
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
// Test SMS State
|
||||
const [testPhone, setTestPhone] = useState('');
|
||||
const [testPatternType, setTestPatternType] = useState('otp');
|
||||
const [customPatternId, setCustomPatternId] = useState('');
|
||||
const [testArg1, setTestArg1] = useState('123456');
|
||||
const [testArg2, setTestArg2] = useState('150000');
|
||||
const [isSendingTest, setIsSendingTest] = useState(false);
|
||||
const [testResult, setTestResult] = useState<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isSubscribed = true;
|
||||
api
|
||||
.get('/settings/sms')
|
||||
.then((res) => {
|
||||
if (!isSubscribed) return;
|
||||
const data = res.data?.data || res.data;
|
||||
if (data) {
|
||||
setConfig({
|
||||
enabled: data.enabled !== undefined ? Boolean(data.enabled) : true,
|
||||
username: data.username || '',
|
||||
password: data.password || '',
|
||||
fromNumber: data.fromNumber || '',
|
||||
otpBodyId: data.otpBodyId || '508079',
|
||||
orderBodyId: data.orderBodyId || '508081',
|
||||
shippingBodyId: data.shippingBodyId || '508082',
|
||||
b2bBodyId: data.b2bBodyId || '508083',
|
||||
petCareBodyId: data.petCareBodyId || '0',
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Failed to fetch SMS settings:', err);
|
||||
toast.error('خطا در دریافت تنظیمات پیامک');
|
||||
})
|
||||
.finally(() => {
|
||||
if (isSubscribed) setIsLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
isSubscribed = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
setIsSaving(true);
|
||||
const payload = {
|
||||
enabled: Boolean(config.enabled),
|
||||
username: config.username.trim(),
|
||||
password: config.password.trim(),
|
||||
fromNumber: config.fromNumber.trim(),
|
||||
otpBodyId: Number(config.otpBodyId) || 0,
|
||||
orderBodyId: Number(config.orderBodyId) || 0,
|
||||
shippingBodyId: Number(config.shippingBodyId) || 0,
|
||||
b2bBodyId: Number(config.b2bBodyId) || 0,
|
||||
petCareBodyId: Number(config.petCareBodyId) || 0,
|
||||
};
|
||||
|
||||
await api.patch('/settings/sms', payload);
|
||||
toast.success('تنظیمات درگاه پیامک با موفقیت در دیتابیس ذخیره شد');
|
||||
} catch (err) {
|
||||
console.error('Failed to update SMS settings:', err);
|
||||
toast.error('خطا در ذخیرهسازی تنظیمات پیامک');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendTestSms = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!testPhone) {
|
||||
toast.error('لطفاً شماره موبایل مقصد برای تست را وارد کنید');
|
||||
return;
|
||||
}
|
||||
|
||||
let patternId = Number(config.otpBodyId);
|
||||
let args = [testArg1];
|
||||
|
||||
if (testPatternType === 'order') {
|
||||
patternId = Number(config.orderBodyId);
|
||||
args = ['ORD-9988', testArg2 || '150000'];
|
||||
} else if (testPatternType === 'shipping') {
|
||||
patternId = Number(config.shippingBodyId);
|
||||
args = ['ORD-9988', 'POST-123456789'];
|
||||
} else if (testPatternType === 'custom') {
|
||||
patternId = Number(customPatternId);
|
||||
args = [testArg1, testArg2].filter(Boolean);
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSendingTest(true);
|
||||
setTestResult(null);
|
||||
|
||||
const response = await api.post('/settings/sms/test', {
|
||||
phone: testPhone.trim(),
|
||||
patternId,
|
||||
args,
|
||||
});
|
||||
|
||||
const resData = response.data?.data || response.data;
|
||||
setTestResult({
|
||||
success: resData.success,
|
||||
message: resData.message || (resData.success ? 'ارسال موفق بود' : 'خطا در ارسال'),
|
||||
});
|
||||
|
||||
if (resData.success) {
|
||||
toast.success('پیامک آزمایشی با موفقیت به شماره مقصد ارسال شد');
|
||||
} else {
|
||||
toast.error(resData.message || 'خطا در ارسال پیامک آزمایشی');
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to dispatch test SMS:', err);
|
||||
const errMsg = err.response?.data?.message || 'خطای شبکه یا سرور در ارسال پیامک آزمایشی';
|
||||
setTestResult({
|
||||
success: false,
|
||||
message: errMsg,
|
||||
});
|
||||
toast.error(errMsg);
|
||||
} finally {
|
||||
setIsSendingTest(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<MessageSquare className="w-6 h-6 text-purple-600" />
|
||||
تنظیمات درگاه پیامک (MeliPayamak Gateway)
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">
|
||||
مدیریت کامل مشخصات اتصال به سامانه پیامکی، شناسههای پترن خدماتی و ابزار ارسال آزمایشی
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center p-12">
|
||||
<Spinner size="lg" className="text-purple-600" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Main Settings Form (2 cols on large) */}
|
||||
<form onSubmit={handleSave} className="lg:col-span-2 space-y-6">
|
||||
{/* Status & Credentials Card */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 space-y-6">
|
||||
<h3 className="text-lg font-bold text-gray-900 border-b border-gray-100 pb-4 flex items-center gap-2">
|
||||
<ShieldCheck className="w-5 h-5 text-purple-600" />
|
||||
وضعیت سامانه و مشخصات حساب کاربری
|
||||
</h3>
|
||||
|
||||
{/* Master Enabled Switch */}
|
||||
<div className="flex items-center justify-between p-4 bg-purple-50 rounded-xl border border-purple-100">
|
||||
<div>
|
||||
<h4 className="font-bold text-gray-900 text-sm">فعال بودن ارسال پیامک در سراسر سیستم</h4>
|
||||
<p className="text-xs text-gray-500 mt-0.5">
|
||||
در صورت غیرفعال بودن، پیامکهای ثبت سفارش و OTP به صورت واقعی ارسال نخواهند شد.
|
||||
</p>
|
||||
</div>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="sr-only peer"
|
||||
checked={config.enabled}
|
||||
onChange={(e) => setConfig({ ...config, enabled: e.target.checked })}
|
||||
/>
|
||||
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Username & Password */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1 flex items-center gap-1.5">
|
||||
<User className="w-3.5 h-3.5 text-gray-500" />
|
||||
نام کاربری یا شماره پنل ملی پیامک (Username) *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={config.username}
|
||||
onChange={(e) => setConfig({ ...config, username: e.target.value })}
|
||||
placeholder="مثلاً: 09364100228"
|
||||
className="w-full border border-gray-200 rounded-xl p-3 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500 mt-1">شماره همراه یا نام کاربری ورود به پنل melipayamak.com</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1 flex items-center gap-1.5">
|
||||
<KeyRound className="w-3.5 h-3.5 text-gray-500" />
|
||||
کلمه عبور یا کلید API (Password / API Key) *
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
required
|
||||
value={config.password}
|
||||
onChange={(e) => setConfig({ ...config, password: e.target.value })}
|
||||
placeholder="••••••••••••"
|
||||
className="w-full border border-gray-200 rounded-xl p-3 pr-10 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 p-1"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-500 mt-1">رمز عبور اختصاصی پنل یا کلید وبسرویس</p>
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1 flex items-center gap-1.5">
|
||||
<Smartphone className="w-3.5 h-3.5 text-gray-500" />
|
||||
شماره خط فرستنده پیامک (From Number - اختیاری)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={config.fromNumber}
|
||||
onChange={(e) => setConfig({ ...config, fromNumber: e.target.value })}
|
||||
placeholder="مثلاً: 50004... (در پترن اشتراکی نیازی نیست)"
|
||||
className="w-full border border-gray-200 rounded-xl p-3 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500 mt-1">
|
||||
در ارسال پترن خدماتی، ملی پیامک به صورت خودکار از خط اشتراکی استفاده میکند و پر کردن این فیلد اختیاری است.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pattern IDs Card */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 space-y-6">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
|
||||
<Hash className="w-5 h-5 text-indigo-600" />
|
||||
شناسههای قالب و الگوهای خدماتی (Pattern Body IDs)
|
||||
</h3>
|
||||
<span className="text-[11px] bg-indigo-50 text-indigo-700 font-bold px-2.5 py-1 rounded-full flex items-center gap-1">
|
||||
<Sparkles className="w-3 h-3" /> عبور از بلکلیست مخابرات
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* OTP Pattern */}
|
||||
<div className="p-4 bg-gray-50 rounded-xl border border-gray-200 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-xs font-bold text-gray-900">کد پترن ورود / ثبتنام (OTP)</label>
|
||||
<span className="text-[10px] text-gray-500 font-mono bg-white px-2 py-0.5 rounded border border-gray-200">
|
||||
متغیر: {'{0}'}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
value={config.otpBodyId}
|
||||
onChange={(e) => setConfig({ ...config, otpBodyId: e.target.value })}
|
||||
placeholder="508079"
|
||||
className="w-full border border-gray-200 rounded-lg p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500">کد تایید اعتبار ورود و فراموشی رمز کاربران</p>
|
||||
</div>
|
||||
|
||||
{/* Order Confirmation Pattern */}
|
||||
<div className="p-4 bg-gray-50 rounded-xl border border-gray-200 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-xs font-bold text-gray-900">کد پترن ثبت و تایید سفارش</label>
|
||||
<span className="text-[10px] text-gray-500 font-mono bg-white px-2 py-0.5 rounded border border-gray-200">
|
||||
متغیرها: {'{0};{1}'}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
value={config.orderBodyId}
|
||||
onChange={(e) => setConfig({ ...config, orderBodyId: e.target.value })}
|
||||
placeholder="508081"
|
||||
className="w-full border border-gray-200 rounded-lg p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500">ارسال شماره فاکتور و مبلغ به خریدار پس از پرداخت</p>
|
||||
</div>
|
||||
|
||||
{/* Shipping Tracking Pattern */}
|
||||
<div className="p-4 bg-gray-50 rounded-xl border border-gray-200 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-xs font-bold text-gray-900">کد پترن رهگیری پستی و ارسال</label>
|
||||
<span className="text-[10px] text-gray-500 font-mono bg-white px-2 py-0.5 rounded border border-gray-200">
|
||||
متغیرها: {'{0};{1}'}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
value={config.shippingBodyId}
|
||||
onChange={(e) => setConfig({ ...config, shippingBodyId: e.target.value })}
|
||||
placeholder="508082"
|
||||
className="w-full border border-gray-200 rounded-lg p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500">ارسال بارکد ۲۴ رقمی پست به مشتری هنگام تحویل مرسوله</p>
|
||||
</div>
|
||||
|
||||
{/* B2B Pattern */}
|
||||
<div className="p-4 bg-gray-50 rounded-xl border border-gray-200 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-xs font-bold text-gray-900">کد پترن درخواست همکاری B2B</label>
|
||||
<span className="text-[10px] text-gray-500 font-mono bg-white px-2 py-0.5 rounded border border-gray-200">
|
||||
متغیر: {'{0}'}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
value={config.b2bBodyId}
|
||||
onChange={(e) => setConfig({ ...config, b2bBodyId: e.target.value })}
|
||||
placeholder="508083"
|
||||
className="w-full border border-gray-200 rounded-lg p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500">اطلاعرسانی ثبت یا تایید حساب متقاضیان عمدهفروشی</p>
|
||||
</div>
|
||||
|
||||
{/* Pet Care Reminder Pattern */}
|
||||
<div className="p-4 bg-gray-50 rounded-xl border border-gray-200 space-y-2 md:col-span-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-xs font-bold text-gray-900">کد پترن یادآور سلامت و واکسیناسیون پت</label>
|
||||
<span className="text-[10px] text-gray-500 font-mono bg-white px-2 py-0.5 rounded border border-gray-200">
|
||||
متغیرها: {'{0};{1}'}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
value={config.petCareBodyId}
|
||||
onChange={(e) => setConfig({ ...config, petCareBodyId: e.target.value })}
|
||||
placeholder="0 (در صورت تعریف نکردن 0 بگذارید)"
|
||||
className="w-full border border-gray-200 rounded-lg p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-sm font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500">یادآور نوبت واکسن، انگلزدایی یا مصرف مکمل پت برای سرپرست</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex justify-end pt-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSaving}
|
||||
className="bg-purple-600 hover:bg-purple-700 text-white font-bold py-3.5 px-8 rounded-xl transition-all flex items-center gap-2 shadow-lg shadow-purple-200 disabled:opacity-50"
|
||||
>
|
||||
{isSaving ? <Spinner size="sm" /> : <Save className="w-5 h-5" />}
|
||||
ذخیره تنظیمات درگاه پیامک
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Test SMS Sidebar (1 col on large) */}
|
||||
<div className="space-y-6">
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 space-y-5">
|
||||
<div className="flex items-center gap-2 border-b border-gray-100 pb-3">
|
||||
<Send className="w-5 h-5 text-blue-600" />
|
||||
<h3 className="text-base font-bold text-gray-900">تست زنده ارسال پیامک</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-500 leading-relaxed">
|
||||
برای اطمینان از صحت نام کاربری، رمز عبور و شناسههای پترن تایید شده در ملی پیامک، یک پیامک آزمایشی به شماره خود ارسال کنید.
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSendTestSms} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">شماره موبایل مقصد *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={testPhone}
|
||||
onChange={(e) => setTestPhone(e.target.value)}
|
||||
placeholder="0912..."
|
||||
className="w-full border border-gray-200 rounded-xl p-3 outline-none focus:ring-2 focus:ring-blue-500 text-sm font-mono font-bold"
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">نوع پترن برای تست</label>
|
||||
<select
|
||||
value={testPatternType}
|
||||
onChange={(e) => setTestPatternType(e.target.value)}
|
||||
className="w-full border border-gray-200 rounded-xl p-2.5 outline-none focus:ring-2 focus:ring-blue-500 text-xs font-bold bg-gray-50"
|
||||
>
|
||||
<option value="otp">کد تایید OTP (BodyId: {config.otpBodyId || '508079'})</option>
|
||||
<option value="order">تایید سفارش (BodyId: {config.orderBodyId || '508081'})</option>
|
||||
<option value="shipping">رهگیری پستی (BodyId: {config.shippingBodyId || '508082'})</option>
|
||||
<option value="custom">پترن سفارشی با کد دلخواه</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{testPatternType === 'custom' && (
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">شناسه پترن دلخواه (BodyId)</label>
|
||||
<input
|
||||
type="number"
|
||||
required
|
||||
value={customPatternId}
|
||||
onChange={(e) => setCustomPatternId(e.target.value)}
|
||||
placeholder="مثلاً: 508079"
|
||||
className="w-full border border-gray-200 rounded-xl p-2.5 outline-none focus:ring-2 focus:ring-blue-500 text-xs font-mono font-bold"
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">متغیر تستی ۱ (کد یا متن)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={testArg1}
|
||||
onChange={(e) => setTestArg1(e.target.value)}
|
||||
placeholder="123456"
|
||||
className="w-full border border-gray-200 rounded-xl p-2.5 outline-none focus:ring-2 focus:ring-blue-500 text-xs font-mono font-bold"
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{testResult && (
|
||||
<div
|
||||
className={`p-3 rounded-xl border text-xs flex items-start gap-2 ${
|
||||
testResult.success
|
||||
? 'bg-emerald-50 border-emerald-200 text-emerald-800'
|
||||
: 'bg-rose-50 border-rose-200 text-rose-800'
|
||||
}`}
|
||||
>
|
||||
{testResult.success ? (
|
||||
<CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600 mt-0.5" />
|
||||
) : (
|
||||
<AlertCircle className="w-4 h-4 shrink-0 text-rose-600 mt-0.5" />
|
||||
)}
|
||||
<span className="font-medium leading-tight">{testResult.message}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSendingTest}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded-xl transition-all flex items-center justify-center gap-2 shadow-md shadow-blue-200 disabled:opacity-50 text-xs"
|
||||
>
|
||||
{isSendingTest ? <Spinner size="sm" /> : <Send className="w-4 h-4" />}
|
||||
ارسال پیامک تستی
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Documentation Help Card */}
|
||||
<div className="bg-slate-50 p-5 rounded-2xl border border-slate-200 space-y-3">
|
||||
<h4 className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
|
||||
<HelpCircle className="w-4 h-4 text-purple-600" />
|
||||
راهنمای پترنهای ملی پیامک
|
||||
</h4>
|
||||
<p className="text-[11px] text-slate-600 leading-relaxed">
|
||||
متن پترنها در پنل ملی پیامک باید از بخش «ارسال بر اساس پترن» ثبت شده و به تایید ناظر برسد. متغیرها به صورت <code className="bg-white px-1 py-0.5 rounded text-purple-700 font-mono font-bold">{'{0}'}</code> و <code className="bg-white px-1 py-0.5 rounded text-purple-700 font-mono font-bold">{'{1}'}</code> تعریف میشوند.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ const B2BManager = lazy(() => import('../pages/B2BManager'));
|
||||
const SeoSettingsPage = lazy(() => import('../pages/SeoSettingsPage'));
|
||||
const FinancialSettingsPage = lazy(() => import('../pages/FinancialSettingsPage'));
|
||||
const SystemSettingsPage = lazy(() => import('../pages/SystemSettingsPage'));
|
||||
const SmsSettingsPage = lazy(() => import('../pages/SmsSettingsPage'));
|
||||
|
||||
export interface AdminRouteConfig {
|
||||
path: string;
|
||||
@@ -58,6 +59,7 @@ export const router = createBrowserRouter([
|
||||
{ path: 'orders/*', element: <Orders /> },
|
||||
{ path: 'coupons/*', element: <Coupons /> },
|
||||
{ path: 'settings', element: <Settings /> },
|
||||
{ path: 'settings/sms', element: <SmsSettingsPage /> },
|
||||
{ path: 'settings/seo', element: <SeoSettingsPage /> },
|
||||
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
|
||||
{ path: 'settings/system', element: <SystemSettingsPage /> },
|
||||
|
||||
Reference in new issue
Block a user