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 }) {
|
function LastMessageDot({ fromMe }) {
|
||||||
const color = status === 'away' ? '#e5a22a' : '#dc2626';
|
const color = fromMe ? '#e5a22a' : '#00a4b7';
|
||||||
|
const label = fromMe ? 'Última mensagem enviada pelo atendimento' : 'Última mensagem enviada pelo cliente';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
aria-hidden="true"
|
title={label}
|
||||||
|
aria-label={label}
|
||||||
style={{
|
style={{
|
||||||
width: 10,
|
width: 10,
|
||||||
height: 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({
|
export function ChatConversationList({
|
||||||
contacts,
|
contacts,
|
||||||
activeContactId,
|
activeContactId,
|
||||||
onSelectContact,
|
onSelectContact,
|
||||||
|
onOpenContact,
|
||||||
isMobile = false,
|
isMobile = false,
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
@ -83,16 +105,16 @@ export function ChatConversationList({
|
|||||||
display: 'grid',
|
display: 'grid',
|
||||||
gridTemplateRows: 'auto minmax(0, 1fr)',
|
gridTemplateRows: 'auto minmax(0, 1fr)',
|
||||||
gap: '0.85rem',
|
gap: '0.85rem',
|
||||||
height: isMobile ? 'auto' : CHAT_LIST_HEIGHT,
|
height: isMobile ? 'auto' : '100%',
|
||||||
maxHeight: isMobile ? 'none' : CHAT_LIST_HEIGHT,
|
maxHeight: isMobile ? 'none' : '100%',
|
||||||
alignSelf: 'start',
|
alignSelf: isMobile ? 'start' : 'stretch',
|
||||||
minHeight: 0,
|
minHeight: 0,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<strong style={{ display: 'block', fontSize: '1.08rem' }}>Conversas ativas</strong>
|
<strong style={{ display: 'block', fontSize: '1.08rem' }}>Conversas ativas</strong>
|
||||||
<span style={{ color: 'var(--color-text-soft)' }}>
|
<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>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -116,6 +138,11 @@ export function ChatConversationList({
|
|||||||
key={contact.id}
|
key={contact.id}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => onSelectContact(contact.id)}
|
onClick={() => onSelectContact(contact.id)}
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
onSelectContact(contact.id);
|
||||||
|
onOpenContact?.(contact);
|
||||||
|
}}
|
||||||
style={{
|
style={{
|
||||||
border: '1px solid',
|
border: '1px solid',
|
||||||
borderColor: isActive ? 'rgba(0, 164, 183, 0.26)' : 'var(--color-border)',
|
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' }}>
|
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '1rem' }}>
|
||||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem', minWidth: 0 }}>
|
<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' }}>
|
<strong style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||||
{contact.name}
|
{contact.name}
|
||||||
</strong>
|
</strong>
|
||||||
@ -139,7 +166,10 @@ export function ChatConversationList({
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem' }}>
|
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem' }}>
|
||||||
|
<span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.45rem', minWidth: 0 }}>
|
||||||
<ChannelBadge channel={contact.channel} />
|
<ChannelBadge channel={contact.channel} />
|
||||||
|
<SavedContactLabel contact={contact} />
|
||||||
|
</span>
|
||||||
<UnreadBadge count={contact.unread} />
|
<UnreadBadge count={contact.unread} />
|
||||||
</div>
|
</div>
|
||||||
<span style={{ color: 'var(--color-text-soft)' }}>{contact.preview}</span>
|
<span style={{ color: 'var(--color-text-soft)' }}>{contact.preview}</span>
|
||||||
|
|||||||
@ -254,6 +254,7 @@ export function ChatWindow({
|
|||||||
canAssumeChat = false,
|
canAssumeChat = false,
|
||||||
canReply = true,
|
canReply = true,
|
||||||
assignmentLabel,
|
assignmentLabel,
|
||||||
|
transferNote,
|
||||||
isReplying,
|
isReplying,
|
||||||
isMobile = false,
|
isMobile = false,
|
||||||
}) {
|
}) {
|
||||||
@ -334,7 +335,7 @@ export function ChatWindow({
|
|||||||
{canAssumeChat ? (
|
{canAssumeChat ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onAssumeChat}
|
onClick={() => onAssumeChat?.()}
|
||||||
style={{
|
style={{
|
||||||
border: 'none',
|
border: 'none',
|
||||||
borderRadius: '14px',
|
borderRadius: '14px',
|
||||||
@ -380,6 +381,24 @@ export function ChatWindow({
|
|||||||
Transferir
|
Transferir
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</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>
|
</header>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@ -535,9 +554,16 @@ export function ChatWindow({
|
|||||||
fontWeight: 700,
|
fontWeight: 700,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<span style={{ display: 'block' }}>
|
||||||
{canAssumeChat
|
{canAssumeChat
|
||||||
? 'Este atendimento esta na fila. Assuma para responder, ou envie uma mensagem para assumir automaticamente.'
|
? 'Este atendimento esta na fila. Assuma para responder ou transferir.'
|
||||||
: assignmentLabel || 'Este atendimento esta atribuido a outro usuario.'}
|
: 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>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
<div
|
<div
|
||||||
@ -583,12 +609,14 @@ export function ChatWindow({
|
|||||||
onSend();
|
onSend();
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={!safeContact.id || (!canReply && !canAssumeChat)}
|
disabled={!safeContact.id || !canReply}
|
||||||
placeholder={
|
placeholder={
|
||||||
!safeContact.id
|
!safeContact.id
|
||||||
? 'Aguardando conversa entrar em uma fila'
|
? 'Aguardando conversa entrar em uma fila'
|
||||||
: canReply || canAssumeChat
|
: canReply
|
||||||
? 'Escreva sua mensagem...'
|
? 'Escreva sua mensagem...'
|
||||||
|
: canAssumeChat
|
||||||
|
? 'Assuma o atendimento para responder'
|
||||||
: 'Atendimento bloqueado para resposta'
|
: 'Atendimento bloqueado para resposta'
|
||||||
}
|
}
|
||||||
style={{
|
style={{
|
||||||
@ -598,13 +626,13 @@ export function ChatWindow({
|
|||||||
background: '#fff',
|
background: '#fff',
|
||||||
outline: 'none',
|
outline: 'none',
|
||||||
minWidth: 0,
|
minWidth: 0,
|
||||||
opacity: safeContact.id && (canReply || canAssumeChat) ? 1 : 0.6,
|
opacity: safeContact.id && canReply ? 1 : 0.6,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onSend}
|
onClick={onSend}
|
||||||
disabled={!safeContact.id || (!canReply && !canAssumeChat)}
|
disabled={!safeContact.id || !canReply}
|
||||||
style={{
|
style={{
|
||||||
border: 'none',
|
border: 'none',
|
||||||
borderRadius: '18px',
|
borderRadius: '18px',
|
||||||
@ -613,7 +641,7 @@ export function ChatWindow({
|
|||||||
color: '#fff',
|
color: '#fff',
|
||||||
fontWeight: 700,
|
fontWeight: 700,
|
||||||
gridColumn: isMobile ? '1 / -1' : 'auto',
|
gridColumn: isMobile ? '1 / -1' : 'auto',
|
||||||
opacity: safeContact.id && (canReply || canAssumeChat) ? 1 : 0.6,
|
opacity: safeContact.id && canReply ? 1 : 0.6,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Enviar
|
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) {
|
function getSerializedId(value) {
|
||||||
if (!value) return '';
|
if (!value) return '';
|
||||||
if (typeof value === 'string') return value;
|
if (typeof value === 'string') return value;
|
||||||
@ -40,6 +46,7 @@ function normalizeChat(chat) {
|
|||||||
const id = getSerializedId(chat.id);
|
const id = getSerializedId(chat.id);
|
||||||
const assignment = chat.assignment || null;
|
const assignment = chat.assignment || null;
|
||||||
const lastSeenTimestamp = chat.timestamp || null;
|
const lastSeenTimestamp = chat.timestamp || null;
|
||||||
|
const hasLastMessageFromMe = typeof chat.lastMessageFromMe === 'boolean';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@ -48,10 +55,12 @@ function normalizeChat(chat) {
|
|||||||
status: lastSeenTimestamp ? 'away' : 'offline',
|
status: lastSeenTimestamp ? 'away' : 'offline',
|
||||||
area: assignment?.area_nome || (assignment?.area_id ? String(assignment.area_id) : 'Sem fila'),
|
area: assignment?.area_nome || (assignment?.area_id ? String(assignment.area_id) : 'Sem fila'),
|
||||||
areaId: assignment?.area_id || null,
|
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 || '',
|
preview: chat.preview || chat.lastMessage?.body || '',
|
||||||
time: formatTime(chat.timestamp) || 'Agora',
|
time: formatTime(chat.timestamp) || 'Agora',
|
||||||
unread: chat.unreadCount || 0,
|
unread: chat.unreadCount || 0,
|
||||||
|
lastMessageFromMe: hasLastMessageFromMe ? chat.lastMessageFromMe : Boolean(chat.lastMessage?.fromMe),
|
||||||
|
contactProfile: chat.contactProfile || null,
|
||||||
assignment,
|
assignment,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -137,7 +146,12 @@ function fileToBase64(file) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildFallbackContacts() {
|
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) {
|
function getUserId(user) {
|
||||||
@ -147,9 +161,15 @@ function getUserId(user) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getUserAreas(user) {
|
function getUserAreas(user) {
|
||||||
const areas = Array.isArray(user?.areas) ? user.areas : [];
|
const normalizeArea = (area) => {
|
||||||
if (user?.areaPrincipal && !areas.includes(user.areaPrincipal)) {
|
if (!area) return null;
|
||||||
return [user.areaPrincipal, ...areas];
|
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;
|
return areas;
|
||||||
}
|
}
|
||||||
@ -172,7 +192,7 @@ export function useChat() {
|
|||||||
const [accessUsers, setAccessUsers] = useState([]);
|
const [accessUsers, setAccessUsers] = useState([]);
|
||||||
const [selectedArea, setSelectedArea] = useState(chatContacts[0].area);
|
const [selectedArea, setSelectedArea] = useState(chatContacts[0].area);
|
||||||
const [isTransferOpen, setIsTransferOpen] = useState(false);
|
const [isTransferOpen, setIsTransferOpen] = useState(false);
|
||||||
const [transferArea, setTransferArea] = useState(currentUser?.areaPrincipal || 'Suporte');
|
const [transferArea, setTransferArea] = useState(currentUserAreas[0] || 'Suporte');
|
||||||
const [transferAttendant, setTransferAttendant] = useState('');
|
const [transferAttendant, setTransferAttendant] = useState('');
|
||||||
const [transferNote, setTransferNote] = useState('');
|
const [transferNote, setTransferNote] = useState('');
|
||||||
const [isReplying] = useState(false);
|
const [isReplying] = useState(false);
|
||||||
@ -182,8 +202,15 @@ export function useChat() {
|
|||||||
const activeContactRef = useRef(activeContactId);
|
const activeContactRef = useRef(activeContactId);
|
||||||
|
|
||||||
const activeContact = useMemo(
|
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] || [];
|
const messages = messagesByContact[activeContactId] || [];
|
||||||
@ -209,6 +236,7 @@ export function useChat() {
|
|||||||
: activeAssignment?.area_nome
|
: activeAssignment?.area_nome
|
||||||
? `Na fila de ${activeAssignment.area_nome}`
|
? `Na fila de ${activeAssignment.area_nome}`
|
||||||
: 'Sem fila definida';
|
: 'Sem fila definida';
|
||||||
|
const transferNoteLabel = activeAssignment?.transfer_note || '';
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setSelectedArea(activeContact?.area || 'Sem fila');
|
setSelectedArea(activeContact?.area || 'Sem fila');
|
||||||
@ -313,16 +341,21 @@ export function useChat() {
|
|||||||
if (!response.ok) throw new Error('Falha ao carregar mensagens do WhatsApp.');
|
if (!response.ok) throw new Error('Falha ao carregar mensagens do WhatsApp.');
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!isMounted || !Array.isArray(data)) return;
|
if (!isMounted || !Array.isArray(data)) return;
|
||||||
setMessagesByContact((current) => ({
|
const normalizedMessages = dedupeMessages(
|
||||||
...current,
|
|
||||||
[activeContactId]: dedupeMessages(
|
|
||||||
data
|
data
|
||||||
.map((message) => ({
|
.map((message) => ({
|
||||||
...normalizeMessage(message),
|
...normalizeMessage(message),
|
||||||
chatId: activeContactId,
|
chatId: activeContactId,
|
||||||
}))
|
}))
|
||||||
.filter(isDisplayableMessage),
|
.filter(isDisplayableMessage),
|
||||||
),
|
);
|
||||||
|
setMessagesByContact((current) => ({
|
||||||
|
...current,
|
||||||
|
[activeContactId]: normalizedMessages,
|
||||||
|
}));
|
||||||
|
updateContact(activeContactId, (contact) => ({
|
||||||
|
...contact,
|
||||||
|
lastMessageFromMe: getLastMessageFromMe(normalizedMessages),
|
||||||
}));
|
}));
|
||||||
setApiError(null);
|
setApiError(null);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -382,7 +415,8 @@ export function useChat() {
|
|||||||
preview,
|
preview,
|
||||||
time: 'Agora',
|
time: 'Agora',
|
||||||
status: 'away',
|
status: 'away',
|
||||||
lastSeen: 'Ultima atividade agora',
|
lastSeen: 'Última atividade agora',
|
||||||
|
lastMessageFromMe: Boolean(incomingMessage.fromMe),
|
||||||
unread:
|
unread:
|
||||||
incomingMessage.fromMe || contactId === activeContactRef.current
|
incomingMessage.fromMe || contactId === activeContactRef.current
|
||||||
? 0
|
? 0
|
||||||
@ -407,6 +441,15 @@ export function useChat() {
|
|||||||
preview: media ? `[Midia: ${media.filename || 'Arquivo'}]` : preview,
|
preview: media ? `[Midia: ${media.filename || 'Arquivo'}]` : preview,
|
||||||
time: 'Agora',
|
time: 'Agora',
|
||||||
unread: 0,
|
unread: 0,
|
||||||
|
lastMessageFromMe: true,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateContactProfile(contactId, profile) {
|
||||||
|
updateContact(contactId, (contact) => ({
|
||||||
|
...contact,
|
||||||
|
name: profile.name || contact.name,
|
||||||
|
contactProfile: profile,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -458,14 +501,17 @@ export function useChat() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function assumeChat() {
|
async function assumeChat(contactId = activeContactId) {
|
||||||
if (!activeContactId?.includes('@') || !currentUserId) return null;
|
if (!contactId?.includes('@') || !currentUserId) return null;
|
||||||
const areaId = activeContact?.areaId || activeAssignment?.area_id || areaOptions.find((area) => currentUserAreas.includes(area.nome))?.id;
|
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`, {
|
const response = await fetch(`${API_BASE_URL}/whatsapp/assign`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
chatId: activeContactId,
|
chatId: contactId,
|
||||||
userId: String(currentUserId),
|
userId: String(currentUserId),
|
||||||
areaId,
|
areaId,
|
||||||
}),
|
}),
|
||||||
@ -473,13 +519,18 @@ export function useChat() {
|
|||||||
|
|
||||||
if (!response.ok) throw new Error('Nao foi possivel assumir o atendimento.');
|
if (!response.ok) throw new Error('Nao foi possivel assumir o atendimento.');
|
||||||
const assignment = await response.json();
|
const assignment = await response.json();
|
||||||
updateContact(activeContactId, (contact) => ({
|
updateContact(contactId, (contact) => ({
|
||||||
...contact,
|
...contact,
|
||||||
assignment,
|
assignment,
|
||||||
area: assignment.area_nome || contact.area,
|
area: assignment.area_nome || contact.area,
|
||||||
areaId: assignment.area_id || contact.areaId,
|
areaId: assignment.area_id || contact.areaId,
|
||||||
}));
|
}));
|
||||||
|
setApiError(null);
|
||||||
return assignment;
|
return assignment;
|
||||||
|
} catch (error) {
|
||||||
|
setApiError(error.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function releaseChat() {
|
async function releaseChat() {
|
||||||
@ -498,19 +549,20 @@ export function useChat() {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendMessage() {
|
async function sendMessage(messageText = draft, contactId = activeContactId) {
|
||||||
const trimmed = draft.trim();
|
const trimmed = String(messageText || '').trim();
|
||||||
if (!trimmed && !attachedFile) return;
|
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 {
|
try {
|
||||||
if (!canReply) {
|
if (!targetIsAssignedToCurrentUser) {
|
||||||
if (canAssumeChat) {
|
setApiError('Assuma o atendimento antes de responder.');
|
||||||
await assumeChat();
|
|
||||||
} else {
|
|
||||||
setApiError('Este atendimento esta atribuido a outro usuario.');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setApiError(error.message);
|
setApiError(error.message);
|
||||||
return;
|
return;
|
||||||
@ -525,7 +577,7 @@ export function useChat() {
|
|||||||
: null;
|
: null;
|
||||||
const newMessage = {
|
const newMessage = {
|
||||||
id: `temp-${Date.now()}`,
|
id: `temp-${Date.now()}`,
|
||||||
chatId: activeContactId,
|
chatId: contactId,
|
||||||
sender: 'agent',
|
sender: 'agent',
|
||||||
text: trimmed,
|
text: trimmed,
|
||||||
timestamp: Math.floor(Date.now() / 1000),
|
timestamp: Math.floor(Date.now() / 1000),
|
||||||
@ -535,26 +587,34 @@ export function useChat() {
|
|||||||
|
|
||||||
setMessagesByContact((current) => ({
|
setMessagesByContact((current) => ({
|
||||||
...current,
|
...current,
|
||||||
[activeContactId]: mergeMessageList(current[activeContactId] || [], newMessage),
|
[contactId]: mergeMessageList(current[contactId] || [], newMessage),
|
||||||
}));
|
}));
|
||||||
updateContactPreview(activeContactId, trimmed || '[Midia]', media);
|
updateContactPreview(contactId, trimmed || '[Midia]', media);
|
||||||
|
if (contactId === activeContactId) {
|
||||||
setDraft('');
|
setDraft('');
|
||||||
|
}
|
||||||
setAttachedFile(null);
|
setAttachedFile(null);
|
||||||
|
|
||||||
if (!activeContactId.includes('@')) return;
|
if (!contactId.includes('@')) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetch(`${API_BASE_URL}/whatsapp/send`, {
|
await fetch(`${API_BASE_URL}/whatsapp/send`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
to: activeContactId,
|
to: contactId,
|
||||||
message: trimmed,
|
message: trimmed,
|
||||||
senderName: getUserDisplayName(currentUser),
|
senderName: getUserDisplayName(currentUser),
|
||||||
media,
|
media,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
setApiError(null);
|
setApiError(null);
|
||||||
|
updateContact(contactId, (contact) => ({
|
||||||
|
...contact,
|
||||||
|
assignment: contact.assignment
|
||||||
|
? { ...contact.assignment, transfer_note: null }
|
||||||
|
: contact.assignment,
|
||||||
|
}));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setApiError(error.message);
|
setApiError(error.message);
|
||||||
}
|
}
|
||||||
@ -569,6 +629,11 @@ export function useChat() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isAssignedToCurrentUser) {
|
||||||
|
setApiError('Assuma o atendimento antes de transferir.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const targetUserId = isSameUserArea && transferAttendant ? Number(transferAttendant) : null;
|
const targetUserId = isSameUserArea && transferAttendant ? Number(transferAttendant) : null;
|
||||||
const response = await fetch(`${API_BASE_URL}/whatsapp/transfer`, {
|
const response = await fetch(`${API_BASE_URL}/whatsapp/transfer`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@ -629,8 +694,10 @@ export function useChat() {
|
|||||||
canAssumeChat,
|
canAssumeChat,
|
||||||
canReply,
|
canReply,
|
||||||
assignmentLabel,
|
assignmentLabel,
|
||||||
|
transferNoteLabel,
|
||||||
isAssignedToCurrentUser,
|
isAssignedToCurrentUser,
|
||||||
activeAssignment,
|
activeAssignment,
|
||||||
|
updateContactProfile,
|
||||||
isReplying,
|
isReplying,
|
||||||
isLoadingChats,
|
isLoadingChats,
|
||||||
isLoadingMessages,
|
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 { BrandMark } from '../../../shared/components/BrandMark';
|
||||||
import { useViewport } from '../../../shared/hooks/useViewport';
|
import { useViewport } from '../../../shared/hooks/useViewport';
|
||||||
import { ChatConversationList } from '../components/ChatConversationList';
|
import { ChatConversationList } from '../components/ChatConversationList';
|
||||||
import { ChatTransferPanel } from '../components/ChatTransferPanel';
|
import { ChatTransferPanel } from '../components/ChatTransferPanel';
|
||||||
|
import { ContactProfilePanel } from '../components/ContactProfilePanel';
|
||||||
import { ChatWindow } from '../components/ChatWindow';
|
import { ChatWindow } from '../components/ChatWindow';
|
||||||
import { useChat } from '../hooks/useChat';
|
import { useChat } from '../hooks/useChat';
|
||||||
import { quickReplies } from '../services/chatMocks';
|
import { quickReplies } from '../services/chatMocks';
|
||||||
|
|
||||||
export function ChatPage() {
|
export function ChatPage() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
const { isWideDesktop, isDesktop, isTablet, isMobile } = useViewport();
|
const { isWideDesktop, isDesktop, isTablet, isMobile } = useViewport();
|
||||||
const {
|
const {
|
||||||
contacts,
|
contacts,
|
||||||
@ -27,6 +30,8 @@ export function ChatPage() {
|
|||||||
canAssumeChat,
|
canAssumeChat,
|
||||||
canReply,
|
canReply,
|
||||||
assignmentLabel,
|
assignmentLabel,
|
||||||
|
transferNoteLabel,
|
||||||
|
updateContactProfile,
|
||||||
isReplying,
|
isReplying,
|
||||||
selectedArea,
|
selectedArea,
|
||||||
setSelectedArea,
|
setSelectedArea,
|
||||||
@ -43,6 +48,14 @@ export function ChatPage() {
|
|||||||
setTransferNote,
|
setTransferNote,
|
||||||
submitTransfer,
|
submitTransfer,
|
||||||
} = useChat();
|
} = 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
|
const gridTemplateColumns = isMobile
|
||||||
? '1fr'
|
? '1fr'
|
||||||
@ -116,6 +129,10 @@ export function ChatPage() {
|
|||||||
contacts={contacts}
|
contacts={contacts}
|
||||||
activeContactId={activeContactId}
|
activeContactId={activeContactId}
|
||||||
onSelectContact={setActiveContactId}
|
onSelectContact={setActiveContactId}
|
||||||
|
onOpenContact={() => {
|
||||||
|
setIsTransferOpen(false);
|
||||||
|
setIsContactPanelOpen(true);
|
||||||
|
}}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@ -132,12 +149,16 @@ export function ChatPage() {
|
|||||||
onRemoveAttachedFile={removeAttachedFile}
|
onRemoveAttachedFile={removeAttachedFile}
|
||||||
onLoadMedia={hydrateMessageMedia}
|
onLoadMedia={hydrateMessageMedia}
|
||||||
onSend={sendMessage}
|
onSend={sendMessage}
|
||||||
onToggleTransfer={() => setIsTransferOpen((current) => !current)}
|
onToggleTransfer={() => {
|
||||||
|
setIsContactPanelOpen(false);
|
||||||
|
setIsTransferOpen((current) => !current);
|
||||||
|
}}
|
||||||
onAssumeChat={assumeChat}
|
onAssumeChat={assumeChat}
|
||||||
onReleaseChat={releaseChat}
|
onReleaseChat={releaseChat}
|
||||||
canAssumeChat={canAssumeChat}
|
canAssumeChat={canAssumeChat}
|
||||||
canReply={canReply}
|
canReply={canReply}
|
||||||
assignmentLabel={assignmentLabel}
|
assignmentLabel={assignmentLabel}
|
||||||
|
transferNote={transferNoteLabel}
|
||||||
isReplying={isReplying}
|
isReplying={isReplying}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
/>
|
/>
|
||||||
@ -171,6 +192,7 @@ export function ChatPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isWideDesktop ? (
|
{isWideDesktop ? (
|
||||||
|
<>
|
||||||
<ChatTransferPanel
|
<ChatTransferPanel
|
||||||
isOpen={isTransferOpen}
|
isOpen={isTransferOpen}
|
||||||
transferArea={transferArea}
|
transferArea={transferArea}
|
||||||
@ -185,10 +207,18 @@ export function ChatPage() {
|
|||||||
onSubmit={submitTransfer}
|
onSubmit={submitTransfer}
|
||||||
onClose={() => setIsTransferOpen(false)}
|
onClose={() => setIsTransferOpen(false)}
|
||||||
/>
|
/>
|
||||||
|
<ContactProfilePanel
|
||||||
|
isOpen={isContactPanelOpen}
|
||||||
|
contact={activeContact}
|
||||||
|
onClose={() => setIsContactPanelOpen(false)}
|
||||||
|
onSaved={updateContactProfile}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{!isWideDesktop ? (
|
{!isWideDesktop ? (
|
||||||
|
<>
|
||||||
<ChatTransferPanel
|
<ChatTransferPanel
|
||||||
isOpen={isTransferOpen}
|
isOpen={isTransferOpen}
|
||||||
transferArea={transferArea}
|
transferArea={transferArea}
|
||||||
@ -203,6 +233,13 @@ export function ChatPage() {
|
|||||||
onSubmit={submitTransfer}
|
onSubmit={submitTransfer}
|
||||||
onClose={() => setIsTransferOpen(false)}
|
onClose={() => setIsTransferOpen(false)}
|
||||||
/>
|
/>
|
||||||
|
<ContactProfilePanel
|
||||||
|
isOpen={isContactPanelOpen}
|
||||||
|
contact={activeContact}
|
||||||
|
onClose={() => setIsContactPanelOpen(false)}
|
||||||
|
onSaved={updateContactProfile}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</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 { useEffect, useMemo, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { createAgentNote, deleteAgentNote, listAgentNotes } from '../services/agentNotesService';
|
||||||
|
import { getCurrentUser } from '../../auth/services/sessionService';
|
||||||
|
|
||||||
const WORKSPACE_HEIGHT = 660;
|
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({
|
export function MessagesWorkspace({
|
||||||
conversations,
|
conversations,
|
||||||
activeConversationId,
|
activeConversationId,
|
||||||
onSelectConversation,
|
onSelectConversation,
|
||||||
|
onSendSuggestedReply,
|
||||||
isWideDesktop = false,
|
isWideDesktop = false,
|
||||||
isDesktop = false,
|
isDesktop = false,
|
||||||
isTablet = false,
|
isTablet = false,
|
||||||
isMobile = false,
|
isMobile = false,
|
||||||
}) {
|
}) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const currentUser = getCurrentUser();
|
||||||
|
const currentUserId = getUserId(currentUser);
|
||||||
const recentConversations = conversations.slice(0, 3);
|
const recentConversations = conversations.slice(0, 3);
|
||||||
const activeConversation =
|
const activeConversation =
|
||||||
recentConversations.find((conversation) => conversation.id === activeConversationId) ||
|
recentConversations.find((conversation) => conversation.id === activeConversationId) ||
|
||||||
@ -127,13 +159,8 @@ export function MessagesWorkspace({
|
|||||||
);
|
);
|
||||||
const [selectedReplyIndex, setSelectedReplyIndex] = useState(0);
|
const [selectedReplyIndex, setSelectedReplyIndex] = useState(0);
|
||||||
const [noteDraft, setNoteDraft] = useState('');
|
const [noteDraft, setNoteDraft] = useState('');
|
||||||
const [notes, setNotes] = useState(() => {
|
const [notes, setNotes] = useState([]);
|
||||||
try {
|
const [notesError, setNotesError] = useState('');
|
||||||
return JSON.parse(window.localStorage.getItem('agentNotes') || '[]');
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const selectedReply = suggestedReplies[selectedReplyIndex] || suggestedReplies[0];
|
const selectedReply = suggestedReplies[selectedReplyIndex] || suggestedReplies[0];
|
||||||
const managerMessages = [
|
const managerMessages = [
|
||||||
@ -154,8 +181,25 @@ export function MessagesWorkspace({
|
|||||||
}, [safeActiveConversation.id]);
|
}, [safeActiveConversation.id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
window.localStorage.setItem('agentNotes', JSON.stringify(notes));
|
let isMounted = true;
|
||||||
}, [notes]);
|
|
||||||
|
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() {
|
function selectPreviousReply() {
|
||||||
setSelectedReplyIndex((current) =>
|
setSelectedReplyIndex((current) =>
|
||||||
@ -167,19 +211,37 @@ export function MessagesWorkspace({
|
|||||||
setSelectedReplyIndex((current) => (current + 1) % suggestedReplies.length);
|
setSelectedReplyIndex((current) => (current + 1) % suggestedReplies.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveNote() {
|
async function saveNote() {
|
||||||
const text = noteDraft.trim();
|
const text = noteDraft.trim();
|
||||||
if (!text) return;
|
if (!text || !currentUserId) return;
|
||||||
|
|
||||||
setNotes((current) => [
|
try {
|
||||||
{
|
const note = await createAgentNote(currentUserId, text);
|
||||||
id: Date.now(),
|
setNotes((current) => [note, ...current]);
|
||||||
text,
|
|
||||||
time: new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }),
|
|
||||||
},
|
|
||||||
...current,
|
|
||||||
]);
|
|
||||||
setNoteDraft('');
|
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
|
const gridTemplateColumns = isMobile
|
||||||
@ -348,6 +410,8 @@ export function MessagesWorkspace({
|
|||||||
>
|
>
|
||||||
{safeActiveConversation.messages.map((message) => {
|
{safeActiveConversation.messages.map((message) => {
|
||||||
const isAgent = message.from === 'agent';
|
const isAgent = message.from === 'agent';
|
||||||
|
const parsedText = parseMessageText(message.text);
|
||||||
|
const messageTime = formatMessageTime(message.timestamp);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@ -360,9 +424,45 @@ export function MessagesWorkspace({
|
|||||||
background: isAgent ? 'var(--color-primary)' : '#edf1f5',
|
background: isAgent ? 'var(--color-primary)' : '#edf1f5',
|
||||||
color: isAgent ? '#fff' : 'var(--color-text)',
|
color: isAgent ? '#fff' : 'var(--color-text)',
|
||||||
boxShadow: 'var(--shadow-md)',
|
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>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@ -402,7 +502,7 @@ export function MessagesWorkspace({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => navigate('/chat')}
|
onClick={sendSuggestedReply}
|
||||||
style={{
|
style={{
|
||||||
border: '1px solid rgba(0, 164, 183, 0.32)',
|
border: '1px solid rgba(0, 164, 183, 0.32)',
|
||||||
borderRadius: '16px',
|
borderRadius: '16px',
|
||||||
@ -507,6 +607,7 @@ export function MessagesWorkspace({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={saveNote}
|
onClick={saveNote}
|
||||||
|
disabled={!currentUserId}
|
||||||
style={{
|
style={{
|
||||||
border: 'none',
|
border: 'none',
|
||||||
borderRadius: '18px',
|
borderRadius: '18px',
|
||||||
@ -514,11 +615,16 @@ export function MessagesWorkspace({
|
|||||||
background: 'linear-gradient(135deg, var(--color-primary), #0b5a86)',
|
background: 'linear-gradient(135deg, var(--color-primary), #0b5a86)',
|
||||||
color: '#fff',
|
color: '#fff',
|
||||||
fontWeight: 800,
|
fontWeight: 800,
|
||||||
|
opacity: currentUserId ? 1 : 0.55,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Salvar anotacao
|
Salvar anotacao
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{notesError ? (
|
||||||
|
<span style={{ color: '#b42318', fontWeight: 700 }}>{notesError}</span>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div style={{ display: 'grid', gap: '0.55rem' }}>
|
<div style={{ display: 'grid', gap: '0.55rem' }}>
|
||||||
{notes.length ? (
|
{notes.length ? (
|
||||||
notes.map((note) => (
|
notes.map((note) => (
|
||||||
@ -529,12 +635,32 @@ export function MessagesWorkspace({
|
|||||||
borderRadius: '16px',
|
borderRadius: '16px',
|
||||||
padding: '0.8rem',
|
padding: '0.8rem',
|
||||||
background: '#fff',
|
background: '#fff',
|
||||||
|
display: 'grid',
|
||||||
|
gap: '0.35rem',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.75rem' }}>
|
||||||
<span style={{ color: 'var(--color-text-soft)', fontSize: '0.82rem' }}>
|
<span style={{ color: 'var(--color-text-soft)', fontSize: '0.82rem' }}>
|
||||||
{note.time}
|
{formatMessageTime(new Date(note.created_at).getTime())}
|
||||||
</span>
|
</span>
|
||||||
<p style={{ margin: '0.35rem 0 0', lineHeight: 1.45 }}>{note.text}</p>
|
<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>
|
</article>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@ -18,10 +18,12 @@ function toHomeConversation(contact, messages = []) {
|
|||||||
lastMessage: contact.preview || messages[messages.length - 1]?.text || '',
|
lastMessage: contact.preview || messages[messages.length - 1]?.text || '',
|
||||||
unread: contact.unread || 0,
|
unread: contact.unread || 0,
|
||||||
time: contact.time || 'Agora',
|
time: contact.time || 'Agora',
|
||||||
|
lastSeen: contact.lastSeen,
|
||||||
messages: messages.map((message) => ({
|
messages: messages.map((message) => ({
|
||||||
id: message.id,
|
id: message.id,
|
||||||
from: message.sender === 'agent' ? 'agent' : 'customer',
|
from: message.sender === 'agent' ? 'agent' : 'customer',
|
||||||
text: message.text || (message.hasMedia ? '[Midia]' : ''),
|
text: message.text || (message.hasMedia ? '[Midia]' : ''),
|
||||||
|
timestamp: message.timestamp,
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -33,6 +35,7 @@ export function HomePage() {
|
|||||||
activeContactId,
|
activeContactId,
|
||||||
setActiveContactId,
|
setActiveContactId,
|
||||||
messages,
|
messages,
|
||||||
|
sendMessage,
|
||||||
isLoadingChats,
|
isLoadingChats,
|
||||||
} = useChat();
|
} = useChat();
|
||||||
const [activeTab, setActiveTab] = useState('messages');
|
const [activeTab, setActiveTab] = useState('messages');
|
||||||
@ -141,6 +144,10 @@ export function HomePage() {
|
|||||||
conversations={filteredConversations}
|
conversations={filteredConversations}
|
||||||
activeConversationId={safeConversationId}
|
activeConversationId={safeConversationId}
|
||||||
onSelectConversation={setActiveContactId}
|
onSelectConversation={setActiveContactId}
|
||||||
|
onSendSuggestedReply={async (conversationId, reply) => {
|
||||||
|
setActiveContactId(conversationId);
|
||||||
|
await sendMessage(reply, conversationId);
|
||||||
|
}}
|
||||||
isWideDesktop={isWideDesktop}
|
isWideDesktop={isWideDesktop}
|
||||||
isDesktop={isDesktop}
|
isDesktop={isDesktop}
|
||||||
isTablet={isTablet}
|
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