feat(support): isolated stateless customer chat with JWT gatekeeper

This commit is contained in:
devops committed 2026-10-14 16:48:56 +00:00
1 parent 8bf1843b9b
commit 8242a1271f
21 files changed
+413

No files matched your search

@@ -0,0 +1,30 @@
// @vitest-environment jsdom
import React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
import SupportChat from './SupportChat';
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:'گفتگو با پشتیبان'}));
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'});
expect(document.querySelector('script')).toBeNull();
});
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:'گفتگو با پشتیبان'}));
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:'ارسال'}));
await waitFor(()=>expect(screen.getByText('private Alice')).toBeTruthy());
localStorage.setItem('accessToken','bob'); fireEvent.focus(window);
await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull());
});
});
@@ -0,0 +1,42 @@
'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;
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>;
}