feat: 2-piece unified floating pill, smart-chat settings redesign, FAQ cleanup script
Deploy Canina / deploy (push) Successful in 5m7s

This commit is contained in:
devops committed 2026-11-07 15:52:17 +00:00
1 parent 054b9470ab
commit 27b61ce6d5
11 files changed
+849 -91

No files matched your search

+65
View File
@@ -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();
});
@@ -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' },
],
},
{
@@ -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(<FAQManager />);
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();
});
});
+34 -11
View File
@@ -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<FAQ[]>([]);
const [searchTerm, setSearchTerm] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingFaq, setEditingFaq] = useState<FAQ | null>(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 (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
@@ -142,30 +150,45 @@ export default function FAQManager() {
</Button>
</div>
{/* Info Box */}
{/* Info Box & Search Filter */}
<div className="bg-orange-50 border border-orange-200 rounded-xl p-4 text-sm text-orange-800">
<strong>💡 نکته SEO:</strong> سوالات فعال به صورت خودکار با markup <code className="bg-orange-100 px-1 rounded">FAQPage</code> در صفحه اصلی نمایش داده می‌شوند و در نتایج گوگل به عنوان Rich Snippet ظاهر می‌شوند.
</div>
<div className="relative">
<Search className="w-5 h-5 text-gray-400 absolute right-3.5 top-3 pointer-events-none" />
<input
type="text"
placeholder="جستجو در متن سوال یا پاسخ متداول..."
value={searchTerm}
onChange={(e) => 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"
/>
</div>
{/* List */}
<div className="space-y-3">
{isLoading ? (
<div className="flex justify-center py-12">
<Spinner size="lg" className="text-purple-600" />
</div>
) : faqs.length === 0 ? (
) : filteredFaqs.length === 0 ? (
<div className="bg-white rounded-2xl border border-gray-200 py-16 text-center">
<HelpCircle className="w-12 h-12 text-gray-300 mx-auto mb-3" />
<p className="text-gray-500 font-medium">هیچ سوالی ثبت نشده است</p>
<button
onClick={() => openModal()}
className="mt-4 text-purple-600 font-bold hover:underline text-sm cursor-pointer"
>
اولین سوال را اضافه کنید
</button>
<p className="text-gray-500 font-medium">
{searchTerm ? 'هیچ سوالی با این عبارت یافت نشد' : 'هیچ سوالی ثبت نشده است'}
</p>
{!searchTerm && (
<button
onClick={() => openModal()}
className="mt-4 text-purple-600 font-bold hover:underline text-sm cursor-pointer"
>
اولین سوال را اضافه کنید
</button>
)}
</div>
) : (
faqs.map((faq) => (
filteredFaqs.map((faq) => (
<div
key={faq.id}
className={`bg-white rounded-2xl border p-5 transition-all ${
@@ -0,0 +1,140 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import SmartChatSettingsPage from './SmartChatSettingsPage';
import api from '../services/api';
import { toast } from 'react-hot-toast';
vi.mock('../services/api', () => ({
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) => <a href={to} className={className}>{children}</a>,
}));
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(<SmartChatSettingsPage />);
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(<SmartChatSettingsPage />);
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(<SmartChatSettingsPage />);
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();
});
});
});
@@ -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<string, number>;
};
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<Settings | null>(null);
const [activeTab, setActiveTab] = useState<'config' | 'analytics'>('config');
// Config State
const [settings, setSettings] = useState<SettingsState | null>(null);
const [providers, setProviders] = useState<Provider[]>([]);
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<Stats | null>(null);
const [conversations, setConversations] = useState<Conversation[]>([]);
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<string, string> = { chat: '💬', paw: '🐾', bot: '🤖' };
return <div dir="rtl" className="space-y-6 font-vazir">
<Link to="/settings">← تنظیمات فروشگاه</Link>
<h2 className="text-2xl font-black">پشتیبان هوشمند سایت</h2>
<p>انتخاب مدل برای تشخیص درخواست و پاسخ‌گویی یکسان است. اطلاعات حساب مشتری به مدل ارسال نمی‌شود.</p>
{error && <div role="alert" className="rounded-xl bg-amber-50 p-4">{error} <button type="button" onClick={load}>تلاش دوباره</button></div>}
{!settings ? <Button onClick={() => setSettings({ enabled: false, provider: '', model: '', label: '', icon: 'chat' })}>ایجاد تنظیمات جدید</Button> :
<form onSubmit={save} className="space-y-5 rounded-2xl bg-white p-6 border border-gray-200">
<label className="flex gap-2"><input type="checkbox" checked={settings.enabled} onChange={e => setSettings({ ...settings, enabled: e.target.checked })} />فعال‌سازی پشتیبان هوشمند</label>
<label className="block">ارائه‌دهنده<select aria-label="ارائه‌دهنده" className="block border rounded-xl p-3 w-full" value={settings.provider} onChange={e => setSettings({ ...settings, provider: e.target.value, model: '' })}>
<option value="">انتخاب ارائه‌دهنده</option>{providers.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
</select></label>
<label className="block">مدل<select aria-label="مدل" disabled={!settings.provider} className="block border rounded-xl p-3 w-full" value={settings.model} onChange={e => setSettings({ ...settings, model: e.target.value })}>
<option value="">انتخاب مدل</option>{providers.find(p => p.id === settings.provider)?.models.map(m => <option key={m} value={m}>{m}</option>)}
</select></label>
<label className="block">نام دکمه و دستیار<input aria-label="نام دکمه و دستیار" required maxLength={60} className="block border rounded-xl p-3 w-full" value={settings.label} onChange={e => setSettings({ ...settings, label: e.target.value })} /></label>
<label className="block">آیکون دستیار<select aria-label="آیکون دستیار" className="block border rounded-xl p-3 w-full" value={settings.icon} onChange={e => setSettings({ ...settings, icon: e.target.value })}><option value="chat">💬 گفتگو</option><option value="paw">🐾 پنجه</option><option value="bot">🤖 ربات</option></select></label>
<p className="text-sm text-gray-500">برای امنیت سایت فقط آیکون‌های داخلی قابل انتخاب هستند؛ نشانی یا SVG دلخواه پذیرفته نمی‌شود.</p>
<div aria-label="پیش‌نمایش دکمه" className="inline-flex gap-2 rounded-full bg-[#1E4053] text-white px-4 py-3"><span>{icons[settings.icon]}</span><span>{settings.label}</span></div>
<div><Button type="submit" disabled={saving || (settings.enabled && (!settings.provider || !settings.model))}>{saving ? 'در حال ذخیره…' : 'ذخیره تنظیمات'}</Button></div>
</form>}
</div>;
const icons: Record<string, string> = {
chat: '💬',
paw: '🐾',
bot: '🤖',
};
return (
<div className="space-y-6 pb-12 font-vazir text-gray-800" dir="rtl">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<div className="flex items-center gap-2 text-xs text-gray-400 mb-1">
<Link to="/settings" className="hover:text-purple-600 transition">تنظیمات فروشگاه</Link>
<span>/</span>
<span className="text-gray-600 font-bold">پشتیبان هوشمند سایت</span>
</div>
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
<Bot className="h-7 w-7 text-purple-600" />
پشتیبان هوشمند سایت (Smart Support Chat)
</h1>
<p className="mt-1 text-sm text-gray-500">
پیکربندی هوش مصنوعی دستیار مشتری، مدل زبانی، کلید شناور سایت و تحلیل مکالمات کاربران
</p>
</div>
<div className="flex items-center gap-3">
<Button
variant="outline"
size="sm"
onClick={() => {
loadConfig();
loadAnalytics();
}}
>
<RefreshCw 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('config')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'config'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Sliders className="h-4 w-4" />
تنظیمات و پیکربندی دستیار
</button>
<button
onClick={() => setActiveTab('analytics')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'analytics'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<BarChart3 className="h-4 w-4" />
تحلیل و تاریخچه مکالمات
{stats && stats.conversations > 0 && (
<span className="rounded-full bg-purple-100 px-2 py-0.5 text-xs font-bold text-purple-700">
{stats.conversations}
</span>
)}
</button>
</div>
{/* Tab 1: Config */}
{activeTab === 'config' && (
<div className="space-y-6">
{configError && (
<div
role="alert"
className="flex items-center justify-between rounded-2xl border border-amber-200 bg-amber-50/80 p-4 text-sm text-amber-800 shadow-sm"
>
<div className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-amber-600 flex-shrink-0" />
<span>{configError}</span>
</div>
<button
type="button"
onClick={loadConfig}
className="font-bold text-purple-700 hover:underline"
>
تلاش دوباره
</button>
</div>
)}
{isConfigLoading ? (
<div className="flex h-64 items-center justify-center rounded-2xl border border-gray-100 bg-white shadow-sm">
<Spinner size="lg" />
</div>
) : !settings ? (
<div className="rounded-2xl border border-dashed border-gray-300 bg-white p-12 text-center shadow-sm">
<Bot className="mx-auto h-12 w-12 text-gray-400 mb-3" />
<h3 className="text-lg font-bold text-gray-800 mb-1">پیکربندی اولیه یافت نشد</h3>
<p className="text-sm text-gray-500 mb-6">برای فعال‌سازی پشتیبان هوشمند روی فروشگاه، تنظیمات اولیه را ثبت کنید.</p>
<Button
onClick={() =>
setSettings({
enabled: false,
provider: providers[0]?.id || '',
model: providers[0]?.models[0] || '',
label: 'گفتگو با پشتیبان',
icon: 'chat',
})
}
>
ایجاد تنظیمات جدید
</Button>
</div>
) : (
<form onSubmit={handleSave} className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Main settings card */}
<div className="lg:col-span-2 space-y-6">
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm space-y-5">
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
<div>
<h3 className="text-lg font-bold text-gray-900">وضعیت سرویس هوش مصنوعی</h3>
<p className="text-xs text-gray-500">فعال یا غیرفعال بودن پنجره چت در فروشگاه</p>
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={settings.enabled}
onChange={(e) => setSettings({ ...settings, 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 md:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">ارائه‌دهنده سرویس (Provider)</label>
<select
aria-label="ارائه‌دهنده"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none bg-white"
value={settings.provider}
onChange={(e) =>
setSettings({ ...settings, provider: e.target.value, model: '' })
}
>
<option value="">انتخاب ارائه‌دهنده</option>
{providers.map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">مدل هوش مصنوعی (AI Model)</label>
<select
aria-label="مدل"
disabled={!settings.provider}
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none bg-white disabled:bg-gray-50 disabled:text-gray-400"
value={settings.model}
onChange={(e) => setSettings({ ...settings, model: e.target.value })}
>
<option value="">انتخاب مدل</option>
{providers
.find((p) => p.id === settings.provider)
?.models.map((m) => (
<option key={m} value={m}>
{m}
</option>
))}
</select>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام دکمه و دستیار</label>
<input
aria-label="نام دکمه و دستیار"
required
maxLength={60}
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
value={settings.label}
onChange={(e) => setSettings({ ...settings, label: e.target.value })}
placeholder="گفتگو با پشتیبان"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">آیکون دستیار</label>
<select
aria-label="آیکون دستیار"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none bg-white"
value={settings.icon}
onChange={(e) => setSettings({ ...settings, icon: e.target.value })}
>
<option value="chat">💬 گفتگو (Chat)</option>
<option value="paw">🐾 پنجه حیوانات (Paw)</option>
<option value="bot">🤖 ربات هوشمند (Bot)</option>
</select>
</div>
</div>
<div className="pt-4 border-t border-gray-100 flex items-center justify-between">
<p className="text-xs text-gray-400">
برای امنیت کامل فروشگاه، فقط آیکون‌های استاندارد داخلی سامانه مجاز هستند.
</p>
<Button
type="submit"
disabled={isSaving || (settings.enabled && (!settings.provider || !settings.model))}
>
{isSaving ? <Spinner size="sm" /> : 'ذخیره تنظیمات'}
</Button>
</div>
</div>
</div>
{/* Sidebar preview card */}
<div className="space-y-6">
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm space-y-4">
<h4 className="text-sm font-bold text-gray-900 flex items-center gap-2">
<Sparkles className="h-4 w-4 text-purple-600" />
پیش‌نمایش زنده المان در فروشگاه
</h4>
<p className="text-xs text-gray-500 leading-relaxed">
نحوه نمایش دکمه در کپسول دو تکه ناوبری مشتری:
</p>
<div className="p-6 rounded-2xl bg-gray-50 border border-gray-200 flex flex-col items-center justify-center gap-3">
<div
aria-label="پیش‌نمایش دکمه"
className="inline-flex items-center gap-2 rounded-full bg-[#1E4053] text-white px-5 py-2.5 shadow-md font-bold text-sm"
>
<span>{icons[settings.icon] || '💬'}</span>
<span>{settings.label || 'گفتگو با پشتیبان'}</span>
</div>
<span className="text-[11px] text-gray-400">
وضعیت کنونی: {settings.enabled ? '🟢 فعال در فروشگاه' : '🔴 غیرفعال'}
</span>
</div>
<div className="rounded-xl bg-purple-50/50 p-4 border border-purple-100 text-xs text-purple-800 space-y-2">
<div className="font-bold flex items-center gap-1.5">
<ShieldCheck className="h-4 w-4 text-purple-600" />
امنیت و حریم خصوصی داده‌ها
</div>
<p className="leading-relaxed text-gray-600">
انتخاب مدل برای تشخیص نوع درخواست و پاسخ‌گویی به صورت یکپارچه عمل می‌کند. هیچ اطلاعات هویتی یا اطلاعات حساب کاربری به مدل ارسال نخواهد شد.
</p>
</div>
</div>
</div>
</form>
)}
</div>
)}
{/* Tab 2: Analytics */}
{activeTab === 'analytics' && (
<div className="space-y-6">
{analyticsError && (
<div role="alert" className="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
{analyticsError}
</div>
)}
{/* Filters */}
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm flex flex-wrap items-end gap-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">از تاریخ</label>
<input
type="date"
className="rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
value={dates.startDate}
onChange={(e) => setDates({ ...dates, startDate: e.target.value })}
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">تا تاریخ</label>
<input
type="date"
className="rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
value={dates.endDate}
onChange={(e) => setDates({ ...dates, endDate: e.target.value })}
/>
</div>
<Button variant="secondary" onClick={loadAnalytics} disabled={isAnalyticsLoading}>
اعمال فیلتر
</Button>
</div>
{/* Stats Grid */}
{stats && (
<div className="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-7">
{[
['گفتگوها', 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]) => (
<div key={String(label)} className="rounded-2xl border border-gray-100 bg-white p-4 shadow-sm text-center">
<div className="text-xs font-bold text-gray-500 mb-1">{label}</div>
<div className={`text-2xl font-black ${textColor}`}>{value}</div>
</div>
))}
</div>
)}
{/* Conversations list */}
{isAnalyticsLoading ? (
<div className="flex h-64 items-center justify-center rounded-2xl border border-gray-100 bg-white shadow-sm">
<Spinner size="lg" />
</div>
) : conversations.length === 0 ? (
<div className="rounded-2xl border border-dashed border-gray-300 bg-white p-12 text-center text-gray-400">
<MessageSquare className="mx-auto h-12 w-12 text-gray-300 mb-2" />
هنوز مکالمه‌ای با پشتیبان هوشمند ثبت نشده است.
</div>
) : (
<div className="space-y-4">
{conversations.map((row) => (
<article key={row.id} className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm space-y-3">
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
<div className="flex items-center gap-2">
<span className="font-bold text-sm text-gray-900">
{row.user
? `${row.user.firstName || ''} ${row.user.lastName || ''}`.trim() || 'کاربر ثبت‌نام‌شده'
: 'مشتری مهمان'}
</span>
{row.user?.mobile && (
<span className="text-xs font-mono text-gray-500 bg-gray-100 px-2 py-0.5 rounded-lg">
{row.user.mobile}
</span>
)}
</div>
<div className="text-xs text-gray-400 flex items-center gap-1">
<Clock className="h-3 w-3" />
{new Date(row.updatedAt).toLocaleString('fa-IR')}
</div>
</div>
<div className="flex gap-2 text-xs">
{row.unanswered && <span className="rounded-lg bg-red-50 text-red-700 px-2.5 py-1 font-bold">بی‌پاسخ</span>}
{row.needsFollowup && <span className="rounded-lg bg-amber-50 text-amber-700 px-2.5 py-1 font-bold">نیازمند پیگیری</span>}
{row.escalationSignal && <span className="rounded-lg bg-rose-50 text-rose-700 px-2.5 py-1 font-bold">ارجاع فوری</span>}
{row.entryPath && <span className="rounded-lg bg-gray-50 text-gray-500 px-2.5 py-1 font-mono">صفحه: {row.entryPath}</span>}
</div>
<div className="space-y-2 pt-1">
{row.messages.map((m, i) => (
<div
key={`${row.id}-${i}`}
className={`rounded-xl p-3 text-sm leading-relaxed ${
m.role === 'user' ? 'bg-purple-50/70 border border-purple-100 text-purple-950 mr-4' : 'bg-gray-50 border border-gray-100 text-gray-800 ml-4'
}`}
>
<div className="font-bold text-xs text-gray-500 mb-1">
{m.role === 'user' ? '👤 پیام مشتری:' : '🤖 پاسخ پشتیبان هوشمند:'}
</div>
<div>{m.content}</div>
</div>
))}
</div>
</article>
))}
</div>
)}
</div>
)}
</div>
);
}
@@ -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: <ZibalPortalPage /> },
{ path: 'coupons/*', element: <Coupons /> },
{ path: 'settings', element: <Settings /> },
{ path: 'settings/smart-chat', element: <SupportChatAnalyticsPage /> },
{ path: 'settings/smart-chat', element: <SmartChatSettingsPage /> },
{ path: 'settings/smart-chat/config', element: <SmartChatSettingsPage /> },
{ path: 'settings/payment-methods', element: <PaymentGatewaysPage /> },
{ path: 'settings/shipping', element: <ShippingSettingsPage /> },
+1 -1
View File
@@ -202,7 +202,7 @@ export default async function RootLayout({
{children}
</ClientLayout>
<SupportChat />
<ContactAdvisorButton />
<ContactAdvisorButton hideFloatingButton={true} />
{/* Deferred Analytics (GTM, GA4, Clarity) to unblock Main Thread */}
<AnalyticsDeferred
@@ -1,14 +1,21 @@
'use client';
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { PhoneCall, X, CheckCircle2, AlertCircle } from 'lucide-react';
interface ContactAdvisorButtonProps {
productId?: string;
productName?: string;
hideFloatingButton?: boolean;
}
export default function ContactAdvisorButton({ productId, productName }: ContactAdvisorButtonProps) {
export default function ContactAdvisorButton({ productId, productName, hideFloatingButton = false }: ContactAdvisorButtonProps) {
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
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 */}
<button
type="button"
onClick={() => setIsOpen(true)}
className="fixed bottom-6 left-6 z-40 flex items-center gap-2.5 rounded-full bg-emerald-600 px-5 py-3.5 text-white font-bold shadow-lg shadow-emerald-600/30 transition-all hover:bg-emerald-700 hover:scale-105 active:scale-95"
>
<PhoneCall className="h-5 w-5 animate-pulse" />
<span>مشاوره و تماس رایگان</span>
</button>
{!hideFloatingButton && (
<button
type="button"
onClick={() => setIsOpen(true)}
className="fixed bottom-6 left-6 z-40 flex items-center gap-2.5 rounded-full bg-emerald-600 px-5 py-3.5 text-white font-bold shadow-lg shadow-emerald-600/30 transition-all hover:bg-emerald-700 hover:scale-105 active:scale-95"
>
<PhoneCall className="h-5 w-5 animate-pulse" />
<span>مشاوره و تماس رایگان</span>
</button>
)}
{/* Modal */}
{isOpen && (
@@ -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(<SupportChat/>);
fireEvent.click(screen.getByRole('button', { name: /درخواست مشاوره تلفنی/ }));
expect(handler).toHaveBeenCalled();
window.removeEventListener('canina-open-advisor-modal', handler);
});
});
+41 -23
View File
@@ -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 ? <span role="status" className="sr-only">تنظیمات پشتیبان هوشمند در دسترس نیست.</span> : null;
const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon];
return (
<aside dir="rtl" className="fixed bottom-20 left-5 z-30 max-w-[calc(100vw-2.5rem)] font-vazir select-none">
{/* Floating Launcher Button */}
<button
type="button"
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-label={open ? 'بستن گفتگو با پشتیبان' : config.label}
className={`group relative flex items-center gap-2.5 rounded-full px-4 py-3 text-white shadow-2xl transition-all duration-300 ${
open
? 'bg-medical-gray-800 hover:bg-medical-gray-900 rotate-0'
: 'bg-canina-blue hover:bg-opacity-95 hover:shadow-canina-blue/30 hover:scale-105'
}`}
>
<span className="relative flex h-3 w-3">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-canina-gold opacity-75"></span>
<span className="relative inline-flex h-3 w-3 rounded-full bg-canina-gold"></span>
</span>
<svg className="h-5 w-5 transition-transform duration-300 group-hover:scale-110" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<aside dir="rtl" className="fixed bottom-6 left-6 z-40 max-w-[calc(100vw-2.5rem)] font-vazir select-none">
{/* 2-Piece Unified Floating Action Pill */}
<div className="flex items-center rounded-full bg-slate-900/90 p-1 text-white shadow-2xl backdrop-blur-md border border-white/10">
{/* Piece 1: Online Support Chat Button */}
<button
type="button"
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-label={open ? 'بستن گفتگو با پشتیبان' : (config.label || 'پشتیبان آنلاین')}
className={`flex items-center gap-2 rounded-full px-4 py-2.5 text-xs sm:text-sm font-bold transition-all duration-200 ${
open
? 'bg-rose-600 text-white shadow-md'
: 'bg-transparent text-white hover:bg-white/10 active:scale-95'
}`}
>
{open ? (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M6 18L18 6M6 6l12 12" />
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M6 18L18 6M6 6l12 12" />
</svg>
) : (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
<MessageSquare className="h-4 w-4 text-amber-400" />
)}
</svg>
<span className="text-sm font-semibold tracking-wide">{!open && <span aria-label="آیکون دستیار">{botIcon}</span>}{open ? 'بستن گفتگو' : config.label}</span>
</button>
<span>{open ? 'بستن گفتگو' : (config.label || 'پشتیبان آنلاین')}</span>
</button>
{/* Divider */}
<div className="h-4 w-px bg-white/20 mx-1" />
{/* Piece 2: Phone Advisor Request Button */}
<button
type="button"
onClick={() => {
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('canina-open-advisor-modal'));
}
}}
aria-label="درخواست مشاوره تلفنی"
className="flex items-center gap-2 rounded-full px-4 py-2.5 text-xs sm:text-sm font-bold bg-transparent text-white hover:bg-white/10 active:scale-95 transition-all duration-200"
>
<PhoneCall className="h-4 w-4 text-emerald-400" />
<span>درخواست مشاوره تلفنی</span>
</button>
</div>
{/* Chat Window */}
{open && (