From 27b61ce6d532152099aeff0014123ffa728b07d0 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 7 Nov 2026 15:52:17 +0000 Subject: [PATCH] feat: 2-piece unified floating pill, smart-chat settings redesign, FAQ cleanup script --- backend/scripts/clean-faqs.ts | 65 ++ .../admin-panel/src/components/Sidebar.tsx | 2 +- .../admin-panel/src/pages/FAQManager.test.tsx | 16 + frontend/admin-panel/src/pages/FAQManager.tsx | 45 +- .../src/pages/SmartChatSettingsPage.test.tsx | 140 +++++ .../src/pages/SmartChatSettingsPage.tsx | 566 ++++++++++++++++-- .../admin-panel/src/routes/adminRoutes.tsx | 3 +- frontend/application/app/layout.tsx | 2 +- .../components/ContactAdvisorButton.tsx | 29 +- .../components/SupportChat.test.tsx | 8 + .../application/components/SupportChat.tsx | 64 +- 11 files changed, 849 insertions(+), 91 deletions(-) create mode 100644 backend/scripts/clean-faqs.ts create mode 100644 frontend/admin-panel/src/pages/SmartChatSettingsPage.test.tsx diff --git a/backend/scripts/clean-faqs.ts b/backend/scripts/clean-faqs.ts new file mode 100644 index 00000000..231a860d --- /dev/null +++ b/backend/scripts/clean-faqs.ts @@ -0,0 +1,65 @@ +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +async function main() { + console.log('--- Inspecting and Cleaning FAQs ---'); + + const totalBefore = await prisma.fAQ.count(); + console.log(`Total FAQs before: ${totalBefore}`); + + const activeCount = await prisma.fAQ.count({ where: { isActive: true } }); + const inactiveCount = await prisma.fAQ.count({ where: { isActive: false } }); + console.log(`Active FAQs: ${activeCount}, Inactive FAQs: ${inactiveCount}`); + + // Fetch sample of active and inactive + const sampleActive = await prisma.fAQ.findMany({ + where: { isActive: true }, + select: { id: true, question: true, order: true }, + take: 5, + }); + console.log('Sample Active FAQs:', JSON.stringify(sampleActive, null, 2)); + + // Find tasks that contain content development phrases + const tasksToDelete = await prisma.fAQ.findMany({ + where: { + OR: [ + { question: { contains: 'راهنمای' } }, + { question: { contains: 'اینفوگرافیک' } }, + { question: { contains: 'نگارش' } }, + { question: { contains: 'تدوین' } }, + { question: { contains: 'تولید' } }, + { question: { contains: 'مقاله' } }, + ], + }, + select: { id: true, question: true, isActive: true }, + }); + + console.log(`Found ${tasksToDelete.length} content tasks inside FAQs table.`); + + if (tasksToDelete.length > 0) { + const ids = tasksToDelete.map(t => t.id); + const deleteResult = await prisma.fAQ.deleteMany({ + where: { id: { in: ids } }, + }); + console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks from faqs.`); + } + + const totalAfter = await prisma.fAQ.count(); + console.log(`Total FAQs remaining: ${totalAfter}`); + + const remaining = await prisma.fAQ.findMany({ + select: { id: true, question: true, isActive: true, order: true }, + take: 10, + }); + console.log('Remaining FAQs:', JSON.stringify(remaining, null, 2)); +} + +main() + .catch(e => { + console.error(e); + process.exit(1); + }) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index 5f3cce26..6b63a9e3 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -110,7 +110,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side items: [ { icon: LayoutDashboard, label: 'نمای کلی داشبورد', path: '/' }, { icon: TrendingUp, label: 'گزارشات و تحلیل فروش', path: '/reports' }, - { icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' }, + { icon: MessageSquare, label: 'پشتیبان هوشمند سایت', path: '/settings/smart-chat' }, ], }, { diff --git a/frontend/admin-panel/src/pages/FAQManager.test.tsx b/frontend/admin-panel/src/pages/FAQManager.test.tsx index 55b14f93..b7ae7967 100644 --- a/frontend/admin-panel/src/pages/FAQManager.test.tsx +++ b/frontend/admin-panel/src/pages/FAQManager.test.tsx @@ -214,4 +214,20 @@ describe('FAQManager Component', () => { expect(toast.success).toHaveBeenCalledWith('سوال حذف شد'); }); }); + + it('filters FAQs by search term', async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs }); + render(); + + await waitFor(() => { + expect(screen.getByText('سوال اول تست')).toBeTruthy(); + expect(screen.getByText('سوال دوم تست')).toBeTruthy(); + }); + + const searchInput = screen.getByPlaceholderText('جستجو در متن سوال یا پاسخ متداول...'); + fireEvent.change(searchInput, { target: { value: 'سوال اول' } }); + + expect(screen.getByText('سوال اول تست')).toBeTruthy(); + expect(screen.queryByText('سوال دوم تست')).toBeNull(); + }); }); diff --git a/frontend/admin-panel/src/pages/FAQManager.tsx b/frontend/admin-panel/src/pages/FAQManager.tsx index 7716afd0..7316115b 100644 --- a/frontend/admin-panel/src/pages/FAQManager.tsx +++ b/frontend/admin-panel/src/pages/FAQManager.tsx @@ -1,4 +1,4 @@ -import { Edit2,HelpCircle,Plus,ToggleLeft,ToggleRight,Trash2 } from 'lucide-react'; +import { Edit2,HelpCircle,Plus,ToggleLeft,ToggleRight,Trash2,Search } from 'lucide-react'; import { useCallback,useEffect,useState } from 'react'; import { toast } from 'react-hot-toast'; import Button from '../components/ui/Button'; @@ -20,6 +20,7 @@ interface FAQ { export default function FAQManager() { const [faqs, setFaqs] = useState([]); + const [searchTerm, setSearchTerm] = useState(''); const [isLoading, setIsLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [editingFaq, setEditingFaq] = useState(null); @@ -120,6 +121,13 @@ export default function FAQManager() { } }; + const filteredFaqs = faqs.filter( + (f) => + !searchTerm.trim() || + f.question.toLowerCase().includes(searchTerm.toLowerCase()) || + f.answer.toLowerCase().includes(searchTerm.toLowerCase()) + ); + return (
@@ -142,30 +150,45 @@ export default function FAQManager() {
- {/* Info Box */} + {/* Info Box & Search Filter */}
💡 نکته SEO: سوالات فعال به صورت خودکار با markup FAQPage در صفحه اصلی نمایش داده می‌شوند و در نتایج گوگل به عنوان Rich Snippet ظاهر می‌شوند.
+
+ + setSearchTerm(e.target.value)} + className="w-full pl-4 pr-11 py-2.5 bg-white border border-gray-200 rounded-xl text-sm focus:border-orange-500 focus:outline-none" + /> +
+ {/* List */}
{isLoading ? (
- ) : faqs.length === 0 ? ( + ) : filteredFaqs.length === 0 ? (
-

هیچ سوالی ثبت نشده است

- +

+ {searchTerm ? 'هیچ سوالی با این عبارت یافت نشد' : 'هیچ سوالی ثبت نشده است'} +

+ {!searchTerm && ( + + )}
) : ( - 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 ? : -
- - - - - -

برای امنیت سایت فقط آیکون‌های داخلی قابل انتخاب هستند؛ نشانی یا SVG دلخواه پذیرفته نمی‌شود.

-
{icons[settings.icon]}{settings.label}
-
-
} -
; + + const icons: Record = { + chat: '💬', + paw: '🐾', + bot: '🤖', + }; + + return ( +
+ {/* Header */} +
+
+
+ تنظیمات فروشگاه + / + پشتیبان هوشمند سایت +
+

+ + پشتیبان هوشمند سایت (Smart Support Chat) +

+

+ پیکربندی هوش مصنوعی دستیار مشتری، مدل زبانی، کلید شناور سایت و تحلیل مکالمات کاربران +

+
+
+ +
+
+ + {/* Tabs */} +
+ + +
+ + {/* Tab 1: Config */} + {activeTab === 'config' && ( +
+ {configError && ( +
+
+ + {configError} +
+ +
+ )} + + {isConfigLoading ? ( +
+ +
+ ) : !settings ? ( +
+ +

پیکربندی اولیه یافت نشد

+

برای فعال‌سازی پشتیبان هوشمند روی فروشگاه، تنظیمات اولیه را ثبت کنید.

+ +
+ ) : ( +
+ {/* Main settings card */} +
+
+
+
+

وضعیت سرویس هوش مصنوعی

+

فعال یا غیرفعال بودن پنجره چت در فروشگاه

+
+ +
+ +
+
+ + +
+ +
+ + +
+
+ +
+
+ + setSettings({ ...settings, label: e.target.value })} + placeholder="گفتگو با پشتیبان" + /> +
+ +
+ + +
+
+ +
+

+ برای امنیت کامل فروشگاه، فقط آیکون‌های استاندارد داخلی سامانه مجاز هستند. +

+ +
+
+
+ + {/* Sidebar preview card */} +
+
+

+ + پیش‌نمایش زنده المان در فروشگاه +

+

+ نحوه نمایش دکمه در کپسول دو تکه ناوبری مشتری: +

+ +
+
+ {icons[settings.icon] || '💬'} + {settings.label || 'گفتگو با پشتیبان'} +
+ + وضعیت کنونی: {settings.enabled ? '🟢 فعال در فروشگاه' : '🔴 غیرفعال'} + +
+ +
+
+ + امنیت و حریم خصوصی داده‌ها +
+

+ انتخاب مدل برای تشخیص نوع درخواست و پاسخ‌گویی به صورت یکپارچه عمل می‌کند. هیچ اطلاعات هویتی یا اطلاعات حساب کاربری به مدل ارسال نخواهد شد. +

+
+
+
+
+ )} +
+ )} + + {/* 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]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ )} + + {/* 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 ( -