feat(notifications & advisors): implement unified notification queue, SMTP config, and catalog advisor contact flow
Deploy Canina / deploy (push) Successful in 8m17s

This commit is contained in:
devops committed 2026-11-07 07:41:24 +00:00
1 parent d881dc491e
commit fae4b570f9
20 files changed
+3445 -8

No files matched your search

@@ -1,5 +1,6 @@
import {
Activity,
Bell,
CheckSquare,
BookOpen,
Building2,
@@ -170,6 +171,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: Users, label: 'مدیریت کاربران', path: '/users' },
{ icon: Heart, label: 'پرونده پت‌ها (همدم‌ها)', path: '/pets' },
{ icon: MessageSquare, label: 'تیکت‌ها و مشاوره تخصصی', path: '/tickets' },
{ icon: PhoneCall, label: 'مشاوران و لیدهای تماس', path: '/advisors' },
{ icon: Building2, label: 'پرتال B2B و همکاران', path: '/b2b' },
{ icon: PhoneCall, label: 'اطلاعات تماس و پیام‌ها', path: '/contact' },
],
@@ -201,6 +203,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: CreditCard, label: 'روش‌های پرداخت و زیبال', path: '/settings/payment-methods' },
{ icon: Truck, label: 'تنظیمات ارسال و کرایه', path: '/settings/shipping' },
{ icon: DollarSign, label: 'تنظیمات مالی و مالیات', path: '/settings/financial' },
{ icon: Bell, label: 'مرکز اطلاع‌رسانی (ایمیل و صف)', path: '/settings/notifications' },
{ icon: MessageSquare, label: 'درگاه پیامک (MeliPayamak)', path: '/settings/sms' },
{ icon: ShieldCheck, label: 'گواهی SSL و امنیت', path: '/settings/ssl' },
{ icon: Key, label: 'کلیدهای دسترسی (API Keys)', path: '/settings/api-keys' },
@@ -0,0 +1,512 @@
import React, { useState, useEffect } from 'react';
import {
Users,
UserPlus,
PhoneCall,
CheckCircle2,
Clock,
Trash2,
Edit2,
Star,
Search,
Package,
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import Spinner from '../components/ui/Spinner';
import Modal from '../components/ui/Modal';
import api from '../services/api';
interface Advisor {
id: string;
name: string;
phone: string;
title?: string;
isDefault: boolean;
isActive: boolean;
productsCount: number;
leadsCount: number;
}
interface Lead {
id: string;
firstName: string;
lastName: string;
phone: string;
status: string;
notes?: string;
createdAt: string;
advisor?: { id: string; name: string; phone: string; title?: string };
product?: { id: string; nameFa: string; nameEn: string; slug: string };
}
export default function AdvisorsManagementPage() {
const [activeTab, setActiveTab] = useState<'leads' | 'advisors'>('leads');
const [isLoading, setIsLoading] = useState(true);
// Advisors State
const [advisors, setAdvisors] = useState<Advisor[]>([]);
const [isAdvisorModalOpen, setIsAdvisorModalOpen] = useState(false);
const [editingAdvisor, setEditingAdvisor] = useState<Advisor | null>(null);
const [advisorForm, setAdvisorForm] = useState({
name: '',
phone: '',
title: '',
isDefault: false,
isActive: true,
});
// Leads State
const [leads, setLeads] = useState<Lead[]>([]);
const [leadStats, setLeadStats] = useState({ total: 0, pending: 0, contacted: 0, cancelled: 0 });
const [leadFilterStatus, setLeadFilterStatus] = useState<string>('ALL');
const [searchTerm, setSearchTerm] = useState('');
const loadAdvisors = async () => {
try {
const res = await api.get('/admin/advisors');
if (res.data?.success) {
setAdvisors(res.data.data);
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت لیست مشاوران');
}
};
const loadLeads = async () => {
try {
setIsLoading(true);
const res = await api.get(`/admin/leads?status=${leadFilterStatus}&search=${encodeURIComponent(searchTerm)}`);
if (res.data?.success) {
setLeads(res.data.data.items);
if (res.data.data.stats) setLeadStats(res.data.data.stats);
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت لیست درخواست‌های تماس');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadAdvisors();
loadLeads();
}, [leadFilterStatus]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
loadLeads();
};
const handleSaveAdvisor = async (e: React.FormEvent) => {
e.preventDefault();
if (!advisorForm.name.trim() || !advisorForm.phone.trim()) {
toast.error('نام و شماره موبایل الزامی است.');
return;
}
try {
if (editingAdvisor) {
await api.put(`/admin/advisors/${editingAdvisor.id}`, advisorForm);
toast.success('مشاور با موفقیت ویرایش شد.');
} else {
await api.post('/admin/advisors', advisorForm);
toast.success('مشاور جدید افزوده شد.');
}
setIsAdvisorModalOpen(false);
setEditingAdvisor(null);
setAdvisorForm({ name: '', phone: '', title: '', isDefault: false, isActive: true });
loadAdvisors();
} catch (err: any) {
toast.error(err?.response?.data?.message || 'خطا در ثبت مشاور');
}
};
const handleSetDefaultAdvisor = async (id: string) => {
try {
await api.patch(`/admin/advisors/${id}/set-default`);
toast.success('مشاور به عنوان پیش‌فرض تعیین شد.');
loadAdvisors();
} catch (err: any) {
toast.error('خطا در تغییر مشاور پیش‌فرض');
}
};
const handleDeleteAdvisor = async (id: string) => {
if (!window.confirm('آیا از حذف این مشاور اطمینان دارید؟')) return;
try {
await api.delete(`/admin/advisors/${id}`);
toast.success('مشاور حذف شد.');
loadAdvisors();
} catch (err: any) {
toast.error('خطا در حذف مشاور');
}
};
const handleUpdateLeadStatus = async (id: string, status: string) => {
try {
await api.patch(`/admin/leads/${id}/status`, { status });
toast.success('وضعیت درخواست تماس به‌روز شد.');
loadLeads();
} catch (err: any) {
toast.error('خطا در به‌روزرسانی وضعیت');
}
};
return (
<div className="space-y-6 pb-12 font-vazir text-gray-800">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
<PhoneCall className="h-7 w-7 text-purple-600" />
درخواست‌های تماس و مشاوران کاتالوگ
</h1>
<p className="mt-1 text-sm text-gray-500">
مدیریت لیدهای تماس وب‌سایت، انتساب مشاوران پیش‌فرض و اختصاصی محصولات
</p>
</div>
<div className="flex items-center gap-3">
<Button onClick={() => {
setEditingAdvisor(null);
setAdvisorForm({ name: '', phone: '', title: '', isDefault: false, isActive: true });
setIsAdvisorModalOpen(true);
}}>
<UserPlus className="h-4 w-4" />
افزودن مشاور جدید
</Button>
</div>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
<button
onClick={() => setActiveTab('leads')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'leads'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<PhoneCall className="h-4 w-4" />
درخواست‌های تماس کاربران (Leads)
{leadStats.pending > 0 && (
<span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-700 font-bold">
{leadStats.pending} نیازمند تماس
</span>
)}
</button>
<button
onClick={() => setActiveTab('advisors')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'advisors'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Users className="h-4 w-4" />
لیست مشاوران تخصصی
<span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600 font-bold">
{advisors.length}
</span>
</button>
</div>
{/* Tab: Leads */}
{activeTab === 'leads' && (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-gray-400">مجموع درخواست‌ها</span>
<p className="mt-2 text-2xl font-black text-gray-900">{leadStats.total}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-amber-500">در انتظار تماس</span>
<p className="mt-2 text-2xl font-black text-amber-600">{leadStats.pending}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-emerald-500">تماس گرفته شده</span>
<p className="mt-2 text-2xl font-black text-emerald-600">{leadStats.contacted}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-gray-400">لغو شده / ناموفق</span>
<p className="mt-2 text-2xl font-black text-gray-600">{leadStats.cancelled}</p>
</div>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-4">
<form onSubmit={handleSearch} className="flex gap-2 w-full sm:w-80">
<input
type="text"
placeholder="جستجو با نام یا شماره..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
/>
<Button type="submit" variant="outline" size="sm">
<Search className="h-4 w-4" />
</Button>
</form>
<div className="flex gap-2">
{['ALL', 'PENDING', 'CONTACTED', 'CANCELLED'].map((st) => (
<button
key={st}
onClick={() => setLeadFilterStatus(st)}
className={`rounded-lg px-3 py-1.5 text-xs font-bold transition-all ${
leadFilterStatus === st
? 'bg-purple-600 text-white'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{st === 'ALL' ? 'همه' : st === 'PENDING' ? 'در انتظار' : st === 'CONTACTED' ? 'تماس گرفته شده' : 'لغو'}
</button>
))}
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">کاربر متقاضی</th>
<th className="py-3 px-4">شماره تماس</th>
<th className="py-3 px-4">محصول مرتبط</th>
<th className="py-3 px-4">مشاور منتسب</th>
<th className="py-3 px-4">زمان ثبت</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{leads.length === 0 ? (
<tr>
<td colSpan={7} className="py-8 text-center text-gray-400">
هیچ درخواست تماسی یافت نشد.
</td>
</tr>
) : (
leads.map((l) => (
<tr key={l.id} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-bold text-gray-900">
{l.firstName} {l.lastName}
</td>
<td className="py-3.5 px-4 font-mono font-medium text-purple-700 dir-ltr text-right">
<a href={`tel:${l.phone}`} className="hover:underline">
{l.phone}
</a>
</td>
<td className="py-3.5 px-4 text-xs text-gray-600">
{l.product ? l.product.nameFa : <span className="text-gray-400">مشاوره عمومی</span>}
</td>
<td className="py-3.5 px-4 text-xs font-medium text-gray-700">
{l.advisor ? `${l.advisor.name} (${l.advisor.phone})` : <span className="text-gray-400">پیش‌فرض</span>}
</td>
<td className="py-3.5 px-4 text-xs text-gray-400">
{new Date(l.createdAt).toLocaleDateString('fa-IR')} - {new Date(l.createdAt).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' })}
</td>
<td className="py-3.5 px-4">
<span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-bold ${
l.status === 'CONTACTED'
? 'bg-emerald-50 text-emerald-700'
: l.status === 'CANCELLED'
? 'bg-gray-100 text-gray-600'
: 'bg-amber-50 text-amber-700'
}`}>
{l.status === 'CONTACTED' ? 'تماس گرفته شد' : l.status === 'CANCELLED' ? 'لغو شده' : 'در انتظار تماس'}
</span>
</td>
<td className="py-3.5 px-4">
<div className="flex items-center gap-2">
{l.status !== 'CONTACTED' && (
<button
onClick={() => handleUpdateLeadStatus(l.id, 'CONTACTED')}
title="ثبت به عنوان تماس گرفته شده"
className="rounded p-1 text-emerald-600 hover:bg-emerald-50"
>
<CheckCircle2 className="h-4 w-4" />
</button>
)}
{l.status !== 'CANCELLED' && (
<button
onClick={() => handleUpdateLeadStatus(l.id, 'CANCELLED')}
title="لغو درخواست"
className="rounded p-1 text-gray-400 hover:bg-gray-100"
>
<Trash2 className="h-4 w-4" />
</button>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* Tab: Advisors */}
{activeTab === 'advisors' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">نام مشاور</th>
<th className="py-3 px-4">شماره همراه</th>
<th className="py-3 px-4">عنوان / تخصص</th>
<th className="py-3 px-4">محصولات منتسب</th>
<th className="py-3 px-4">تعداد لیدها</th>
<th className="py-3 px-4">نقش</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{advisors.map((adv) => (
<tr key={adv.id} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-bold text-gray-900">{adv.name}</td>
<td className="py-3.5 px-4 font-mono font-medium text-gray-700">{adv.phone}</td>
<td className="py-3.5 px-4 text-xs text-gray-500">{adv.title || '-'}</td>
<td className="py-3.5 px-4 text-xs font-bold text-purple-600">{adv.productsCount} محصول</td>
<td className="py-3.5 px-4 text-xs font-bold text-gray-700">{adv.leadsCount} درخواست</td>
<td className="py-3.5 px-4">
{adv.isDefault ? (
<span className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2.5 py-0.5 text-xs font-bold text-amber-700">
<Star className="h-3 w-3 fill-amber-500 text-amber-500" />
پیش‌فرض سیستم
</span>
) : (
<button
onClick={() => handleSetDefaultAdvisor(adv.id)}
className="text-xs text-gray-400 hover:text-purple-600 hover:underline"
>
تنظیم به عنوان پیش‌فرض
</button>
)}
</td>
<td className="py-3.5 px-4">
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-bold ${
adv.isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
}`}>
{adv.isActive ? 'فعال' : 'غیرفعال'}
</span>
</td>
<td className="py-3.5 px-4">
<div className="flex items-center gap-2">
<button
onClick={() => {
setEditingAdvisor(adv);
setAdvisorForm({
name: adv.name,
phone: adv.phone,
title: adv.title || '',
isDefault: adv.isDefault,
isActive: adv.isActive,
});
setIsAdvisorModalOpen(true);
}}
className="rounded p-1 text-gray-500 hover:bg-gray-100"
>
<Edit2 className="h-4 w-4" />
</button>
<button
onClick={() => handleDeleteAdvisor(adv.id)}
className="rounded p-1 text-red-500 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Modal: Advisor Create/Edit */}
<Modal
isOpen={isAdvisorModalOpen}
onClose={() => setIsAdvisorModalOpen(false)}
title={editingAdvisor ? 'ویرایش مشاور' : 'افزودن مشاور جدید'}
>
<form onSubmit={handleSaveAdvisor} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام و نام خانوادگی مشاور</label>
<input
type="text"
value={advisorForm.name}
onChange={(e) => setAdvisorForm({ ...advisorForm, name: e.target.value })}
placeholder="مثال: دکتر مهدی صابری"
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">شماره تلفن همراه</label>
<input
type="text"
dir="ltr"
value={advisorForm.phone}
onChange={(e) => setAdvisorForm({ ...advisorForm, phone: e.target.value })}
placeholder="09121234567"
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">عنوان تخصصی یا سمت</label>
<input
type="text"
value={advisorForm.title}
onChange={(e) => setAdvisorForm({ ...advisorForm, title: e.target.value })}
placeholder="مثال: کارشناس تغذیه سگ و گربه"
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
/>
</div>
<div className="flex items-center gap-6 pt-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={advisorForm.isDefault}
onChange={(e) => setAdvisorForm({ ...advisorForm, isDefault: e.target.checked })}
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
/>
<span className="text-xs font-bold text-gray-700">مشاور پیش‌فرض سیستم</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={advisorForm.isActive}
onChange={(e) => setAdvisorForm({ ...advisorForm, isActive: e.target.checked })}
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
/>
<span className="text-xs font-bold text-gray-700">مشاور فعال</span>
</label>
</div>
<div className="flex justify-end gap-2 pt-4 border-t border-gray-100">
<Button variant="outline" type="button" onClick={() => setIsAdvisorModalOpen(false)}>
انصراف
</Button>
<Button type="submit">
ذخیره
</Button>
</div>
</form>
</Modal>
</div>
);
}
@@ -0,0 +1,725 @@
import React, { useState, useEffect } from 'react';
import {
Bell,
Mail,
MessageSquare,
Server,
Send,
ListFilter,
RefreshCw,
CheckCircle2,
AlertCircle,
Clock,
ShieldCheck,
Plus,
Trash2,
ExternalLink,
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
interface EmailConfig {
enabled: boolean;
host: string;
port: number;
secure: boolean;
user: string;
password?: string;
fromName: string;
fromEmail: string;
}
interface QueueItem {
id: string;
channel: 'SMS' | 'EMAIL';
recipient: string;
event: string;
subject?: string;
content: string;
status: 'QUEUED' | 'PROCESSING' | 'SENT' | 'FAILED';
attempts: number;
maxAttempts: number;
lastError?: string;
sentAt?: string;
createdAt: string;
}
interface NotificationTemplate {
id: string;
channel: 'SMS' | 'EMAIL';
event: string;
name: string;
subject?: string;
body: string;
recipientType: string;
isActive: boolean;
variables: string[];
}
export default function NotificationsSettingsPage() {
const [activeTab, setActiveTab] = useState<'overview' | 'email' | 'templates' | 'manual' | 'queue'>('overview');
const [isLoading, setIsLoading] = useState(true);
// Email Config State
const [emailConfig, setEmailConfig] = useState<EmailConfig>({
enabled: true,
host: 'mail.canina.ir',
port: 587,
secure: false,
user: '',
password: '',
fromName: 'کنینا ایران',
fromEmail: 'info@canina.ir',
});
const [isSavingEmail, setIsSavingEmail] = useState(false);
const [isTestingSmtp, setIsTestingSmtp] = useState(false);
const [smtpStatus, setSmtpStatus] = useState<{ checked: boolean; success: boolean; message: string } | null>(null);
// Queue state
const [queueItems, setQueueItems] = useState<QueueItem[]>([]);
const [queueStats, setQueueStats] = useState({ total: 0, queued: 0, sent: 0, failed: 0, successRate: 100 });
const [isLoadingQueue, setIsLoadingQueue] = useState(false);
// Templates state
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
const [eventsList, setEventsList] = useState<{ event: string; name: string; variables: string[] }[]>([]);
// Manual Send State
const [manualForm, setManualForm] = useState({
channel: 'SMS' as 'SMS' | 'EMAIL',
targetType: 'single' as 'single' | 'all_users' | 'custom_list',
recipient: '',
subject: '',
content: '',
});
const [isSendingManual, setIsSendingManual] = useState(false);
// Load Initial Config
const loadConfig = async () => {
try {
setIsLoading(true);
const res = await api.get('/admin/notifications/config');
if (res.data?.success) {
setEmailConfig(res.data.data.email);
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت تنظیمات اطلاع‌رسانی');
} finally {
setIsLoading(false);
}
};
const loadQueue = async () => {
try {
setIsLoadingQueue(true);
const res = await api.get('/admin/notifications/queue?limit=50');
if (res.data?.success) {
setQueueItems(res.data.data.items);
if (res.data.data.stats) setQueueStats(res.data.data.stats);
}
} catch (err) {
console.error(err);
} finally {
setIsLoadingQueue(false);
}
};
const loadTemplates = async () => {
try {
const res = await api.get('/admin/notifications/templates');
if (res.data?.success) {
setTemplates(res.data.data.templates);
setEventsList(res.data.data.events || []);
}
} catch (err) {
console.error(err);
}
};
useEffect(() => {
loadConfig();
loadQueue();
loadTemplates();
}, []);
const handleSaveEmail = async (e: React.FormEvent) => {
e.preventDefault();
try {
setIsSavingEmail(true);
const res = await api.put('/admin/notifications/email-config', emailConfig);
if (res.data?.success) {
toast.success(res.data.message || 'تنظیمات سرور ایمیل ذخیره شد.');
}
} catch (err: any) {
toast.error(err?.response?.data?.message || 'خطا در ذخیره تنظیمات ایمیل');
} finally {
setIsSavingEmail(false);
}
};
const handleTestSmtp = async () => {
try {
setIsTestingSmtp(true);
setSmtpStatus(null);
const res = await api.post('/admin/notifications/test-smtp', emailConfig);
setSmtpStatus({
checked: true,
success: res.data?.success,
message: res.data?.message,
});
if (res.data?.success) {
toast.success('اتصال به سرور SMTP با موفقیت برقرار شد.');
} else {
toast.error(res.data?.message || 'خطا در اتصال به سرور SMTP');
}
} catch (err: any) {
const msg = err?.response?.data?.message || 'خطا در تست اتصال سرور';
setSmtpStatus({ checked: true, success: false, message: msg });
toast.error(msg);
} finally {
setIsTestingSmtp(false);
}
};
const handleManualSend = async (e: React.FormEvent) => {
e.preventDefault();
if (!manualForm.content.trim()) {
toast.error('متن پیام الزامی است.');
return;
}
try {
setIsSendingManual(true);
const res = await api.post('/admin/notifications/manual-send', manualForm);
if (res.data?.success) {
toast.success(res.data.message || 'پیام با موفقیت در صف ارسال قرار گرفت.');
setManualForm({ ...manualForm, recipient: '', subject: '', content: '' });
loadQueue();
}
} catch (err: any) {
toast.error(err?.response?.data?.message || 'خطا در ثبت پیام در صف');
} finally {
setIsSendingManual(false);
}
};
const handleRetryQueue = async (id: string) => {
try {
const res = await api.post(`/admin/notifications/queue/${id}/retry`);
if (res.data?.success) {
toast.success('پیام مجدداً در صف قرار گرفت.');
loadQueue();
}
} catch (err: any) {
toast.error('خطا در ارسال مجدد');
}
};
if (isLoading) {
return (
<div className="flex h-96 items-center justify-center">
<Spinner size="lg" />
</div>
);
}
return (
<div className="space-y-6 pb-12 font-vazir text-gray-800">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
<Bell className="h-7 w-7 text-purple-600" />
مرکز مدیریت اطلاع‌رسانی و پیام‌ها
</h1>
<p className="mt-1 text-sm text-gray-500">
پیکربندی یکپارچه ایمیل (SMTP)، سامانه پیامک، صف ارسال پایدار و رویدادهای خودکار
</p>
</div>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
<button
onClick={() => setActiveTab('overview')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'overview'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Server className="h-4 w-4" />
داشبورد و وضعیت
</button>
<button
onClick={() => setActiveTab('email')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'email'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Mail className="h-4 w-4" />
تنظیمات ایمیل (SMTP)
</button>
<button
onClick={() => setActiveTab('templates')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'templates'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<ListFilter className="h-4 w-4" />
قالب‌های رویدادها
</button>
<button
onClick={() => setActiveTab('manual')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'manual'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Send className="h-4 w-4" />
ارسال دستی هدفمند
</button>
<button
onClick={() => setActiveTab('queue')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'queue'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Clock className="h-4 w-4" />
صف ارسال و لاگ‌ها
{queueStats.failed > 0 && (
<span className="rounded-full bg-red-100 px-2 py-0.5 text-xs text-red-600 font-bold">
{queueStats.failed} خطا
</span>
)}
</button>
</div>
{/* Tab: Overview */}
{activeTab === 'overview' && (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-gray-400">مجموع پیام‌های صف</span>
<p className="mt-2 text-3xl font-black text-gray-900">{queueStats.total}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-emerald-500">ارسال موفق</span>
<p className="mt-2 text-3xl font-black text-emerald-600">{queueStats.sent}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-amber-500">در حال پردازش / صف</span>
<p className="mt-2 text-3xl font-black text-amber-600">{queueStats.queued}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-red-500">ناموفق با تلاش مجدد</span>
<p className="mt-2 text-3xl font-black text-red-600">{queueStats.failed}</p>
</div>
</div>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-purple-50 p-3 text-purple-600">
<Mail className="h-6 w-6" />
</div>
<div>
<h3 className="font-bold text-gray-900">سرویس ایمیل سازمانی</h3>
<p className="text-xs text-gray-400">پروتکل SMTP / TLS اختصاصی</p>
</div>
</div>
<span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-bold ${
emailConfig.enabled ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
}`}>
{emailConfig.enabled ? 'فعال' : 'غیرفعال'}
</span>
</div>
<div className="mt-4 space-y-2 text-sm text-gray-600">
<div className="flex justify-between">
<span>سرور میزبان:</span>
<span className="font-mono text-gray-900 font-medium">{emailConfig.host || '-'}</span>
</div>
<div className="flex justify-between">
<span>پورت اتصال:</span>
<span className="font-mono text-gray-900 font-medium">{emailConfig.port}</span>
</div>
<div className="flex justify-between">
<span>فرستنده پیش‌فرض:</span>
<span className="font-mono text-gray-900 font-medium">{emailConfig.fromEmail}</span>
</div>
</div>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-violet-50 p-3 text-violet-600">
<MessageSquare className="h-6 w-6" />
</div>
<div>
<h3 className="font-bold text-gray-900">درگاه پیامک (MeliPayamak)</h3>
<p className="text-xs text-gray-400">ارسال خدماتی با الگوهای تایید شده</p>
</div>
</div>
<span className="inline-flex rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-bold text-emerald-700">
متصل
</span>
</div>
<div className="mt-4 space-y-2 text-sm text-gray-600">
<div className="flex justify-between">
<span>وضعیت اتصال:</span>
<span className="text-emerald-600 font-bold">برقرار</span>
</div>
<div className="flex justify-between">
<span>قالب‌های پیامک:</span>
<a href="/settings/sms" className="flex items-center gap-1 text-purple-600 hover:underline">
مشاهده تنظیمات پیشرفته ملی‌پیامک
<ExternalLink className="h-3 w-3" />
</a>
</div>
</div>
</div>
</div>
</div>
)}
{/* Tab: Email SMTP */}
{activeTab === 'email' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<form onSubmit={handleSaveEmail} className="space-y-6 max-w-3xl">
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
<div>
<h3 className="text-lg font-bold text-gray-900">پیکربندی سرور ارسال ایمیل (SMTP)</h3>
<p className="text-xs text-gray-500">مشخصات سرور میل اختصاصی خود را وارد نمایید</p>
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={emailConfig.enabled}
onChange={(e) => setEmailConfig({ ...emailConfig, enabled: e.target.checked })}
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
/>
<span className="text-sm font-bold text-gray-700">فعال‌سازی ارسال ایمیل</span>
</label>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">هاست سرور SMTP</label>
<input
type="text"
dir="ltr"
value={emailConfig.host}
onChange={(e) => setEmailConfig({ ...emailConfig, host: e.target.value })}
placeholder="mail.canina.ir"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">پورت اتصال</label>
<input
type="number"
dir="ltr"
value={emailConfig.port}
onChange={(e) => setEmailConfig({ ...emailConfig, port: Number(e.target.value) })}
placeholder="587 یا 465"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام کاربری (ایمیل ورود)</label>
<input
type="text"
dir="ltr"
value={emailConfig.user}
onChange={(e) => setEmailConfig({ ...emailConfig, user: e.target.value })}
placeholder="info@canina.ir"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">رمز عبور ایمیل</label>
<input
type="password"
dir="ltr"
value={emailConfig.password}
onChange={(e) => setEmailConfig({ ...emailConfig, password: e.target.value })}
placeholder="••••••••"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام فرستنده (Sender Name)</label>
<input
type="text"
value={emailConfig.fromName}
onChange={(e) => setEmailConfig({ ...emailConfig, fromName: e.target.value })}
placeholder="کنینا ایران"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">آدرس ایمیل فرستنده (From Address)</label>
<input
type="email"
dir="ltr"
value={emailConfig.fromEmail}
onChange={(e) => setEmailConfig({ ...emailConfig, fromEmail: e.target.value })}
placeholder="info@canina.ir"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
</div>
{/* Test result status */}
{smtpStatus && (
<div className={`flex items-center gap-3 rounded-xl p-4 text-sm ${
smtpStatus.success ? 'bg-emerald-50 text-emerald-800' : 'bg-red-50 text-red-800'
}`}>
{smtpStatus.success ? <CheckCircle2 className="h-5 w-5 shrink-0" /> : <AlertCircle className="h-5 w-5 shrink-0" />}
<span>{smtpStatus.message}</span>
</div>
)}
<div className="flex items-center gap-3 pt-4 border-t border-gray-100">
<Button type="submit" disabled={isSavingEmail}>
{isSavingEmail ? <Spinner size="sm" /> : 'ذخیره تنظیمات'}
</Button>
<Button
type="button"
variant="outline"
onClick={handleTestSmtp}
disabled={isTestingSmtp}
>
{isTestingSmtp ? <Spinner size="sm" /> : 'تست اتصال به سرور (SMTP Test)'}
</Button>
</div>
</form>
</div>
)}
{/* Tab: Templates */}
{activeTab === 'templates' && (
<div className="space-y-6">
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<h3 className="text-lg font-bold text-gray-900 mb-4">قالب‌های خودکار سیستم بر اساس رویداد</h3>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">نام رویداد</th>
<th className="py-3 px-4">کانال</th>
<th className="py-3 px-4">عنوان / موضوع</th>
<th className="py-3 px-4">گیرنده</th>
<th className="py-3 px-4">متغیرها</th>
<th className="py-3 px-4">وضعیت</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{eventsList.map((ev) => (
<tr key={ev.event} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-bold text-gray-900">{ev.name}</td>
<td className="py-3.5 px-4">
<span className="rounded-md bg-purple-50 px-2 py-1 text-xs font-bold text-purple-700">
SMS & EMAIL
</span>
</td>
<td className="py-3.5 px-4 text-gray-600 font-mono text-xs">{ev.event}</td>
<td className="py-3.5 px-4 text-gray-600">کاربر / مشتری</td>
<td className="py-3.5 px-4 text-xs font-mono text-gray-400">
{ev.variables.join(', ')}
</td>
<td className="py-3.5 px-4">
<span className="inline-flex items-center gap-1 text-xs text-emerald-600 font-bold">
<CheckCircle2 className="h-3.5 w-3.5" />
فعال
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* Tab: Manual Send */}
{activeTab === 'manual' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm max-w-2xl">
<h3 className="text-lg font-bold text-gray-900 mb-2">ارسال دستی و هدفمند پیام</h3>
<p className="text-xs text-gray-500 mb-6">پیامک یا ایمیل دلخواه خود را به یک کاربر یا گروه‌های مشخص ارسال کنید</p>
<form onSubmit={handleManualSend} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">کانال ارسال</label>
<div className="flex gap-4">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="channel"
checked={manualForm.channel === 'SMS'}
onChange={() => setManualForm({ ...manualForm, channel: 'SMS' })}
className="text-purple-600 focus:ring-purple-500"
/>
<span className="text-sm font-medium">پیامک (SMS)</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="channel"
checked={manualForm.channel === 'EMAIL'}
onChange={() => setManualForm({ ...manualForm, channel: 'EMAIL' })}
className="text-purple-600 focus:ring-purple-500"
/>
<span className="text-sm font-medium">ایمیل (Email)</span>
</label>
</div>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">
{manualForm.channel === 'SMS' ? 'شماره موبایل گیرنده' : 'آدرس ایمیل گیرنده'}
</label>
<input
type="text"
dir="ltr"
value={manualForm.recipient}
onChange={(e) => setManualForm({ ...manualForm, recipient: e.target.value })}
placeholder={manualForm.channel === 'SMS' ? '09121234567' : 'user@example.com'}
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
{manualForm.channel === 'EMAIL' && (
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">موضوع ایمیل</label>
<input
type="text"
value={manualForm.subject}
onChange={(e) => setManualForm({ ...manualForm, subject: e.target.value })}
placeholder="موضوع اطلاعیه..."
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
)}
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">متن پیام</label>
<textarea
rows={4}
value={manualForm.content}
onChange={(e) => setManualForm({ ...manualForm, content: e.target.value })}
placeholder="متن پیام خود را اینجا بنویسید..."
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
<Button type="submit" disabled={isSendingManual}>
{isSendingManual ? <Spinner size="sm" /> : 'ثبت در صف ارسال'}
</Button>
</form>
</div>
)}
{/* Tab: Queue & Logs */}
{activeTab === 'queue' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-bold text-gray-900">صف پردازش پایدار نوتیفیکیشن‌ها</h3>
<Button variant="outline" size="sm" onClick={loadQueue} disabled={isLoadingQueue}>
<RefreshCw className={`h-4 w-4 ${isLoadingQueue ? 'animate-spin' : ''}`} />
به‌روزرسانی صف
</Button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">گیرنده</th>
<th className="py-3 px-4">کانال</th>
<th className="py-3 px-4">رویداد</th>
<th className="py-3 px-4">تلاش</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4">زمان ثبت</th>
<th className="py-3 px-4">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{queueItems.length === 0 ? (
<tr>
<td colSpan={7} className="py-8 text-center text-gray-400">
هیچ پیامی در صف وجود ندارد.
</td>
</tr>
) : (
queueItems.map((item) => (
<tr key={item.id} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-mono font-medium text-gray-900">{item.recipient}</td>
<td className="py-3.5 px-4">
<span className={`rounded-md px-2 py-0.5 text-xs font-bold ${
item.channel === 'EMAIL' ? 'bg-blue-50 text-blue-700' : 'bg-violet-50 text-violet-700'
}`}>
{item.channel}
</span>
</td>
<td className="py-3.5 px-4 text-xs font-mono text-gray-600">{item.event}</td>
<td className="py-3.5 px-4 font-mono text-xs">{item.attempts} / {item.maxAttempts}</td>
<td className="py-3.5 px-4">
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-bold ${
item.status === 'SENT'
? 'bg-emerald-50 text-emerald-700'
: item.status === 'FAILED'
? 'bg-red-50 text-red-700'
: 'bg-amber-50 text-amber-700'
}`}>
{item.status === 'SENT' ? 'ارسال شده' : item.status === 'FAILED' ? 'ناموفق' : 'در صف'}
</span>
</td>
<td className="py-3.5 px-4 text-xs text-gray-400">
{new Date(item.createdAt).toLocaleTimeString('fa-IR')}
</td>
<td className="py-3.5 px-4">
{item.status === 'FAILED' && (
<button
onClick={() => handleRetryQueue(item.id)}
className="text-xs text-purple-600 hover:underline font-bold"
>
تلاش مجدد
</button>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}
+12 -8
View File
@@ -1,12 +1,14 @@
import {
Building2,
ChevronLeft,
CreditCard,
DollarSign,
Globe,
MessageSquare,
Palette,
Save,
Bell,
Building2,
ChevronLeft,
CreditCard,
DollarSign,
Globe,
MessageSquare,
Palette,
PhoneCall,
Save,
Settings as SettingsIcon,
Share2,
ShieldCheck,
@@ -114,6 +116,8 @@ export default function Settings() {
};
const SETTING_MODULES = [
{ title: 'مرکز اطلاع‌رسانی و ایمیل', desc: 'پیکربندی سرور SMTP، صف ارسال پیامک و ایمیل و قالب‌های خودکار', path: '/settings/notifications', icon: Bell, color: 'from-fuchsia-600 to-purple-800', badge: 'جدید' },
{ title: 'مشاوران تخصصی و لیدها', desc: 'مدیریت مشاوران کاتالوگ و پیگیری درخواست‌های تماس کاربران', path: '/advisors', icon: PhoneCall, color: 'from-blue-600 to-indigo-800', badge: 'جدید' },
{ title: 'پشتیبان هوشمند سایت', desc: 'فعال‌سازی، ارائه‌دهنده و مدل، نام دکمه و آیکون دستیار', path: '/settings/smart-chat', icon: MessageSquare, color: 'from-purple-600 to-purple-800', badge: 'هوشمند' },
{
title: 'روش‌های پرداخت و زیبال',
@@ -39,6 +39,8 @@ const ZibalPortalPage = lazyWithRetry(() => import('../pages/ZibalPortalPage'));
const ShippingSettingsPage = lazyWithRetry(() => import('../pages/ShippingSettingsPage'));
const SystemSettingsPage = lazyWithRetry(() => import('../pages/SystemSettingsPage'));
const SmsSettingsPage = lazyWithRetry(() => import('../pages/SmsSettingsPage'));
const NotificationsSettingsPage = lazyWithRetry(() => import('../pages/NotificationsSettingsPage'));
const AdvisorsManagementPage = lazyWithRetry(() => import('../pages/AdvisorsManagementPage'));
const SslSettingsPage = lazyWithRetry(() => import('../pages/SslSettingsPage'));
const ApiKeysPage = lazyWithRetry(() => import('../pages/ApiKeysPage'));
const Transactions = lazyWithRetry(() => import('../pages/Transactions'));
@@ -88,6 +90,9 @@ export const router = createBrowserRouter([
{ path: 'settings/ssl', element: <SslSettingsPage /> },
{ path: 'settings/api-keys', element: <ApiKeysPage /> },
{ path: 'settings/sms', element: <SmsSettingsPage /> },
{ path: 'settings/notifications', element: <NotificationsSettingsPage /> },
{ path: 'advisors/*', element: <AdvisorsManagementPage /> },
{ path: 'leads/*', element: <AdvisorsManagementPage /> },
{ path: 'settings/seo', element: <SeoSettingsPage /> },
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
{ path: 'settings/system', element: <SystemSettingsPage /> },