feat(support-chat): modern brand UI and model-driven conversational intent recognition
This commit is contained in:
1 parent
85a4031c4a
commit
9aebe0ec43
6 files changed
+368
-72
No files matched your search
@@ -7,7 +7,7 @@ afterEach(() => { cleanup(); vi.restoreAllMocks(); localStorage.clear(); });
|
||||
describe('support widget', () => {
|
||||
it('submits only message and explicit scope, renders text safely', async () => {
|
||||
const fetcher=vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:'<script>bad</script>'})} as Response);
|
||||
render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:'گفتگو با پشتیبان'}));
|
||||
render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/}));
|
||||
fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'مکمل سگ'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
|
||||
await waitFor(()=>expect(screen.getByText('<script>bad</script>')).toBeTruthy());
|
||||
expect(JSON.parse(fetcher.mock.calls[0][1]!.body as string)).toEqual({message:'مکمل سگ',scope:'public'});
|
||||
@@ -15,14 +15,14 @@ describe('support widget', () => {
|
||||
});
|
||||
it('does not expose upstream errors', async()=> {
|
||||
vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response);
|
||||
render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:'گفتگو با پشتیبان'}));
|
||||
render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/}));
|
||||
fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'سلام'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
|
||||
await waitFor(()=>expect(screen.getByText(/فعلاً در دسترس نیست/)).toBeTruthy()); expect(screen.queryByText('secret-provider')).toBeNull();
|
||||
});
|
||||
it('clears transcript on account transition', async()=> {
|
||||
localStorage.setItem('accessToken','alice');
|
||||
vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:'private Alice'})} as Response);
|
||||
render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:'گفتگو با پشتیبان'})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'کیف پول'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
|
||||
render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'کیف پول'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
|
||||
await waitFor(()=>expect(screen.getByText('private Alice')).toBeTruthy());
|
||||
localStorage.setItem('accessToken','bob'); fireEvent.focus(window);
|
||||
await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull());
|
||||
|
||||
@@ -1,42 +1,288 @@
|
||||
'use client';
|
||||
import { FormEvent, useEffect, useRef, useState } from 'react';
|
||||
|
||||
const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
||||
const token = () => { try { return localStorage.getItem('accessToken') || ''; } catch { return ''; } };
|
||||
export default function SupportChat() {
|
||||
const [open,setOpen]=useState(false), [message,setMessage]=useState(''), [scope,setScope]=useState('public'), [busy,setBusy]=useState(false);
|
||||
const [rows,setRows]=useState<{question:string,answer:string}[]>([]);
|
||||
const identity=useRef(''), pending=useRef<AbortController|null>(null);
|
||||
useEffect(()=>{
|
||||
identity.current=token();
|
||||
const check=()=>{ if(identity.current!==token()){identity.current=token();pending.current?.abort();setRows([]);setMessage('');setScope('public');setBusy(false);} };
|
||||
window.addEventListener('focus',check);window.addEventListener('storage',check);
|
||||
const interval=window.setInterval(check,500);
|
||||
return ()=>{window.removeEventListener('focus',check);window.removeEventListener('storage',check);clearInterval(interval);pending.current?.abort();};
|
||||
},[]);
|
||||
async function send(event:FormEvent) {
|
||||
event.preventDefault();if(busy||!message.trim())return;
|
||||
const current=token(); if(current!==identity.current){setRows([]);identity.current=current;}
|
||||
const question=message.trim();setMessage('');setBusy(true);
|
||||
const controller=new AbortController();pending.current=controller;
|
||||
let answer=unavailable;
|
||||
const token = () => {
|
||||
try {
|
||||
const response=await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/ask`,{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest',...(current?{Authorization:`Bearer ${current}`}:{})},credentials:'include',body:JSON.stringify({message:question,scope}),signal:AbortSignal.any([controller.signal,AbortSignal.timeout(50000)])});
|
||||
if(response.status===401)answer='لطفاً دوباره وارد حساب کاربری شوید.';
|
||||
else if(response.ok){const data=await response.json();if(typeof data.answer==='string')answer=data.answer;}
|
||||
} catch {}
|
||||
if(!controller.signal.aborted&&token()===current)setRows(r=>[...r.slice(-9),{question,answer}]);
|
||||
if(pending.current===controller)setBusy(false);
|
||||
}
|
||||
return <aside dir="rtl" className="fixed bottom-24 left-4 z-[1000] max-w-[calc(100vw-2rem)]">
|
||||
<button type="button" onClick={()=>setOpen(!open)} aria-expanded={open} className="rounded-full bg-sky-700 p-3 text-white shadow-lg">{open?'بستن گفتگو':'گفتگو با پشتیبان'}</button>
|
||||
{open&&<section aria-label="پشتیبان کنینا" className="mt-2 w-80 rounded-xl border bg-white p-4 shadow-xl">
|
||||
<p className="text-sm">پشتیبان هوشمند کنینا · هر پیام مستقل است. اطلاعات پزشکی جایگزین دامپزشک نیست.</p>
|
||||
<div aria-live="polite" className="my-3 max-h-64 overflow-y-auto whitespace-pre-wrap text-sm">{rows.map((r,i)=><div key={i} className="my-3"><p className="font-bold">{r.question}</p><p>{r.answer}</p></div>)}{busy&&<p>در حال بررسی…</p>}</div>
|
||||
<form onSubmit={send}>
|
||||
<label className="text-sm">موضوع<select aria-label="موضوع گفتگو" value={scope} onChange={e=>setScope(e.target.value)} className="block w-full border p-2"><option value="public">محصولات و اطلاعات عمومی</option><option value="orders">سفارشهای من</option><option value="wallet">کیف پول من</option></select></label>
|
||||
<label className="text-sm">پیام شما<textarea aria-label="پیام شما" value={message} maxLength={1500} onChange={e=>setMessage(e.target.value)} className="mt-2 w-full border p-2" /></label>
|
||||
<button disabled={busy||!message.trim()} className="rounded bg-sky-700 px-4 py-2 text-white disabled:opacity-50">ارسال</button>
|
||||
</form><a href="/dashboard?tab=tickets" className="mt-2 block text-sm text-sky-700">ثبت تیکت پشتیبانی</a>
|
||||
</section>}
|
||||
</aside>;
|
||||
return localStorage.getItem('accessToken') || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
export default function SupportChat() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [scope, setScope] = useState<'public' | 'orders' | 'wallet'>('public');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
|
||||
const identity = useRef('');
|
||||
const pending = useRef<AbortController | null>(null);
|
||||
const chatScrollRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
identity.current = token();
|
||||
const check = () => {
|
||||
if (identity.current !== token()) {
|
||||
identity.current = token();
|
||||
pending.current?.abort();
|
||||
setRows([]);
|
||||
setMessage('');
|
||||
setScope('public');
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener('focus', check);
|
||||
window.addEventListener('storage', check);
|
||||
const interval = window.setInterval(check, 500);
|
||||
return () => {
|
||||
window.removeEventListener('focus', check);
|
||||
window.removeEventListener('storage', check);
|
||||
clearInterval(interval);
|
||||
pending.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (chatScrollRef.current) {
|
||||
chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [rows, busy]);
|
||||
|
||||
async function send(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
if (busy || !message.trim()) return;
|
||||
const current = token();
|
||||
if (current !== identity.current) {
|
||||
setRows([]);
|
||||
identity.current = current;
|
||||
}
|
||||
const question = message.trim();
|
||||
setMessage('');
|
||||
setBusy(true);
|
||||
const controller = new AbortController();
|
||||
pending.current = controller;
|
||||
let answer = unavailable;
|
||||
try {
|
||||
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/ask`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
...(current ? { Authorization: `Bearer ${current}` } : {})
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ message: question, scope }),
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)])
|
||||
});
|
||||
if (response.status === 401) {
|
||||
answer = 'لطفاً دوباره وارد حساب کاربری شوید.';
|
||||
} else if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (typeof data.answer === 'string') answer = data.answer;
|
||||
}
|
||||
} catch {
|
||||
// safe fallback kept
|
||||
}
|
||||
if (!controller.signal.aborted && token() === current) {
|
||||
setRows((r) => [...r.slice(-9), { question, answer }]);
|
||||
}
|
||||
if (pending.current === controller) setBusy(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<aside dir="rtl" className="fixed bottom-20 left-5 z-[9999] 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 ? 'بستن گفتگو با پشتیبان' : 'گفتگو با پشتیبان هوشمند'}
|
||||
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">
|
||||
{open ? (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M6 18L18 6M6 6l12 12" />
|
||||
) : (
|
||||
<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" />
|
||||
)}
|
||||
</svg>
|
||||
<span className="text-sm font-semibold tracking-wide">{open ? 'بستن گفتگو' : 'گفتگو با پشتیبان'}</span>
|
||||
</button>
|
||||
|
||||
{/* Chat Window */}
|
||||
{open && (
|
||||
<section
|
||||
aria-label="پشتیبان کنینا"
|
||||
className="absolute bottom-16 left-0 flex flex-col w-[360px] sm:w-[400px] h-[540px] max-h-[calc(100vh-7rem)] rounded-2xl border border-medical-gray-200 bg-white/95 backdrop-blur-md shadow-2xl overflow-hidden transition-all duration-300 animate-in fade-in slide-in-from-bottom-4"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="bg-gradient-to-r from-canina-blue to-medical-gray-800 text-white p-4 flex items-center justify-between border-b border-white/10">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative flex h-10 w-10 items-center justify-center rounded-xl bg-white/10 border border-white/20 text-canina-gold font-bold text-lg">
|
||||
C
|
||||
<span className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-canina-blue bg-emerald-500"></span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-bold flex items-center gap-1.5">
|
||||
پشتیبان هوشمند کنینا
|
||||
<span className="text-[10px] bg-canina-gold/20 text-canina-gold px-1.5 py-0.5 rounded border border-canina-gold/30">AI</span>
|
||||
</h3>
|
||||
<p className="text-[11px] text-white/70">راهنمای محصولات و سلامت پت</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
className="rounded-lg p-1 text-white/70 hover:bg-white/10 hover:text-white transition-colors"
|
||||
aria-label="بستن"
|
||||
>
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Scope Selector Bar */}
|
||||
<div className="bg-medical-gray-100 p-2 border-b border-medical-gray-200 flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setScope('public')}
|
||||
className={`flex-1 py-1.5 text-xs font-medium rounded-lg transition-all ${
|
||||
scope === 'public'
|
||||
? 'bg-white text-canina-blue shadow-sm font-bold border border-medical-gray-300'
|
||||
: 'text-medical-gray-600 hover:text-medical-gray-900 hover:bg-white/50'
|
||||
}`}
|
||||
>
|
||||
محصولات و عمومی
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setScope('orders')}
|
||||
className={`flex-1 py-1.5 text-xs font-medium rounded-lg transition-all ${
|
||||
scope === 'orders'
|
||||
? 'bg-white text-canina-blue shadow-sm font-bold border border-medical-gray-300'
|
||||
: 'text-medical-gray-600 hover:text-medical-gray-900 hover:bg-white/50'
|
||||
}`}
|
||||
>
|
||||
سفارشهای من
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setScope('wallet')}
|
||||
className={`flex-1 py-1.5 text-xs font-medium rounded-lg transition-all ${
|
||||
scope === 'wallet'
|
||||
? 'bg-white text-canina-blue shadow-sm font-bold border border-medical-gray-300'
|
||||
: 'text-medical-gray-600 hover:text-medical-gray-900 hover:bg-white/50'
|
||||
}`}
|
||||
>
|
||||
کیف پول
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Message Area */}
|
||||
<div
|
||||
ref={chatScrollRef}
|
||||
aria-live="polite"
|
||||
className="flex-1 overflow-y-auto p-4 space-y-3.5 bg-gradient-to-b from-medical-gray-50/50 to-white text-xs select-text"
|
||||
>
|
||||
<div className="rounded-xl bg-medical-gray-100 p-3 text-[11px] text-medical-gray-600 leading-relaxed border border-medical-gray-200 flex items-start gap-2">
|
||||
<svg className="h-4 w-4 text-canina-blue shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.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" />
|
||||
</svg>
|
||||
<span>پشتیبان هوشمند کنینا · هر پیام مستقل است. اطلاعات تغذیه و مکملها جایگزین تشخیص دامپزشک نیست.</span>
|
||||
</div>
|
||||
|
||||
{rows.length === 0 && (
|
||||
<div className="text-center py-8 text-medical-gray-400">
|
||||
<p className="text-xs">سوالی درباره مکملها، تغذیه یا سفارشها دارید؟</p>
|
||||
<p className="text-[11px] mt-1 text-medical-gray-500">به فارسی یا فینگلیش بپرسید تا راهنماییتان کنم.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{rows.map((r, i) => (
|
||||
<div key={i} className="space-y-2">
|
||||
{/* User Message */}
|
||||
<div className="flex justify-start">
|
||||
<div className="max-w-[85%] rounded-2xl rounded-tr-sm bg-canina-blue text-white px-3.5 py-2.5 shadow-sm text-xs leading-relaxed whitespace-pre-wrap">
|
||||
{r.question}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Assistant Message */}
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[90%] rounded-2xl rounded-tl-sm bg-medical-gray-100 text-medical-gray-900 border border-medical-gray-200 px-3.5 py-2.5 shadow-sm text-xs leading-relaxed whitespace-pre-wrap">
|
||||
{r.answer}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{busy && (
|
||||
<div className="flex justify-end">
|
||||
<div className="rounded-2xl rounded-tl-sm bg-medical-gray-100 border border-medical-gray-200 px-4 py-2.5 text-medical-gray-600 flex items-center gap-1.5 shadow-sm">
|
||||
<span className="text-[11px]">در حال بررسی و تنظیم پاسخ</span>
|
||||
<span className="flex gap-1 mr-1">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-canina-blue animate-bounce"></span>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-canina-blue animate-bounce [animation-delay:0.2s]"></span>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-canina-blue animate-bounce [animation-delay:0.4s]"></span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input & Footer */}
|
||||
<div className="p-3 bg-white border-t border-medical-gray-200">
|
||||
<form onSubmit={send} className="relative flex items-center">
|
||||
<textarea
|
||||
aria-label="پیام شما"
|
||||
value={message}
|
||||
maxLength={1500}
|
||||
rows={1}
|
||||
placeholder="پیام یا سوال خود را بنویسید…"
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (!busy && message.trim()) send(e);
|
||||
}
|
||||
}}
|
||||
className="w-full resize-none rounded-xl border border-medical-gray-300 bg-medical-gray-50/50 py-2.5 pr-3 pl-12 text-xs text-medical-gray-900 placeholder-medical-gray-400 focus:border-canina-blue focus:bg-white focus:outline-none transition-all"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy || !message.trim()}
|
||||
aria-label="ارسال"
|
||||
className="absolute left-1.5 flex h-8 w-8 items-center justify-center rounded-lg bg-canina-blue text-white shadow-sm transition-all hover:bg-opacity-90 disabled:opacity-30 disabled:hover:bg-canina-blue"
|
||||
>
|
||||
<svg className="h-4 w-4 rotate-180" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
|
||||
</svg>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-2 flex items-center justify-between px-1 text-[11px] text-medical-gray-500">
|
||||
<span>Shift+Enter خط جدید</span>
|
||||
<a
|
||||
href="/dashboard?tab=tickets"
|
||||
className="text-canina-blue font-medium hover:underline hover:text-medical-gray-800 transition-colors"
|
||||
>
|
||||
ثبت تیکت پشتیبانی ←
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user