FEAT: Adicionado funcionalidade de perfil de contato e notas do agente
- Adicionado Perfil de Contato para visualização e edição dos detalhes do contato. - Implementada serviço de perfil de contato para busca e salvamento de informações do contato. - Introduzido serviço de notas do agente para gerenciamento das notas (listar, criar, excluir). - Atualizado ChatConversationList para exibir rótulos de contatos salvos e indicadores de última mensagem. - Aprimorado ChatWindow para mostrar notas de transferência e melhorar o tratamento de mensagens. - Modificado hook useChat para gerenciar o status da última mensagem e notas de transferência. - Improved MessagesWorkspace to handle suggested replies and agent notes.
This commit is contained in:
parent
2e97ac6e5a
commit
b605a4c507
@ -23,12 +23,14 @@ function ChannelBadge({ channel }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ActivityDot({ status }) {
|
||||
const color = status === 'away' ? '#e5a22a' : '#dc2626';
|
||||
function LastMessageDot({ fromMe }) {
|
||||
const color = fromMe ? '#e5a22a' : '#00a4b7';
|
||||
const label = fromMe ? 'Última mensagem enviada pelo atendimento' : 'Última mensagem enviada pelo cliente';
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
title={label}
|
||||
aria-label={label}
|
||||
style={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
@ -65,12 +67,32 @@ function UnreadBadge({ count }) {
|
||||
);
|
||||
}
|
||||
|
||||
const CHAT_LIST_HEIGHT = 'min(640px, calc(100vh - 220px))';
|
||||
function SavedContactLabel({ contact }) {
|
||||
const profile = contact.contactProfile;
|
||||
const hasSavedContact = Boolean(profile?.created_at || profile?.name || profile?.company || profile?.note);
|
||||
if (!hasSavedContact) return null;
|
||||
|
||||
return (
|
||||
<span
|
||||
title="Contato salvo na agenda"
|
||||
style={{
|
||||
color: '#b7791f',
|
||||
flex: '0 0 auto',
|
||||
fontSize: '0.72rem',
|
||||
fontWeight: 800,
|
||||
lineHeight: 1,
|
||||
}}
|
||||
>
|
||||
•Salvo•
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatConversationList({
|
||||
contacts,
|
||||
activeContactId,
|
||||
onSelectContact,
|
||||
onOpenContact,
|
||||
isMobile = false,
|
||||
}) {
|
||||
return (
|
||||
@ -83,16 +105,16 @@ export function ChatConversationList({
|
||||
display: 'grid',
|
||||
gridTemplateRows: 'auto minmax(0, 1fr)',
|
||||
gap: '0.85rem',
|
||||
height: isMobile ? 'auto' : CHAT_LIST_HEIGHT,
|
||||
maxHeight: isMobile ? 'none' : CHAT_LIST_HEIGHT,
|
||||
alignSelf: 'start',
|
||||
height: isMobile ? 'auto' : '100%',
|
||||
maxHeight: isMobile ? 'none' : '100%',
|
||||
alignSelf: isMobile ? 'start' : 'stretch',
|
||||
minHeight: 0,
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong style={{ display: 'block', fontSize: '1.08rem' }}>Conversas ativas</strong>
|
||||
<span style={{ color: 'var(--color-text-soft)' }}>
|
||||
WhatsApp, SMS e email em uma fila visual.
|
||||
WhatsApp, SMS e e-mail em uma fila visual.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@ -116,6 +138,11 @@ export function ChatConversationList({
|
||||
key={contact.id}
|
||||
type="button"
|
||||
onClick={() => onSelectContact(contact.id)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
onSelectContact(contact.id);
|
||||
onOpenContact?.(contact);
|
||||
}}
|
||||
style={{
|
||||
border: '1px solid',
|
||||
borderColor: isActive ? 'rgba(0, 164, 183, 0.26)' : 'var(--color-border)',
|
||||
@ -129,7 +156,7 @@ export function ChatConversationList({
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '1rem' }}>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem', minWidth: 0 }}>
|
||||
<ActivityDot status={contact.status} />
|
||||
<LastMessageDot fromMe={contact.lastMessageFromMe} />
|
||||
<strong style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{contact.name}
|
||||
</strong>
|
||||
@ -139,7 +166,10 @@ export function ChatConversationList({
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem' }}>
|
||||
<ChannelBadge channel={contact.channel} />
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.45rem', minWidth: 0 }}>
|
||||
<ChannelBadge channel={contact.channel} />
|
||||
<SavedContactLabel contact={contact} />
|
||||
</span>
|
||||
<UnreadBadge count={contact.unread} />
|
||||
</div>
|
||||
<span style={{ color: 'var(--color-text-soft)' }}>{contact.preview}</span>
|
||||
|
||||
@ -254,6 +254,7 @@ export function ChatWindow({
|
||||
canAssumeChat = false,
|
||||
canReply = true,
|
||||
assignmentLabel,
|
||||
transferNote,
|
||||
isReplying,
|
||||
isMobile = false,
|
||||
}) {
|
||||
@ -334,7 +335,7 @@ export function ChatWindow({
|
||||
{canAssumeChat ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAssumeChat}
|
||||
onClick={() => onAssumeChat?.()}
|
||||
style={{
|
||||
border: 'none',
|
||||
borderRadius: '14px',
|
||||
@ -380,6 +381,24 @@ export function ChatWindow({
|
||||
Transferir
|
||||
</button>
|
||||
</div>
|
||||
{transferNote ? (
|
||||
<div
|
||||
style={{
|
||||
gridColumn: '1 / -1',
|
||||
border: '1px solid rgba(0, 164, 183, 0.24)',
|
||||
borderRadius: 16,
|
||||
padding: '0.85rem 1rem',
|
||||
background: 'rgba(0, 164, 183, 0.07)',
|
||||
color: 'var(--color-text)',
|
||||
lineHeight: 1.45,
|
||||
}}
|
||||
>
|
||||
<strong style={{ display: 'block', color: 'var(--color-primary)', marginBottom: '0.25rem' }}>
|
||||
Observacao da transferencia
|
||||
</strong>
|
||||
{transferNote}
|
||||
</div>
|
||||
) : null}
|
||||
</header>
|
||||
|
||||
<div
|
||||
@ -535,9 +554,16 @@ export function ChatWindow({
|
||||
fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
{canAssumeChat
|
||||
? 'Este atendimento esta na fila. Assuma para responder, ou envie uma mensagem para assumir automaticamente.'
|
||||
: assignmentLabel || 'Este atendimento esta atribuido a outro usuario.'}
|
||||
<span style={{ display: 'block' }}>
|
||||
{canAssumeChat
|
||||
? 'Este atendimento esta na fila. Assuma para responder ou transferir.'
|
||||
: assignmentLabel || 'Este atendimento esta atribuido a outro usuario.'}
|
||||
</span>
|
||||
{transferNote ? (
|
||||
<span style={{ display: 'block', marginTop: '0.45rem', color: 'var(--color-text)' }}>
|
||||
Obs: {transferNote}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
@ -583,13 +609,15 @@ export function ChatWindow({
|
||||
onSend();
|
||||
}
|
||||
}}
|
||||
disabled={!safeContact.id || (!canReply && !canAssumeChat)}
|
||||
disabled={!safeContact.id || !canReply}
|
||||
placeholder={
|
||||
!safeContact.id
|
||||
? 'Aguardando conversa entrar em uma fila'
|
||||
: canReply || canAssumeChat
|
||||
: canReply
|
||||
? 'Escreva sua mensagem...'
|
||||
: 'Atendimento bloqueado para resposta'
|
||||
: canAssumeChat
|
||||
? 'Assuma o atendimento para responder'
|
||||
: 'Atendimento bloqueado para resposta'
|
||||
}
|
||||
style={{
|
||||
border: '1px solid var(--color-border)',
|
||||
@ -598,13 +626,13 @@ export function ChatWindow({
|
||||
background: '#fff',
|
||||
outline: 'none',
|
||||
minWidth: 0,
|
||||
opacity: safeContact.id && (canReply || canAssumeChat) ? 1 : 0.6,
|
||||
opacity: safeContact.id && canReply ? 1 : 0.6,
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSend}
|
||||
disabled={!safeContact.id || (!canReply && !canAssumeChat)}
|
||||
disabled={!safeContact.id || !canReply}
|
||||
style={{
|
||||
border: 'none',
|
||||
borderRadius: '18px',
|
||||
@ -613,7 +641,7 @@ export function ChatWindow({
|
||||
color: '#fff',
|
||||
fontWeight: 700,
|
||||
gridColumn: isMobile ? '1 / -1' : 'auto',
|
||||
opacity: safeContact.id && (canReply || canAssumeChat) ? 1 : 0.6,
|
||||
opacity: safeContact.id && canReply ? 1 : 0.6,
|
||||
}}
|
||||
>
|
||||
Enviar
|
||||
|
||||
197
src/modules/chat/components/ContactProfilePanel.jsx
Normal file
197
src/modules/chat/components/ContactProfilePanel.jsx
Normal file
@ -0,0 +1,197 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { getCurrentUser } from '../../auth/services/sessionService';
|
||||
import { getContactProfile, saveContactProfile } from '../services/contactProfileService';
|
||||
|
||||
function getUserId(user) {
|
||||
const value = user?.databaseId || user?.id;
|
||||
const numeric = Number(value);
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
function formatPhone(phone) {
|
||||
const digits = String(phone || '').replace(/\D/g, '');
|
||||
if (!digits) return 'Telefone nao disponivel';
|
||||
|
||||
if (digits.startsWith('55') && digits.length === 13) {
|
||||
return `+55 (${digits.slice(2, 4)}) ${digits.slice(4, 9)}-${digits.slice(9)}`;
|
||||
}
|
||||
|
||||
if (digits.startsWith('55') && digits.length === 12) {
|
||||
return `+55 (${digits.slice(2, 4)}) ${digits.slice(4, 8)}-${digits.slice(8)}`;
|
||||
}
|
||||
|
||||
if (digits.length === 11) {
|
||||
return `(${digits.slice(0, 2)}) ${digits.slice(2, 7)}-${digits.slice(7)}`;
|
||||
}
|
||||
|
||||
if (digits.length === 10) {
|
||||
return `(${digits.slice(0, 2)}) ${digits.slice(2, 6)}-${digits.slice(6)}`;
|
||||
}
|
||||
|
||||
return phone;
|
||||
}
|
||||
|
||||
export function ContactProfilePanel({ isOpen, contact, onClose, onSaved }) {
|
||||
const [profile, setProfile] = useState(null);
|
||||
const [form, setForm] = useState({ name: '', company: '', note: '' });
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
async function loadProfile() {
|
||||
if (!isOpen || !contact?.id) return;
|
||||
try {
|
||||
const data = await getContactProfile(contact.id);
|
||||
if (!isMounted) return;
|
||||
setProfile(data);
|
||||
setForm({
|
||||
name: data.name || contact.name || '',
|
||||
company: data.company || '',
|
||||
note: data.note || '',
|
||||
});
|
||||
setError('');
|
||||
} catch (err) {
|
||||
if (isMounted) setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
loadProfile();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [isOpen, contact?.id]);
|
||||
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fieldStyle = {
|
||||
width: '100%',
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: '16px',
|
||||
padding: '0.9rem 1rem',
|
||||
background: '#fff',
|
||||
outline: 'none',
|
||||
};
|
||||
|
||||
async function submit() {
|
||||
if (!contact?.id) return;
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const userId = getUserId(getCurrentUser());
|
||||
const saved = await saveContactProfile(contact.id, {
|
||||
phone: profile?.phone || contact?.contactProfile?.phone || '',
|
||||
name: form.name,
|
||||
company: form.company,
|
||||
note: form.note,
|
||||
userId,
|
||||
});
|
||||
setProfile(saved);
|
||||
onSaved?.(contact.id, saved);
|
||||
setError('');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
style={{
|
||||
background: '#fff',
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: '28px',
|
||||
padding: '1.25rem',
|
||||
display: 'grid',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '1rem' }}>
|
||||
<div>
|
||||
<strong style={{ display: 'block', fontSize: '1.06rem' }}>Contato do cliente</strong>
|
||||
<span style={{ color: 'var(--color-text-soft)' }}>
|
||||
Atualize os dados de agenda deste atendimento.
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
style={{
|
||||
border: 'none',
|
||||
background: 'transparent',
|
||||
color: 'var(--color-text-soft)',
|
||||
fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
Fechar
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label style={{ display: 'grid', gap: '0.45rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Nome</span>
|
||||
<input
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
|
||||
style={fieldStyle}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label style={{ display: 'grid', gap: '0.45rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Empresa</span>
|
||||
<input
|
||||
value={form.company}
|
||||
onChange={(event) => setForm((current) => ({ ...current, company: event.target.value }))}
|
||||
placeholder="Empresa ou conta vinculada"
|
||||
style={fieldStyle}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label style={{ display: 'grid', gap: '0.45rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Telefone</span>
|
||||
<input
|
||||
value={formatPhone(profile?.phone || contact?.contactProfile?.phone)}
|
||||
disabled
|
||||
style={{
|
||||
...fieldStyle,
|
||||
background: 'rgba(0, 49, 80, 0.04)',
|
||||
color: 'var(--color-text-soft)',
|
||||
fontWeight: 700,
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label style={{ display: 'grid', gap: '0.45rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Observacao</span>
|
||||
<textarea
|
||||
rows={5}
|
||||
value={form.note}
|
||||
onChange={(event) => setForm((current) => ({ ...current, note: event.target.value }))}
|
||||
placeholder="Informacoes relevantes do cliente."
|
||||
style={{ ...fieldStyle, resize: 'vertical' }}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{error ? <span style={{ color: '#b42318', fontWeight: 700 }}>{error}</span> : null}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={submit}
|
||||
disabled={isSaving}
|
||||
style={{
|
||||
border: 'none',
|
||||
borderRadius: '16px',
|
||||
padding: '0.95rem 1rem',
|
||||
background: 'linear-gradient(135deg, var(--color-primary), #0b5a86)',
|
||||
color: '#fff',
|
||||
fontWeight: 700,
|
||||
opacity: isSaving ? 0.65 : 1,
|
||||
}}
|
||||
>
|
||||
{isSaving ? 'Salvando...' : 'Salvar contato'}
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@ -12,6 +12,12 @@ function buildInitialMessages() {
|
||||
}, {});
|
||||
}
|
||||
|
||||
function getLastMessageFromMe(messages = []) {
|
||||
const lastMessage = [...messages].reverse().find(isDisplayableMessage);
|
||||
if (!lastMessage) return false;
|
||||
return lastMessage.sender === 'agent' || lastMessage.fromMe === true;
|
||||
}
|
||||
|
||||
function getSerializedId(value) {
|
||||
if (!value) return '';
|
||||
if (typeof value === 'string') return value;
|
||||
@ -40,6 +46,7 @@ function normalizeChat(chat) {
|
||||
const id = getSerializedId(chat.id);
|
||||
const assignment = chat.assignment || null;
|
||||
const lastSeenTimestamp = chat.timestamp || null;
|
||||
const hasLastMessageFromMe = typeof chat.lastMessageFromMe === 'boolean';
|
||||
|
||||
return {
|
||||
id,
|
||||
@ -48,10 +55,12 @@ function normalizeChat(chat) {
|
||||
status: lastSeenTimestamp ? 'away' : 'offline',
|
||||
area: assignment?.area_nome || (assignment?.area_id ? String(assignment.area_id) : 'Sem fila'),
|
||||
areaId: assignment?.area_id || null,
|
||||
lastSeen: lastSeenTimestamp ? `Ultima atividade as ${formatTime(lastSeenTimestamp)}` : 'Sem atividade recente',
|
||||
lastSeen: lastSeenTimestamp ? `Última atividade as ${formatTime(lastSeenTimestamp)}` : 'Sem atividade recente',
|
||||
preview: chat.preview || chat.lastMessage?.body || '',
|
||||
time: formatTime(chat.timestamp) || 'Agora',
|
||||
unread: chat.unreadCount || 0,
|
||||
lastMessageFromMe: hasLastMessageFromMe ? chat.lastMessageFromMe : Boolean(chat.lastMessage?.fromMe),
|
||||
contactProfile: chat.contactProfile || null,
|
||||
assignment,
|
||||
};
|
||||
}
|
||||
@ -137,7 +146,12 @@ function fileToBase64(file) {
|
||||
}
|
||||
|
||||
function buildFallbackContacts() {
|
||||
return chatContacts.map((contact) => ({ ...contact, assignment: null, areaId: null }));
|
||||
return chatContacts.map((contact) => ({
|
||||
...contact,
|
||||
assignment: null,
|
||||
areaId: null,
|
||||
lastMessageFromMe: getLastMessageFromMe(contact.messages),
|
||||
}));
|
||||
}
|
||||
|
||||
function getUserId(user) {
|
||||
@ -147,9 +161,15 @@ function getUserId(user) {
|
||||
}
|
||||
|
||||
function getUserAreas(user) {
|
||||
const areas = Array.isArray(user?.areas) ? user.areas : [];
|
||||
if (user?.areaPrincipal && !areas.includes(user.areaPrincipal)) {
|
||||
return [user.areaPrincipal, ...areas];
|
||||
const normalizeArea = (area) => {
|
||||
if (!area) return null;
|
||||
if (typeof area === 'string') return area;
|
||||
return area.nome || area.name || null;
|
||||
};
|
||||
const areas = (Array.isArray(user?.areas) ? user.areas : []).map(normalizeArea).filter(Boolean);
|
||||
const primaryArea = normalizeArea(user?.areaPrincipal);
|
||||
if (primaryArea && !areas.includes(primaryArea)) {
|
||||
return [primaryArea, ...areas];
|
||||
}
|
||||
return areas;
|
||||
}
|
||||
@ -172,7 +192,7 @@ export function useChat() {
|
||||
const [accessUsers, setAccessUsers] = useState([]);
|
||||
const [selectedArea, setSelectedArea] = useState(chatContacts[0].area);
|
||||
const [isTransferOpen, setIsTransferOpen] = useState(false);
|
||||
const [transferArea, setTransferArea] = useState(currentUser?.areaPrincipal || 'Suporte');
|
||||
const [transferArea, setTransferArea] = useState(currentUserAreas[0] || 'Suporte');
|
||||
const [transferAttendant, setTransferAttendant] = useState('');
|
||||
const [transferNote, setTransferNote] = useState('');
|
||||
const [isReplying] = useState(false);
|
||||
@ -182,8 +202,15 @@ export function useChat() {
|
||||
const activeContactRef = useRef(activeContactId);
|
||||
|
||||
const activeContact = useMemo(
|
||||
() => contacts.find((contact) => contact.id === activeContactId) || contacts[0],
|
||||
[contacts, activeContactId],
|
||||
() => {
|
||||
const contact = contacts.find((item) => item.id === activeContactId) || contacts[0];
|
||||
if (!contact || typeof contact.lastMessageFromMe === 'boolean') return contact;
|
||||
return {
|
||||
...contact,
|
||||
lastMessageFromMe: getLastMessageFromMe(messagesByContact[contact.id] || []),
|
||||
};
|
||||
},
|
||||
[contacts, activeContactId, messagesByContact],
|
||||
);
|
||||
|
||||
const messages = messagesByContact[activeContactId] || [];
|
||||
@ -209,6 +236,7 @@ export function useChat() {
|
||||
: activeAssignment?.area_nome
|
||||
? `Na fila de ${activeAssignment.area_nome}`
|
||||
: 'Sem fila definida';
|
||||
const transferNoteLabel = activeAssignment?.transfer_note || '';
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedArea(activeContact?.area || 'Sem fila');
|
||||
@ -313,16 +341,21 @@ export function useChat() {
|
||||
if (!response.ok) throw new Error('Falha ao carregar mensagens do WhatsApp.');
|
||||
const data = await response.json();
|
||||
if (!isMounted || !Array.isArray(data)) return;
|
||||
const normalizedMessages = dedupeMessages(
|
||||
data
|
||||
.map((message) => ({
|
||||
...normalizeMessage(message),
|
||||
chatId: activeContactId,
|
||||
}))
|
||||
.filter(isDisplayableMessage),
|
||||
);
|
||||
setMessagesByContact((current) => ({
|
||||
...current,
|
||||
[activeContactId]: dedupeMessages(
|
||||
data
|
||||
.map((message) => ({
|
||||
...normalizeMessage(message),
|
||||
chatId: activeContactId,
|
||||
}))
|
||||
.filter(isDisplayableMessage),
|
||||
),
|
||||
[activeContactId]: normalizedMessages,
|
||||
}));
|
||||
updateContact(activeContactId, (contact) => ({
|
||||
...contact,
|
||||
lastMessageFromMe: getLastMessageFromMe(normalizedMessages),
|
||||
}));
|
||||
setApiError(null);
|
||||
} catch (error) {
|
||||
@ -382,7 +415,8 @@ export function useChat() {
|
||||
preview,
|
||||
time: 'Agora',
|
||||
status: 'away',
|
||||
lastSeen: 'Ultima atividade agora',
|
||||
lastSeen: 'Última atividade agora',
|
||||
lastMessageFromMe: Boolean(incomingMessage.fromMe),
|
||||
unread:
|
||||
incomingMessage.fromMe || contactId === activeContactRef.current
|
||||
? 0
|
||||
@ -407,6 +441,15 @@ export function useChat() {
|
||||
preview: media ? `[Midia: ${media.filename || 'Arquivo'}]` : preview,
|
||||
time: 'Agora',
|
||||
unread: 0,
|
||||
lastMessageFromMe: true,
|
||||
}));
|
||||
}
|
||||
|
||||
function updateContactProfile(contactId, profile) {
|
||||
updateContact(contactId, (contact) => ({
|
||||
...contact,
|
||||
name: profile.name || contact.name,
|
||||
contactProfile: profile,
|
||||
}));
|
||||
}
|
||||
|
||||
@ -458,28 +501,36 @@ export function useChat() {
|
||||
}
|
||||
}
|
||||
|
||||
async function assumeChat() {
|
||||
if (!activeContactId?.includes('@') || !currentUserId) return null;
|
||||
const areaId = activeContact?.areaId || activeAssignment?.area_id || areaOptions.find((area) => currentUserAreas.includes(area.nome))?.id;
|
||||
const response = await fetch(`${API_BASE_URL}/whatsapp/assign`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
chatId: activeContactId,
|
||||
userId: String(currentUserId),
|
||||
areaId,
|
||||
}),
|
||||
});
|
||||
async function assumeChat(contactId = activeContactId) {
|
||||
if (!contactId?.includes('@') || !currentUserId) return null;
|
||||
const targetContact = contacts.find((contact) => contact.id === contactId) || activeContact;
|
||||
const targetAssignment = targetContact?.assignment || null;
|
||||
const areaId = targetContact?.areaId || targetAssignment?.area_id || areaOptions.find((area) => currentUserAreas.includes(area.nome))?.id;
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/whatsapp/assign`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
chatId: contactId,
|
||||
userId: String(currentUserId),
|
||||
areaId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Nao foi possivel assumir o atendimento.');
|
||||
const assignment = await response.json();
|
||||
updateContact(activeContactId, (contact) => ({
|
||||
...contact,
|
||||
assignment,
|
||||
area: assignment.area_nome || contact.area,
|
||||
areaId: assignment.area_id || contact.areaId,
|
||||
}));
|
||||
return assignment;
|
||||
if (!response.ok) throw new Error('Nao foi possivel assumir o atendimento.');
|
||||
const assignment = await response.json();
|
||||
updateContact(contactId, (contact) => ({
|
||||
...contact,
|
||||
assignment,
|
||||
area: assignment.area_nome || contact.area,
|
||||
areaId: assignment.area_id || contact.areaId,
|
||||
}));
|
||||
setApiError(null);
|
||||
return assignment;
|
||||
} catch (error) {
|
||||
setApiError(error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseChat() {
|
||||
@ -498,18 +549,19 @@ export function useChat() {
|
||||
}));
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const trimmed = draft.trim();
|
||||
async function sendMessage(messageText = draft, contactId = activeContactId) {
|
||||
const trimmed = String(messageText || '').trim();
|
||||
if (!trimmed && !attachedFile) return;
|
||||
|
||||
const targetContact = contacts.find((contact) => contact.id === contactId) || activeContact;
|
||||
const targetAssignment = targetContact?.assignment || null;
|
||||
const targetIsAssignedToCurrentUser = Boolean(
|
||||
targetAssignment?.user_id && currentUserId && Number(targetAssignment.user_id) === currentUserId,
|
||||
);
|
||||
try {
|
||||
if (!canReply) {
|
||||
if (canAssumeChat) {
|
||||
await assumeChat();
|
||||
} else {
|
||||
setApiError('Este atendimento esta atribuido a outro usuario.');
|
||||
return;
|
||||
}
|
||||
if (!targetIsAssignedToCurrentUser) {
|
||||
setApiError('Assuma o atendimento antes de responder.');
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
setApiError(error.message);
|
||||
@ -525,7 +577,7 @@ export function useChat() {
|
||||
: null;
|
||||
const newMessage = {
|
||||
id: `temp-${Date.now()}`,
|
||||
chatId: activeContactId,
|
||||
chatId: contactId,
|
||||
sender: 'agent',
|
||||
text: trimmed,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
@ -535,26 +587,34 @@ export function useChat() {
|
||||
|
||||
setMessagesByContact((current) => ({
|
||||
...current,
|
||||
[activeContactId]: mergeMessageList(current[activeContactId] || [], newMessage),
|
||||
[contactId]: mergeMessageList(current[contactId] || [], newMessage),
|
||||
}));
|
||||
updateContactPreview(activeContactId, trimmed || '[Midia]', media);
|
||||
setDraft('');
|
||||
updateContactPreview(contactId, trimmed || '[Midia]', media);
|
||||
if (contactId === activeContactId) {
|
||||
setDraft('');
|
||||
}
|
||||
setAttachedFile(null);
|
||||
|
||||
if (!activeContactId.includes('@')) return;
|
||||
if (!contactId.includes('@')) return;
|
||||
|
||||
try {
|
||||
await fetch(`${API_BASE_URL}/whatsapp/send`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
to: activeContactId,
|
||||
to: contactId,
|
||||
message: trimmed,
|
||||
senderName: getUserDisplayName(currentUser),
|
||||
media,
|
||||
}),
|
||||
});
|
||||
setApiError(null);
|
||||
updateContact(contactId, (contact) => ({
|
||||
...contact,
|
||||
assignment: contact.assignment
|
||||
? { ...contact.assignment, transfer_note: null }
|
||||
: contact.assignment,
|
||||
}));
|
||||
} catch (error) {
|
||||
setApiError(error.message);
|
||||
}
|
||||
@ -569,6 +629,11 @@ export function useChat() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAssignedToCurrentUser) {
|
||||
setApiError('Assuma o atendimento antes de transferir.');
|
||||
return;
|
||||
}
|
||||
|
||||
const targetUserId = isSameUserArea && transferAttendant ? Number(transferAttendant) : null;
|
||||
const response = await fetch(`${API_BASE_URL}/whatsapp/transfer`, {
|
||||
method: 'POST',
|
||||
@ -629,8 +694,10 @@ export function useChat() {
|
||||
canAssumeChat,
|
||||
canReply,
|
||||
assignmentLabel,
|
||||
transferNoteLabel,
|
||||
isAssignedToCurrentUser,
|
||||
activeAssignment,
|
||||
updateContactProfile,
|
||||
isReplying,
|
||||
isLoadingChats,
|
||||
isLoadingMessages,
|
||||
|
||||
@ -1,13 +1,16 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { BrandMark } from '../../../shared/components/BrandMark';
|
||||
import { useViewport } from '../../../shared/hooks/useViewport';
|
||||
import { ChatConversationList } from '../components/ChatConversationList';
|
||||
import { ChatTransferPanel } from '../components/ChatTransferPanel';
|
||||
import { ContactProfilePanel } from '../components/ContactProfilePanel';
|
||||
import { ChatWindow } from '../components/ChatWindow';
|
||||
import { useChat } from '../hooks/useChat';
|
||||
import { quickReplies } from '../services/chatMocks';
|
||||
|
||||
export function ChatPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const { isWideDesktop, isDesktop, isTablet, isMobile } = useViewport();
|
||||
const {
|
||||
contacts,
|
||||
@ -27,6 +30,8 @@ export function ChatPage() {
|
||||
canAssumeChat,
|
||||
canReply,
|
||||
assignmentLabel,
|
||||
transferNoteLabel,
|
||||
updateContactProfile,
|
||||
isReplying,
|
||||
selectedArea,
|
||||
setSelectedArea,
|
||||
@ -43,6 +48,14 @@ export function ChatPage() {
|
||||
setTransferNote,
|
||||
submitTransfer,
|
||||
} = useChat();
|
||||
const requestedChatId = searchParams.get('chatId');
|
||||
const [isContactPanelOpen, setIsContactPanelOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestedChatId) return;
|
||||
if (!contacts.some((contact) => contact.id === requestedChatId)) return;
|
||||
setActiveContactId(requestedChatId);
|
||||
}, [requestedChatId, contacts, setActiveContactId]);
|
||||
|
||||
const gridTemplateColumns = isMobile
|
||||
? '1fr'
|
||||
@ -116,6 +129,10 @@ export function ChatPage() {
|
||||
contacts={contacts}
|
||||
activeContactId={activeContactId}
|
||||
onSelectContact={setActiveContactId}
|
||||
onOpenContact={() => {
|
||||
setIsTransferOpen(false);
|
||||
setIsContactPanelOpen(true);
|
||||
}}
|
||||
isMobile={isMobile}
|
||||
/>
|
||||
|
||||
@ -132,12 +149,16 @@ export function ChatPage() {
|
||||
onRemoveAttachedFile={removeAttachedFile}
|
||||
onLoadMedia={hydrateMessageMedia}
|
||||
onSend={sendMessage}
|
||||
onToggleTransfer={() => setIsTransferOpen((current) => !current)}
|
||||
onToggleTransfer={() => {
|
||||
setIsContactPanelOpen(false);
|
||||
setIsTransferOpen((current) => !current);
|
||||
}}
|
||||
onAssumeChat={assumeChat}
|
||||
onReleaseChat={releaseChat}
|
||||
canAssumeChat={canAssumeChat}
|
||||
canReply={canReply}
|
||||
assignmentLabel={assignmentLabel}
|
||||
transferNote={transferNoteLabel}
|
||||
isReplying={isReplying}
|
||||
isMobile={isMobile}
|
||||
/>
|
||||
@ -171,6 +192,33 @@ export function ChatPage() {
|
||||
</div>
|
||||
|
||||
{isWideDesktop ? (
|
||||
<>
|
||||
<ChatTransferPanel
|
||||
isOpen={isTransferOpen}
|
||||
transferArea={transferArea}
|
||||
setTransferArea={setTransferArea}
|
||||
transferAreas={transferAreas}
|
||||
attendants={attendants}
|
||||
isSameUserArea={isSameUserArea}
|
||||
transferAttendant={transferAttendant}
|
||||
setTransferAttendant={setTransferAttendant}
|
||||
transferNote={transferNote}
|
||||
setTransferNote={setTransferNote}
|
||||
onSubmit={submitTransfer}
|
||||
onClose={() => setIsTransferOpen(false)}
|
||||
/>
|
||||
<ContactProfilePanel
|
||||
isOpen={isContactPanelOpen}
|
||||
contact={activeContact}
|
||||
onClose={() => setIsContactPanelOpen(false)}
|
||||
onSaved={updateContactProfile}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{!isWideDesktop ? (
|
||||
<>
|
||||
<ChatTransferPanel
|
||||
isOpen={isTransferOpen}
|
||||
transferArea={transferArea}
|
||||
@ -185,24 +233,13 @@ export function ChatPage() {
|
||||
onSubmit={submitTransfer}
|
||||
onClose={() => setIsTransferOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{!isWideDesktop ? (
|
||||
<ChatTransferPanel
|
||||
isOpen={isTransferOpen}
|
||||
transferArea={transferArea}
|
||||
setTransferArea={setTransferArea}
|
||||
transferAreas={transferAreas}
|
||||
attendants={attendants}
|
||||
isSameUserArea={isSameUserArea}
|
||||
transferAttendant={transferAttendant}
|
||||
setTransferAttendant={setTransferAttendant}
|
||||
transferNote={transferNote}
|
||||
setTransferNote={setTransferNote}
|
||||
onSubmit={submitTransfer}
|
||||
onClose={() => setIsTransferOpen(false)}
|
||||
/>
|
||||
<ContactProfilePanel
|
||||
isOpen={isContactPanelOpen}
|
||||
contact={activeContact}
|
||||
onClose={() => setIsContactPanelOpen(false)}
|
||||
onSaved={updateContactProfile}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
</main>
|
||||
|
||||
17
src/modules/chat/services/contactProfileService.js
Normal file
17
src/modules/chat/services/contactProfileService.js
Normal file
@ -0,0 +1,17 @@
|
||||
import { API_BASE_URL } from '../../../shared/services/apiConfig';
|
||||
|
||||
export async function getContactProfile(chatId) {
|
||||
const response = await fetch(`${API_BASE_URL}/contacts/${encodeURIComponent(chatId)}`);
|
||||
if (!response.ok) throw new Error('Falha ao carregar contato.');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function saveContactProfile(chatId, payload) {
|
||||
const response = await fetch(`${API_BASE_URL}/contacts/${encodeURIComponent(chatId)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) throw new Error('Falha ao salvar contato.');
|
||||
return response.json();
|
||||
}
|
||||
@ -1,5 +1,7 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { createAgentNote, deleteAgentNote, listAgentNotes } from '../services/agentNotesService';
|
||||
import { getCurrentUser } from '../../auth/services/sessionService';
|
||||
|
||||
const WORKSPACE_HEIGHT = 660;
|
||||
|
||||
@ -100,16 +102,46 @@ function buildSuggestedReplies(conversation) {
|
||||
];
|
||||
}
|
||||
|
||||
function parseMessageText(text) {
|
||||
const rawText = String(text || '');
|
||||
const match = rawText.match(/^\*(Atendente(?: virtual)?:\s*[^*]+)\*\s*\n+/i);
|
||||
|
||||
if (!match) {
|
||||
return { senderLabel: null, body: rawText };
|
||||
}
|
||||
|
||||
return {
|
||||
senderLabel: match[1],
|
||||
body: rawText.slice(match[0].length),
|
||||
};
|
||||
}
|
||||
|
||||
function formatMessageTime(timestamp) {
|
||||
if (!timestamp) return '';
|
||||
const numericTimestamp = Number(timestamp);
|
||||
const date = new Date(numericTimestamp > 1000000000000 ? numericTimestamp : numericTimestamp * 1000);
|
||||
return date.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function getUserId(user) {
|
||||
const value = user?.databaseId || user?.id;
|
||||
const numeric = Number(value);
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
export function MessagesWorkspace({
|
||||
conversations,
|
||||
activeConversationId,
|
||||
onSelectConversation,
|
||||
onSendSuggestedReply,
|
||||
isWideDesktop = false,
|
||||
isDesktop = false,
|
||||
isTablet = false,
|
||||
isMobile = false,
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const currentUser = getCurrentUser();
|
||||
const currentUserId = getUserId(currentUser);
|
||||
const recentConversations = conversations.slice(0, 3);
|
||||
const activeConversation =
|
||||
recentConversations.find((conversation) => conversation.id === activeConversationId) ||
|
||||
@ -127,13 +159,8 @@ export function MessagesWorkspace({
|
||||
);
|
||||
const [selectedReplyIndex, setSelectedReplyIndex] = useState(0);
|
||||
const [noteDraft, setNoteDraft] = useState('');
|
||||
const [notes, setNotes] = useState(() => {
|
||||
try {
|
||||
return JSON.parse(window.localStorage.getItem('agentNotes') || '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
const [notes, setNotes] = useState([]);
|
||||
const [notesError, setNotesError] = useState('');
|
||||
|
||||
const selectedReply = suggestedReplies[selectedReplyIndex] || suggestedReplies[0];
|
||||
const managerMessages = [
|
||||
@ -154,8 +181,25 @@ export function MessagesWorkspace({
|
||||
}, [safeActiveConversation.id]);
|
||||
|
||||
useEffect(() => {
|
||||
window.localStorage.setItem('agentNotes', JSON.stringify(notes));
|
||||
}, [notes]);
|
||||
let isMounted = true;
|
||||
|
||||
async function loadNotes() {
|
||||
try {
|
||||
const data = await listAgentNotes(currentUserId);
|
||||
if (isMounted) {
|
||||
setNotes(Array.isArray(data) ? data : []);
|
||||
setNotesError('');
|
||||
}
|
||||
} catch (error) {
|
||||
if (isMounted) setNotesError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
loadNotes();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [currentUserId]);
|
||||
|
||||
function selectPreviousReply() {
|
||||
setSelectedReplyIndex((current) =>
|
||||
@ -167,19 +211,37 @@ export function MessagesWorkspace({
|
||||
setSelectedReplyIndex((current) => (current + 1) % suggestedReplies.length);
|
||||
}
|
||||
|
||||
function saveNote() {
|
||||
async function saveNote() {
|
||||
const text = noteDraft.trim();
|
||||
if (!text) return;
|
||||
if (!text || !currentUserId) return;
|
||||
|
||||
setNotes((current) => [
|
||||
{
|
||||
id: Date.now(),
|
||||
text,
|
||||
time: new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }),
|
||||
},
|
||||
...current,
|
||||
]);
|
||||
setNoteDraft('');
|
||||
try {
|
||||
const note = await createAgentNote(currentUserId, text);
|
||||
setNotes((current) => [note, ...current]);
|
||||
setNoteDraft('');
|
||||
setNotesError('');
|
||||
} catch (error) {
|
||||
setNotesError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeNote(noteId) {
|
||||
if (!currentUserId) return;
|
||||
|
||||
try {
|
||||
await deleteAgentNote(currentUserId, noteId);
|
||||
setNotes((current) => current.filter((note) => note.id !== noteId));
|
||||
setNotesError('');
|
||||
} catch (error) {
|
||||
setNotesError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendSuggestedReply() {
|
||||
if (!safeActiveConversation.id || safeActiveConversation.id === 'empty') return;
|
||||
|
||||
await onSendSuggestedReply?.(safeActiveConversation.id, selectedReply);
|
||||
navigate(`/chat?chatId=${encodeURIComponent(safeActiveConversation.id)}`);
|
||||
}
|
||||
|
||||
const gridTemplateColumns = isMobile
|
||||
@ -348,6 +410,8 @@ export function MessagesWorkspace({
|
||||
>
|
||||
{safeActiveConversation.messages.map((message) => {
|
||||
const isAgent = message.from === 'agent';
|
||||
const parsedText = parseMessageText(message.text);
|
||||
const messageTime = formatMessageTime(message.timestamp);
|
||||
|
||||
return (
|
||||
<div
|
||||
@ -360,9 +424,45 @@ export function MessagesWorkspace({
|
||||
background: isAgent ? 'var(--color-primary)' : '#edf1f5',
|
||||
color: isAgent ? '#fff' : 'var(--color-text)',
|
||||
boxShadow: 'var(--shadow-md)',
|
||||
display: 'grid',
|
||||
gap: '0.55rem',
|
||||
}}
|
||||
>
|
||||
{message.text}
|
||||
{parsedText.senderLabel ? (
|
||||
<strong
|
||||
style={{
|
||||
display: 'block',
|
||||
fontSize: '0.76rem',
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: '0.02em',
|
||||
textTransform: 'uppercase',
|
||||
color: isAgent ? 'rgba(255,255,255,0.78)' : 'var(--color-primary)',
|
||||
}}
|
||||
>
|
||||
{parsedText.senderLabel}
|
||||
</strong>
|
||||
) : null}
|
||||
<span
|
||||
style={{
|
||||
whiteSpace: 'pre-wrap',
|
||||
lineHeight: 1.45,
|
||||
overflowWrap: 'anywhere',
|
||||
}}
|
||||
>
|
||||
{parsedText.body}
|
||||
</span>
|
||||
{messageTime ? (
|
||||
<span
|
||||
style={{
|
||||
justifySelf: 'end',
|
||||
fontSize: '0.72rem',
|
||||
lineHeight: 1,
|
||||
color: isAgent ? 'rgba(255,255,255,0.7)' : 'var(--color-text-soft)',
|
||||
}}
|
||||
>
|
||||
{messageTime}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@ -402,7 +502,7 @@ export function MessagesWorkspace({
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/chat')}
|
||||
onClick={sendSuggestedReply}
|
||||
style={{
|
||||
border: '1px solid rgba(0, 164, 183, 0.32)',
|
||||
borderRadius: '16px',
|
||||
@ -507,6 +607,7 @@ export function MessagesWorkspace({
|
||||
<button
|
||||
type="button"
|
||||
onClick={saveNote}
|
||||
disabled={!currentUserId}
|
||||
style={{
|
||||
border: 'none',
|
||||
borderRadius: '18px',
|
||||
@ -514,11 +615,16 @@ export function MessagesWorkspace({
|
||||
background: 'linear-gradient(135deg, var(--color-primary), #0b5a86)',
|
||||
color: '#fff',
|
||||
fontWeight: 800,
|
||||
opacity: currentUserId ? 1 : 0.55,
|
||||
}}
|
||||
>
|
||||
Salvar anotacao
|
||||
</button>
|
||||
|
||||
{notesError ? (
|
||||
<span style={{ color: '#b42318', fontWeight: 700 }}>{notesError}</span>
|
||||
) : null}
|
||||
|
||||
<div style={{ display: 'grid', gap: '0.55rem' }}>
|
||||
{notes.length ? (
|
||||
notes.map((note) => (
|
||||
@ -529,12 +635,32 @@ export function MessagesWorkspace({
|
||||
borderRadius: '16px',
|
||||
padding: '0.8rem',
|
||||
background: '#fff',
|
||||
display: 'grid',
|
||||
gap: '0.35rem',
|
||||
}}
|
||||
>
|
||||
<span style={{ color: 'var(--color-text-soft)', fontSize: '0.82rem' }}>
|
||||
{note.time}
|
||||
</span>
|
||||
<p style={{ margin: '0.35rem 0 0', lineHeight: 1.45 }}>{note.text}</p>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem' }}>
|
||||
<span style={{ color: 'var(--color-text-soft)', fontSize: '0.82rem' }}>
|
||||
{formatMessageTime(new Date(note.created_at).getTime())}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeNote(note.id)}
|
||||
title="Excluir anotacao"
|
||||
style={{
|
||||
border: 'none',
|
||||
borderRadius: 999,
|
||||
width: 26,
|
||||
height: 26,
|
||||
background: 'rgba(214, 40, 40, 0.1)',
|
||||
color: '#b42318',
|
||||
fontWeight: 900,
|
||||
}}
|
||||
>
|
||||
x
|
||||
</button>
|
||||
</div>
|
||||
<p style={{ margin: 0, lineHeight: 1.45 }}>{note.text}</p>
|
||||
</article>
|
||||
))
|
||||
) : (
|
||||
|
||||
@ -18,10 +18,12 @@ function toHomeConversation(contact, messages = []) {
|
||||
lastMessage: contact.preview || messages[messages.length - 1]?.text || '',
|
||||
unread: contact.unread || 0,
|
||||
time: contact.time || 'Agora',
|
||||
lastSeen: contact.lastSeen,
|
||||
messages: messages.map((message) => ({
|
||||
id: message.id,
|
||||
from: message.sender === 'agent' ? 'agent' : 'customer',
|
||||
text: message.text || (message.hasMedia ? '[Midia]' : ''),
|
||||
timestamp: message.timestamp,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@ -33,6 +35,7 @@ export function HomePage() {
|
||||
activeContactId,
|
||||
setActiveContactId,
|
||||
messages,
|
||||
sendMessage,
|
||||
isLoadingChats,
|
||||
} = useChat();
|
||||
const [activeTab, setActiveTab] = useState('messages');
|
||||
@ -141,6 +144,10 @@ export function HomePage() {
|
||||
conversations={filteredConversations}
|
||||
activeConversationId={safeConversationId}
|
||||
onSelectConversation={setActiveContactId}
|
||||
onSendSuggestedReply={async (conversationId, reply) => {
|
||||
setActiveContactId(conversationId);
|
||||
await sendMessage(reply, conversationId);
|
||||
}}
|
||||
isWideDesktop={isWideDesktop}
|
||||
isDesktop={isDesktop}
|
||||
isTablet={isTablet}
|
||||
|
||||
27
src/modules/home/services/agentNotesService.js
Normal file
27
src/modules/home/services/agentNotesService.js
Normal file
@ -0,0 +1,27 @@
|
||||
import { API_BASE_URL } from '../../../shared/services/apiConfig';
|
||||
|
||||
export async function listAgentNotes(userId) {
|
||||
if (!userId) return [];
|
||||
const response = await fetch(`${API_BASE_URL}/agent/notes?userId=${encodeURIComponent(userId)}`);
|
||||
if (!response.ok) throw new Error('Falha ao carregar anotacoes.');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function createAgentNote(userId, text) {
|
||||
const response = await fetch(`${API_BASE_URL}/agent/notes`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ userId, text }),
|
||||
});
|
||||
if (!response.ok) throw new Error('Falha ao salvar anotacao.');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function deleteAgentNote(userId, noteId) {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/agent/notes/${encodeURIComponent(noteId)}?userId=${encodeURIComponent(userId)}`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
if (!response.ok) throw new Error('Falha ao excluir anotacao.');
|
||||
return response.json();
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user