- ) : faqs.length === 0 ? (
+ ) : filteredFaqs.length === 0 ? (
) : (
- faqs.map((faq) => (
+ filteredFaqs.map((faq) => (
({
+ default: {
+ get: vi.fn(),
+ put: vi.fn(),
+ },
+}));
+
+vi.mock('react-hot-toast', () => ({
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+vi.mock('react-router-dom', () => ({
+ Link: ({ children, to, className }: any) =>
{children},
+}));
+
+describe('SmartChatSettingsPage Component', () => {
+ const mockSettings = {
+ enabled: true,
+ provider: 'configured-test-1234',
+ model: 'gpt-test-model',
+ label: 'گفتگو با پشتیبان',
+ icon: 'chat',
+ };
+
+ const mockCatalog = {
+ providers: [
+ {
+ id: 'configured-test-1234',
+ label: 'ارائهدهنده کنینا',
+ models: ['gpt-test-model', 'claude-test-model'],
+ },
+ ],
+ };
+
+ const mockStats = {
+ conversations: 5,
+ messages: 12,
+ authenticated: 3,
+ anonymous: 2,
+ unanswered: 0,
+ followup: 1,
+ escalated: 0,
+ topics: {},
+ };
+
+ const mockConversations = {
+ data: [
+ {
+ id: 'conv-1',
+ createdAt: '2026-11-07T10:00:00.000Z',
+ updatedAt: '2026-11-07T10:05:00.000Z',
+ unanswered: false,
+ needsFollowup: false,
+ escalationSignal: false,
+ user: { firstName: 'پارسا', lastName: 'آقایی', mobile: '09211231517' },
+ messages: [
+ { role: 'user', content: 'سلام، مکمل مفاصل موجود دارید؟', createdAt: '2026-11-07T10:00:00.000Z' },
+ { role: 'assistant', content: 'بله Canhydrox GAG موجود است.', createdAt: '2026-11-07T10:01:00.000Z' },
+ ],
+ },
+ ],
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(api.get).mockImplementation(async (url: string) => {
+ if (url === '/support-chat/settings') return { data: { data: mockSettings } };
+ if (url === '/support-chat/catalog') return { data: { data: mockCatalog } };
+ if (url === '/admin/support-chat/stats') return { data: { data: mockStats } };
+ if (url === '/admin/support-chat/conversations') return { data: { data: mockConversations } };
+ return { data: {} };
+ });
+ });
+
+ it('renders settings tab and loads config correctly', async () => {
+ render(
);
+
+ await waitFor(() => {
+ expect(screen.getByText('پشتیبان هوشمند سایت (Smart Support Chat)')).toBeTruthy();
+ expect(screen.getByLabelText('نام دکمه و دستیار')).toHaveValue('گفتگو با پشتیبان');
+ expect(screen.getByLabelText('ارائهدهنده')).toHaveValue('configured-test-1234');
+ expect(screen.getByLabelText('مدل')).toHaveValue('gpt-test-model');
+ });
+ });
+
+ it('allows saving updated settings', async () => {
+ vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
+
+ render(
);
+
+ await waitFor(() => {
+ expect(screen.getByLabelText('نام دکمه و دستیار')).toHaveValue('گفتگو با پشتیبان');
+ });
+
+ const labelInput = screen.getByLabelText('نام دکمه و دستیار');
+ fireEvent.change(labelInput, { target: { value: 'پشتیبان آنلاین ۲۴ ساعته' } });
+
+ const submitBtn = screen.getByRole('button', { name: 'ذخیره تنظیمات' });
+ fireEvent.click(submitBtn);
+
+ await waitFor(() => {
+ expect(api.put).toHaveBeenCalledWith(
+ '/support-chat/settings',
+ expect.objectContaining({
+ label: 'پشتیبان آنلاین ۲۴ ساعته',
+ })
+ );
+ expect(toast.success).toHaveBeenCalledWith('تنظیمات پشتیبان هوشمند سایت با موفقیت ذخیره شد.');
+ });
+ });
+
+ it('switches to analytics tab and displays stats and conversations', async () => {
+ render(
);
+
+ await waitFor(() => {
+ expect(screen.getByText('تحلیل و تاریخچه مکالمات')).toBeTruthy();
+ });
+
+ const analyticsTabBtn = screen.getByText('تحلیل و تاریخچه مکالمات');
+ fireEvent.click(analyticsTabBtn);
+
+ await waitFor(() => {
+ expect(screen.getByText('گفتگوها')).toBeTruthy();
+ expect(screen.getByText('5')).toBeTruthy();
+ expect(screen.getByText('سلام، مکمل مفاصل موجود دارید؟')).toBeTruthy();
+ expect(screen.getByText('بله Canhydrox GAG موجود است.')).toBeTruthy();
+ expect(screen.getByText('پارسا آقایی')).toBeTruthy();
+ });
+ });
+});
diff --git a/frontend/admin-panel/src/pages/SmartChatSettingsPage.tsx b/frontend/admin-panel/src/pages/SmartChatSettingsPage.tsx
index 0502df41..0af05f01 100644
--- a/frontend/admin-panel/src/pages/SmartChatSettingsPage.tsx
+++ b/frontend/admin-panel/src/pages/SmartChatSettingsPage.tsx
@@ -1,59 +1,539 @@
-import { useEffect, useState } from 'react';
+import React, { useEffect, useState } from 'react';
+import {
+ MessageSquare,
+ Bot,
+ Settings,
+ BarChart3,
+ RefreshCw,
+ Sliders,
+ CheckCircle2,
+ AlertCircle,
+ HelpCircle,
+ ShieldCheck,
+ Save,
+ Clock,
+ Sparkles,
+ ArrowRight,
+ ExternalLink,
+} from 'lucide-react';
import { Link } from 'react-router-dom';
import { toast } from 'react-hot-toast';
import api from '../services/api';
import Button from '../components/ui/Button';
+import Spinner from '../components/ui/Spinner';
+
+type SettingsState = {
+ enabled: boolean;
+ provider: string;
+ model: string;
+ label: string;
+ icon: string;
+};
+
+type Provider = {
+ id: string;
+ label: string;
+ models: string[];
+};
+
+type Stats = {
+ conversations: number;
+ messages: number;
+ authenticated: number;
+ anonymous: number;
+ unanswered: number;
+ followup: number;
+ escalated: number;
+ topics: Record
;
+};
+
+type Conversation = {
+ id: string;
+ createdAt: string;
+ updatedAt: string;
+ entryPath?: string;
+ unanswered: boolean;
+ needsFollowup: boolean;
+ escalationSignal: boolean;
+ summary?: string;
+ user?: {
+ firstName?: string;
+ lastName?: string;
+ mobile?: string;
+ email?: string;
+ } | null;
+ messages: {
+ role: string;
+ content: string;
+ createdAt: string;
+ }[];
+};
-type Settings = { enabled: boolean; provider: string; model: string; label: string; icon: string };
-type Provider = { id: string; label: string; models: string[] };
const unwrap = (r: any) => r.data?.data ?? r.data;
+
export default function SmartChatSettingsPage() {
- const [settings, setSettings] = useState(null);
+ const [activeTab, setActiveTab] = useState<'config' | 'analytics'>('config');
+
+ // Config State
+ const [settings, setSettings] = useState(null);
const [providers, setProviders] = useState([]);
- const [error, setError] = useState('');
- const [saving, setSaving] = useState(false);
- const load = async () => {
- setError('');
- const [s, c] = await Promise.allSettled([api.get('/support-chat/settings'), api.get('/support-chat/catalog')]);
- if (s.status === 'fulfilled') setSettings(unwrap(s.value));
- else setError('تنظیمات ذخیرهشده دریافت نشد. پشتیبان تا ثبت تنظیمات معتبر نمایش داده نمیشود.');
- if (c.status === 'fulfilled') setProviders(unwrap(c.value).providers);
- else { setProviders([]); setError('فهرست واقعی ارائهدهندگان در دسترس نیست. لطفاً دوباره تلاش کنید.'); }
+ const [isConfigLoading, setIsConfigLoading] = useState(true);
+ const [isSaving, setIsSaving] = useState(false);
+ const [configError, setConfigError] = useState('');
+
+ // Analytics State
+ const [stats, setStats] = useState(null);
+ const [conversations, setConversations] = useState([]);
+ const [isAnalyticsLoading, setIsAnalyticsLoading] = useState(false);
+ const [analyticsError, setAnalyticsError] = useState('');
+ const [dates, setDates] = useState({ startDate: '', endDate: '' });
+
+ // Load config & catalog
+ const loadConfig = async () => {
+ setIsConfigLoading(true);
+ setConfigError('');
+ try {
+ const [sRes, cRes] = await Promise.allSettled([
+ api.get('/support-chat/settings'),
+ api.get('/support-chat/catalog'),
+ ]);
+
+ if (sRes.status === 'fulfilled') {
+ setSettings(unwrap(sRes.value));
+ } else {
+ setConfigError('تنظیمات ذخیرهشده دریافت نشد. لطفاً تنظیمات جدید ایجاد و ثبت نمایید.');
+ }
+
+ if (cRes.status === 'fulfilled') {
+ const cat = unwrap(cRes.value);
+ setProviders(cat.providers || []);
+ } else {
+ setProviders([]);
+ }
+ } catch {
+ setConfigError('خطا در برقراری ارتباط با سامانه پشتیبان هوشمند.');
+ } finally {
+ setIsConfigLoading(false);
+ }
};
- useEffect(() => { void load(); }, []);
- const save = async (event: React.FormEvent) => {
- event.preventDefault();
+
+ // Load analytics
+ const loadAnalytics = async () => {
+ setIsAnalyticsLoading(true);
+ setAnalyticsError('');
+ try {
+ const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v));
+ const [sRes, cRes] = await Promise.all([
+ api.get('/admin/support-chat/stats', { params }),
+ api.get('/admin/support-chat/conversations', { params: { ...params, page: 1, limit: 50 } }),
+ ]);
+ setStats(unwrap(sRes));
+ setConversations(unwrap(cRes).data || []);
+ } catch {
+ setAnalyticsError('گزارش تحلیلی مکالمات پشتیبان بارگذاری نشد.');
+ } finally {
+ setIsAnalyticsLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ loadConfig();
+ loadAnalytics();
+ }, []);
+
+ const handleSave = async (e: React.FormEvent) => {
+ e.preventDefault();
if (!settings) return;
- setSaving(true);
+ setIsSaving(true);
try {
await api.put('/support-chat/settings', settings);
const saved = unwrap(await api.get('/support-chat/settings'));
setSettings(saved);
- setError('');
- toast.success('تنظیمات پشتیبان هوشمند ذخیره شد.');
- } catch { toast.error('ذخیره تنظیمات انجام نشد؛ ارائهدهنده و مدل را بررسی کنید.'); }
- finally { setSaving(false); }
+ setConfigError('');
+ toast.success('تنظیمات پشتیبان هوشمند سایت با موفقیت ذخیره شد.');
+ } catch (err: any) {
+ const msg = err?.response?.data?.message || 'ذخیره تنظیمات انجام نشد؛ ارائهدهنده و مدل را بررسی نمایید.';
+ toast.error(msg);
+ } finally {
+ setIsSaving(false);
+ }
};
- const icons: Record = { chat: '💬', paw: '🐾', bot: '🤖' };
- return
-
← تنظیمات فروشگاه
-
پشتیبان هوشمند سایت
-
انتخاب مدل برای تشخیص درخواست و پاسخگویی یکسان است. اطلاعات حساب مشتری به مدل ارسال نمیشود.
- {error &&
{error}
}
- {!settings ?
:
-
}
-
;
+
+ const icons: Record = {
+ chat: '💬',
+ paw: '🐾',
+ bot: '🤖',
+ };
+
+ return (
+
+ {/* Header */}
+
+
+
+ تنظیمات فروشگاه
+ /
+ پشتیبان هوشمند سایت
+
+
+
+ پشتیبان هوشمند سایت (Smart Support Chat)
+
+
+ پیکربندی هوش مصنوعی دستیار مشتری، مدل زبانی، کلید شناور سایت و تحلیل مکالمات کاربران
+
+
+
+
+
+
+
+ {/* Tabs */}
+
+
+
+
+
+ {/* Tab 1: Config */}
+ {activeTab === 'config' && (
+
+ {configError && (
+
+ )}
+
+ {isConfigLoading ? (
+
+
+
+ ) : !settings ? (
+
+
+
پیکربندی اولیه یافت نشد
+
برای فعالسازی پشتیبان هوشمند روی فروشگاه، تنظیمات اولیه را ثبت کنید.
+
+
+ ) : (
+
+ )}
+
+ )}
+
+ {/* Tab 2: Analytics */}
+ {activeTab === 'analytics' && (
+
+ {analyticsError && (
+
+ {analyticsError}
+
+ )}
+
+ {/* Filters */}
+
+
+
+ setDates({ ...dates, startDate: e.target.value })}
+ />
+
+
+
+ setDates({ ...dates, endDate: e.target.value })}
+ />
+
+
+
+
+ {/* Stats Grid */}
+ {stats && (
+
+ {[
+ ['گفتگوها', stats.conversations, 'text-blue-600', 'bg-blue-50'],
+ ['کل پیامها', stats.messages, 'text-purple-600', 'bg-purple-50'],
+ ['کاربران عضو', stats.authenticated, 'text-emerald-600', 'bg-emerald-50'],
+ ['مهمان', stats.anonymous, 'text-gray-600', 'bg-gray-100'],
+ ['بیپاسخ', stats.unanswered, 'text-red-600', 'bg-red-50'],
+ ['نیازمند پیگیری', stats.followup, 'text-amber-600', 'bg-amber-50'],
+ ['سیگنال هشدار', stats.escalated, 'text-rose-600', 'bg-rose-50'],
+ ].map(([label, value, textColor, bgColor]) => (
+
+ ))}
+
+ )}
+
+ {/* Conversations list */}
+ {isAnalyticsLoading ? (
+
+
+
+ ) : conversations.length === 0 ? (
+
+
+ هنوز مکالمهای با پشتیبان هوشمند ثبت نشده است.
+
+ ) : (
+
+ {conversations.map((row) => (
+
+
+
+
+ {row.user
+ ? `${row.user.firstName || ''} ${row.user.lastName || ''}`.trim() || 'کاربر ثبتنامشده'
+ : 'مشتری مهمان'}
+
+ {row.user?.mobile && (
+
+ {row.user.mobile}
+
+ )}
+
+
+
+ {new Date(row.updatedAt).toLocaleString('fa-IR')}
+
+
+
+
+ {row.unanswered && بیپاسخ}
+ {row.needsFollowup && نیازمند پیگیری}
+ {row.escalationSignal && ارجاع فوری}
+ {row.entryPath && صفحه: {row.entryPath}}
+
+
+
+ {row.messages.map((m, i) => (
+
+
+ {m.role === 'user' ? '👤 پیام مشتری:' : '🤖 پاسخ پشتیبان هوشمند:'}
+
+
{m.content}
+
+ ))}
+
+
+ ))}
+
+ )}
+
+ )}
+
+ );
}
diff --git a/frontend/admin-panel/src/routes/adminRoutes.tsx b/frontend/admin-panel/src/routes/adminRoutes.tsx
index 65bd6ab9..3721a51e 100644
--- a/frontend/admin-panel/src/routes/adminRoutes.tsx
+++ b/frontend/admin-panel/src/routes/adminRoutes.tsx
@@ -13,7 +13,6 @@ const Products = lazyWithRetry(() => import('../pages/Products'));
const Orders = lazyWithRetry(() => import('../pages/Orders'));
const Coupons = lazyWithRetry(() => import('../pages/Coupons'));
const SmartChatSettingsPage = lazyWithRetry(() => import('../pages/SmartChatSettingsPage'));
-const SupportChatAnalyticsPage = lazyWithRetry(() => import('../pages/SupportChatAnalyticsPage'));
const Settings = lazyWithRetry(() => import('../pages/Settings'));
const Reports = lazyWithRetry(() => import('../pages/Reports'));
const Categories = lazyWithRetry(() => import('../pages/Categories'));
@@ -83,7 +82,7 @@ export const router = createBrowserRouter([
{ path: 'zibal-portal/*', element: },
{ path: 'coupons/*', element: },
{ path: 'settings', element: },
- { path: 'settings/smart-chat', element: },
+ { path: 'settings/smart-chat', element: },
{ path: 'settings/smart-chat/config', element: },
{ path: 'settings/payment-methods', element: },
{ path: 'settings/shipping', element: },
diff --git a/frontend/application/app/layout.tsx b/frontend/application/app/layout.tsx
index daacc485..20f70796 100644
--- a/frontend/application/app/layout.tsx
+++ b/frontend/application/app/layout.tsx
@@ -202,7 +202,7 @@ export default async function RootLayout({
{children}
-
+
{/* Deferred Analytics (GTM, GA4, Clarity) to unblock Main Thread */}
{
+ const handler = () => setIsOpen(true);
+ window.addEventListener('canina-open-advisor-modal', handler);
+ return () => window.removeEventListener('canina-open-advisor-modal', handler);
+ }, []);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [phone, setPhone] = useState('');
@@ -66,14 +73,16 @@ export default function ContactAdvisorButton({ productId, productName }: Contact
return (
<>
{/* Floating Action Button */}
-
+ {!hideFloatingButton && (
+
+ )}
{/* Modal */}
{isOpen && (
diff --git a/frontend/application/components/SupportChat.test.tsx b/frontend/application/components/SupportChat.test.tsx
index 6e65b327..6b604ec4 100644
--- a/frontend/application/components/SupportChat.test.tsx
+++ b/frontend/application/components/SupportChat.test.tsx
@@ -28,4 +28,12 @@ describe('support widget', () => {
localStorage.setItem('accessToken','bob'); fireEvent.focus(window);
await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull());
});
+ it('dispatches advisor event when phone button clicked', async () => {
+ const handler = vi.fn();
+ window.addEventListener('canina-open-advisor-modal', handler);
+ render();
+ fireEvent.click(screen.getByRole('button', { name: /درخواست مشاوره تلفنی/ }));
+ expect(handler).toHaveBeenCalled();
+ window.removeEventListener('canina-open-advisor-modal', handler);
+ });
});
diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx
index 4ac4ba33..19261c00 100644
--- a/frontend/application/components/SupportChat.tsx
+++ b/frontend/application/components/SupportChat.tsx
@@ -1,5 +1,6 @@
'use client';
import { FormEvent, useEffect, useRef, useState } from 'react';
+import { PhoneCall, MessageSquare } from 'lucide-react';
type PersistedMessage = { role: 'user' | 'assistant'; content: string };
@@ -168,32 +169,49 @@ export default function SupportChat() {
if (!config?.enabled) return configError ? تنظیمات پشتیبان هوشمند در دسترس نیست. : null;
const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon];
return (
-