// WaInboxView — Inbox WhatsApp do scoreodonto, consumindo o motor NewWhats via // proxy do backend (/api/nw/v1/* → motor /api/ext/v1/*). Estágio 1: lista de // conversas + thread + envio. Visual aproximado do motor (WhatsApp-like). import React, { useEffect, useRef, useState } from 'react'; import { PageHeader } from '../components/PageHeader.tsx'; const API = (import.meta as any).env?.VITE_API_URL || '/api'; async function nw(path: string, opts: RequestInit = {}) { const token = localStorage.getItem('SCOREODONTO_AUTH_TOKEN'); const res = await fetch(`${API}/nw/v1${path}`, { ...opts, headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(opts.headers || {}), }, }); if (!res.ok) throw new Error(`${res.status} ${await res.text().catch(() => '')}`.slice(0, 200)); return res.json(); } interface Chat { id: string | number; remote_jid?: string; displayName?: string; phone?: string; last_message_text?: string | null; unread_count?: number } interface Msg { id: string | number; text?: string; direction?: 'in' | 'out'; from_me?: number; timestamp?: number; type?: string } export const WaInboxView: React.FC = () => { const [sessions, setSessions] = useState([]); const [session, setSession] = useState(''); const [chats, setChats] = useState([]); const [active, setActive] = useState(null); const [msgs, setMsgs] = useState([]); const [text, setText] = useState(''); const [err, setErr] = useState(null); const [loading, setLoading] = useState(false); const endRef = useRef(null); useEffect(() => { nw('/sessions').then((s) => { const list = Array.isArray(s) ? s : []; setSessions(list); const conn = list.find((i: any) => String(i.status).toLowerCase() === 'connected') || list[0]; if (conn) setSession(conn.id || conn.instance); }).catch((e) => setErr(String(e.message))); }, []); useEffect(() => { if (!session) return; setLoading(true); nw(`/inbox?session=${encodeURIComponent(session)}&limit=50`) .then((c) => setChats(Array.isArray(c) ? c : (c.chats ?? []))) .catch((e) => setErr(String(e.message))) .finally(() => setLoading(false)); }, [session]); const openChat = async (c: Chat) => { setActive(c); setMsgs([]); try { const m = await nw(`/inbox/${encodeURIComponent(String(c.id))}/messages?limit=50`); setMsgs(Array.isArray(m) ? m : (m.messages ?? [])); setTimeout(() => endRef.current?.scrollIntoView(), 50); } catch (e: any) { setErr(String(e.message)); } }; const send = async () => { if (!active || !text.trim()) return; const body = text.trim(); setText(''); try { await nw(`/inbox/${encodeURIComponent(String(active.id))}/send`, { method: 'POST', body: JSON.stringify({ text: body }) }); setMsgs((p) => [...p, { id: `tmp-${Date.now()}`, text: body, from_me: 1, direction: 'out', timestamp: Date.now() }]); setTimeout(() => endRef.current?.scrollIntoView(), 50); } catch (e: any) { setErr(String(e.message)); } }; return (
{err &&
Erro: {err}. Verifique a configuração do plugin (super-admin) e o pareamento com o motor.
}
{/* Lista de conversas */}
{loading &&
Carregando…
} {chats.map((c) => (
openChat(c)} style={{ padding: '10px 12px', cursor: 'pointer', borderBottom: '1px solid #f3f4f6', background: active?.id === c.id ? '#f0fdf4' : 'transparent' }}>
{c.displayName || c.phone || c.remote_jid} {!!c.unread_count && {c.unread_count}}
{c.last_message_text || ''}
))} {!loading && !chats.length &&
Nenhuma conversa.
}
{/* Thread */}
{!active ? (
Selecione uma conversa
) : ( <>
{active.displayName || active.phone || active.remote_jid}
{msgs.map((m) => { const out = m.from_me === 1 || m.direction === 'out'; return (
{m.text || [{m.type || 'mídia'}]}
); })}
setText(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} placeholder="Mensagem" style={{ flex: 1, padding: '8px 12px', borderRadius: 20, border: '1px solid #d1d5db' }} />
)}
); };