2644e60bb6
Sessão 11+: fechamento do CRM de WhatsApp com dois providers (Evolution/Twilio),
sistema de créditos com Asaas/PIX, polimorfismo de telefones/emails, e integração
admin SaaS no /saas/addons existente.
═══════════════════════════════════════════════════════════════════════════
GRUPO 3 — WORKFLOW / CRM (completo)
═══════════════════════════════════════════════════════════════════════════
3.1 Tags · migration conversation_tags + seed de 5 system tags · composable
useConversationTags.js · popover + pills no drawer e nos cards do Kanban.
3.2 Atribuição de conversa a terapeuta · migration 20260421000012 com PK
(tenant_id, thread_key), UPSERT, RLS que valida assignee como membro ativo
do mesmo tenant · view conversation_threads expandida com assigned_to +
assigned_at · composable useConversationAssignment.js · drawer com Select
filtrável + botão "Assumir" · inbox com filtro aside (Todas/Minhas/Não
atribuídas) e chip do responsável em cada card (destaca "Eu" em azul).
3.3 Notas internas · migration conversation_notes · composable + seção
colapsável no drawer · apenas o criador pode editar/apagar (RLS).
3.5 Converter desconhecido em paciente · botão + dialog quick-cadastro ·
"Vincular existente" com Select filter de até 500 pacientes · cria
telefone WhatsApp (vinculado) via upsertWhatsappForExisting.
3.6 Histórico de conversa no prontuário · nova aba "Conversas" em
PatientProntuario.vue · PatientConversationsTab.vue com stats (total /
recebidas / enviadas / primeira / última), SelectButton de filtro, timeline
com bolhas por direção, mídia inline (imagem/áudio/vídeo/doc via signed
URL), indicadores ✓ ✓✓ de delivery, botão "Abrir no CRM".
═══════════════════════════════════════════════════════════════════════════
MARCO A — UNIFICAÇÃO WHATSAPP (dois providers mutuamente exclusivos)
═══════════════════════════════════════════════════════════════════════════
- Página chooser ConfiguracoesWhatsappChooserPage.vue com 2 cards (Pessoal/
Oficial), deactivate via edge function deactivate-notification-channel
- send-whatsapp-message refatorada com roteamento por provider; Twilio deduz
1 crédito antes do envio e refunda em falha
- Paridade Twilio (novo): módulo compartilhado supabase/functions/_shared/
whatsapp-hooks.ts com lógica provider-agnóstica (opt-in, opt-out, auto-
reply, schedule helpers em TZ São Paulo, makeTwilioCreditedSendFn que
envolve envio em dedução atômica + rollback). Consumido por Evolution E
Twilio inbound. Evolution refatorado (~290 linhas duplicadas removidas).
- Bucket privado whatsapp-media · decrypt via Evolution getBase64From
MediaMessage · upload com path tenant/yyyy/mm · signed URLs on-demand
═══════════════════════════════════════════════════════════════════════════
MARCO B — SISTEMA DE CRÉDITOS WHATSAPP + ASAAS
═══════════════════════════════════════════════════════════════════════════
Banco:
- Migration 20260421000007_whatsapp_credits (4 tabelas: balance,
transactions, packages, purchases) + RPCs add_whatsapp_credits e
deduct_whatsapp_credits (atômicas com SELECT FOR UPDATE)
- Migration 20260421000013_tenant_cpf_cnpj (coluna em tenants com CHECK
de 11 ou 14 dígitos)
Edge functions:
- create-whatsapp-credit-charge · Asaas v3 (sandbox + prod) · PIX com
QR code · getOrCreateAsaasCustomer patcha customer existente com CPF
quando está faltando
- asaas-webhook · recebe PAYMENT_RECEIVED/CONFIRMED e credita balance
Frontend (tenant):
- Página /configuracoes/creditos-whatsapp com saldo + loja + histórico
- Dialog de confirmação com CPF/CNPJ (validação via isValidCPF/CNPJ de
utils/validators, formatação on-blur, pré-fill de tenants.cpf_cnpj,
persiste no primeiro uso) · fallback sandbox 24971563792 REMOVIDO
- Composable useWhatsappCredits extrai erros amigáveis via
error.context.json()
Frontend (SaaS admin):
- Em /saas/addons (reuso do pattern existente, não criou página paralela):
- Aba 4 "Pacotes WhatsApp" — CRUD whatsapp_credit_packages com DataTable,
toggle is_active inline, dialog de edição com validação
- Aba 5 "Topup WhatsApp" — tenant Select com saldo ao vivo · RPC
add_whatsapp_credits com p_admin_id = auth.uid() (auditoria) · histórico
das últimas 20 transações topup/adjustment/refund
═══════════════════════════════════════════════════════════════════════════
GRUPO 2 — AUTOMAÇÃO
═══════════════════════════════════════════════════════════════════════════
2.3 Auto-reply · conversation_autoreply_settings + conversation_autoreply_
log · 3 modos de schedule (agenda das regras semanais, business_hours
custom, custom_window) · cooldown por thread · respeita opt-out · agora
funciona em Evolution E Twilio (hooks compartilhados)
2.4 Lembretes de sessão · conversation_session_reminders_settings +
_logs · edge send-session-reminders (cron) · janelas 24h e 2h antes ·
Twilio deduz crédito com rollback em falha
═══════════════════════════════════════════════════════════════════════════
GRUPO 5 — COMPLIANCE (LGPD Art. 18 §2)
═══════════════════════════════════════════════════════════════════════════
5.2 Opt-out · conversation_optouts + conversation_optout_keywords (10 system
seed + custom por tenant) · detecção por regex word-boundary e normalização
(lowercase + strip acentos + pontuação) · ack automático (deduz crédito em
Twilio) · opt-in via "voltar", "retornar", "reativar", "restart" ·
página /configuracoes/conversas-optouts com CRUD de keywords
═══════════════════════════════════════════════════════════════════════════
REFACTOR POLIMÓRFICO — TELEFONES + EMAILS
═══════════════════════════════════════════════════════════════════════════
- contact_types + contact_phones (entity_type + entity_id) — migration
20260421000008 · contact_email_types + contact_emails — 20260421000011
- Componentes ContactPhonesEditor.vue e ContactEmailsEditor.vue (add/edit/
remove com confirm, primary selector, WhatsApp linked badge)
- Composables useContactPhones.js + useContactEmails.js com
unsetOtherPrimaries() e validação
- Trocado em PatientsCadastroPage.vue e MedicosPage.vue (removidos campos
legados telefone/telefone_alternativo e email_principal/email_alternativo)
- Migration retroativa v2 (20260421000010) detecta conversation_messages
e cria/atualiza phone como WhatsApp vinculado
═══════════════════════════════════════════════════════════════════════════
POLIMENTO VISUAL + INFRA
═══════════════════════════════════════════════════════════════════════════
- Skeletons simplificados no dashboard do terapeuta
- Animações fade-up com stagger via [--delay:Xms] (fix specificity sobre
.dash-card box-shadow transition)
- ConfirmDialog com group="conversation-drawer" (evita montagem duplicada)
- Image preview PrimeVue com botão de download injetado via MutationObserver
(fetch + blob para funcionar cross-origin)
- Áudio/vídeo com preload="metadata" e controles de velocidade do browser
- friendlySendError() mapeia códigos do edge pra mensagens pt-BR via
error.context.json()
- Teleport #cfg-page-actions para ações globais de Configurações
- Brotli/Gzip + auto-import Vue/PrimeVue + bundle analyzer
- AppLayout consolidado (removidas duplicatas por área) + RouterPassthrough
- Removido console.trace debug que estava em watch de router e queries
Supabase (degradava perf pra todos)
- Realtime em conversation_messages via publication supabase_realtime
- Notifier global flutuante com beep + toggle mute (4 camadas: badge +
sino + popup + browser notification)
═══════════════════════════════════════════════════════════════════════════
MIGRATIONS NOVAS (13)
═══════════════════════════════════════════════════════════════════════════
20260420000001_patient_intake_invite_info_rpc
20260420000002_audit_logs_lgpd
20260420000003_audit_logs_unified_view
20260420000004_lgpd_export_patient_rpc
20260420000005_conversation_messages
20260420000005_search_global_rpc
20260420000006_conv_messages_notifications
20260420000007_notif_channels_saas_admin_insert
20260420000008_conv_messages_realtime
20260420000009_conv_messages_delivery_status
20260421000001_whatsapp_media_bucket
20260421000002_conversation_notes
20260421000003_conversation_tags
20260421000004_conversation_autoreply
20260421000005_conversation_optouts
20260421000006_session_reminders
20260421000007_whatsapp_credits
20260421000008_contact_phones
20260421000009_retroactive_whatsapp_link
20260421000010_retroactive_whatsapp_link_v2
20260421000011_contact_emails
20260421000012_conversation_assignments
20260421000013_tenant_cpf_cnpj
═══════════════════════════════════════════════════════════════════════════
EDGE FUNCTIONS NOVAS / MODIFICADAS
═══════════════════════════════════════════════════════════════════════════
Novas:
- _shared/whatsapp-hooks.ts (módulo compartilhado)
- asaas-webhook
- create-whatsapp-credit-charge
- deactivate-notification-channel
- evolution-webhook-provision
- evolution-whatsapp-inbound
- get-intake-invite-info
- notification-webhook
- send-session-reminders
- send-whatsapp-message
- submit-patient-intake
- twilio-whatsapp-inbound
═══════════════════════════════════════════════════════════════════════════
FRONTEND — RESUMO
═══════════════════════════════════════════════════════════════════════════
Composables novos: useAddonExtrato, useAuditoria, useAutoReplySettings,
useClinicKPIs, useContactEmails, useContactPhones, useConversationAssignment,
useConversationNotes, useConversationOptouts, useConversationTags,
useConversations, useLgpdExport, useSessionReminders, useWhatsappCredits
Stores: conversationDrawerStore
Componentes novos: ConversationDrawer, GlobalInboundNotifier, GlobalSearch,
ContactEmailsEditor, ContactPhonesEditor
Páginas novas: CRMConversasPage, PatientConversationsTab, AddonsExtratoPage,
AuditoriaPage, NotificationsHistoryPage, ConfiguracoesWhatsappChooserPage,
ConfiguracoesConversasAutoreplyPage, ConfiguracoesConversasOptoutsPage,
ConfiguracoesConversasTagsPage, ConfiguracoesCreditosWhatsappPage,
ConfiguracoesLembretesSessaoPage
Utils novos: addonExtratoExport, auditoriaExport, excelExport,
lgpdExportFormats
Páginas existentes alteradas: ClinicDashboard, PatientsCadastroPage,
PatientCadastroDialog, PatientsListPage, MedicosPage, PatientProntuario,
ConfiguracoesWhatsappPage, SaasWhatsappPage, ConfiguracoesRecursosExtrasPage,
ConfiguracoesPage, AgendaTerapeutaPage, AgendaClinicaPage, NotificationItem,
NotificationDrawer, AppLayout, AppTopbar, useMenuBadges,
patientsRepository, SaasAddonsPage (aba 4 + 5 WhatsApp)
Routes: routes.clinic, routes.configs, routes.therapist atualizados
Menus: clinic.menu, therapist.menu, saas.menu atualizados
═══════════════════════════════════════════════════════════════════════════
NOTAS
- Após subir, rodar supabase functions serve --no-verify-jwt
--env-file supabase/functions/.env pra carregar o módulo _shared
- WHATSAPP_SETUP.md reescrito (~400 linhas) com setup completo dos 3
providers + troubleshooting + LGPD
- HANDOFF.md atualizado com estado atual e próximos passos
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
532 lines
27 KiB
Vue
532 lines
27 KiB
Vue
<!--
|
|
|--------------------------------------------------------------------------
|
|
| Agência PSI
|
|
|--------------------------------------------------------------------------
|
|
| Criado e desenvolvido por Leonardo Nohama
|
|
|
|
|
| Tecnologia aplicada à escuta.
|
|
| Estrutura para o cuidado.
|
|
|
|
|
| Arquivo: src/features/conversations/CRMConversasPage.vue
|
|
| Data: 2026
|
|
| Local: São Carlos/SP — Brasil
|
|
|--------------------------------------------------------------------------
|
|
| © 2026 — Todos os direitos reservados
|
|
|--------------------------------------------------------------------------
|
|
-->
|
|
<script setup>
|
|
import { ref, computed, onMounted, watch } from 'vue';
|
|
import { useRoute, useRouter } from 'vue-router';
|
|
import { supabase } from '@/lib/supabase/client';
|
|
import { useConversations } from '@/composables/useConversations';
|
|
import { useConversationTags } from '@/composables/useConversationTags';
|
|
import { useTenantStore } from '@/stores/tenantStore';
|
|
import { useLayout } from '@/layout/composables/layout';
|
|
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
|
|
|
const route = useRoute();
|
|
const router = useRouter();
|
|
const tenantStore = useTenantStore();
|
|
const drawerStore = useConversationDrawerStore();
|
|
|
|
function goSettings() {
|
|
router.push('/configuracoes/whatsapp');
|
|
}
|
|
|
|
const { threads, filteredThreads, byKanban, summary, filters, loading, load, subscribeRealtime, unsubscribeRealtime } = useConversations();
|
|
|
|
// Tags — pra renderizar pills nos cards
|
|
const tagsApi = useConversationTags();
|
|
const threadTagsMap = ref(new Map()); // Map<thread_key, tag_id[]>
|
|
const tagById = computed(() => {
|
|
const m = {};
|
|
for (const t of tagsApi.allTags.value) m[t.id] = t;
|
|
return m;
|
|
});
|
|
|
|
function tagsForThread(threadKey) {
|
|
const ids = threadTagsMap.value.get(threadKey) || [];
|
|
return ids.map((id) => tagById.value[id]).filter(Boolean);
|
|
}
|
|
|
|
async function reloadThreadTags() {
|
|
const keys = filteredThreads.value.map((t) => t.thread_key);
|
|
threadTagsMap.value = await tagsApi.loadForThreads(keys);
|
|
}
|
|
|
|
// Layout
|
|
const { effectiveVariant, layoutState, layoutConfig, isMobile, railPanelPushesLayout } = useLayout();
|
|
const isMobileLayout = computed(() => isMobile.value);
|
|
const asideLeft = computed(() => {
|
|
if (isMobileLayout.value) return undefined;
|
|
if (effectiveVariant.value !== 'rail') {
|
|
const isStaticActive = layoutConfig.menuMode === 'static' && !layoutState.staticMenuInactive;
|
|
return isStaticActive ? '20rem' : '0';
|
|
}
|
|
return railPanelPushesLayout.value ? 'calc(60px + 260px)' : '60px';
|
|
});
|
|
const asideOpen = ref(false);
|
|
|
|
const KANBAN_COLUMNS = [
|
|
{ key: 'urgent', label: 'Urgente', icon: 'pi pi-exclamation-triangle', color: 'red' },
|
|
{ key: 'awaiting_us', label: 'Aguardando resposta', icon: 'pi pi-inbox', color: 'amber' },
|
|
{ key: 'awaiting_patient', label: 'Aguardando paciente', icon: 'pi pi-hourglass', color: 'blue' },
|
|
{ key: 'resolved', label: 'Resolvido', icon: 'pi pi-check', color: 'emerald' }
|
|
];
|
|
|
|
const CHANNEL_OPTIONS = [
|
|
{ label: 'Todos', value: null },
|
|
{ label: 'WhatsApp', value: 'whatsapp' },
|
|
{ label: 'SMS', value: 'sms' },
|
|
{ label: 'E-mail', value: 'email' }
|
|
];
|
|
|
|
function fmtRelative(iso) {
|
|
if (!iso) return '';
|
|
const d = new Date(iso);
|
|
const now = new Date();
|
|
const diff = Math.floor((now - d) / 1000);
|
|
if (diff < 60) return 'agora';
|
|
if (diff < 3600) return `${Math.floor(diff / 60)}m`;
|
|
if (diff < 86400) return `${Math.floor(diff / 3600)}h`;
|
|
if (diff < 604800) return `${Math.floor(diff / 86400)}d`;
|
|
return d.toLocaleDateString('pt-BR');
|
|
}
|
|
|
|
function channelIcon(ch) {
|
|
const map = { whatsapp: 'pi-whatsapp', sms: 'pi-comment', email: 'pi-envelope' };
|
|
return map[ch] || 'pi-comment';
|
|
}
|
|
|
|
function truncate(s, n = 80) {
|
|
if (!s) return '';
|
|
const str = String(s).replace(/\s+/g, ' ').trim();
|
|
return str.length > n ? str.slice(0, n - 1) + '…' : str;
|
|
}
|
|
|
|
function contactLabel(thread) {
|
|
return thread.patient_name || thread.contact_number || 'Desconhecido';
|
|
}
|
|
|
|
function onCardClick(thread) {
|
|
drawerStore.openForThread(thread);
|
|
if (isMobileLayout.value) asideOpen.value = false;
|
|
}
|
|
|
|
// Top 10 pacientes com atividade recente — aside
|
|
const recentPatients = computed(() => {
|
|
return filteredThreads.value
|
|
.filter((t) => t.patient_id)
|
|
.slice(0, 10);
|
|
});
|
|
|
|
const unlinkedCount = computed(() => filteredThreads.value.filter((t) => !t.patient_id).length);
|
|
|
|
// Atribuição — contadores sobre threads (antes do filtro de atribuição)
|
|
const currentUserId = ref(null);
|
|
supabase.auth.getUser().then(({ data }) => { currentUserId.value = data?.user?.id ?? null; });
|
|
const mineCount = computed(() => {
|
|
const uid = currentUserId.value;
|
|
if (!uid) return 0;
|
|
return threads.value.filter((t) => t.assigned_to === uid).length;
|
|
});
|
|
const unassignedCount = computed(() => threads.value.filter((t) => !t.assigned_to).length);
|
|
|
|
// Map user_id → nome curto pra chip no card
|
|
const memberNameMap = ref({});
|
|
async function loadMemberNames() {
|
|
const tenantId = tenantStore.activeTenantId;
|
|
if (!tenantId) return;
|
|
const { data } = await supabase
|
|
.from('v_tenant_members_with_profiles')
|
|
.select('user_id, full_name, email')
|
|
.eq('tenant_id', tenantId)
|
|
.eq('status', 'active');
|
|
const map = {};
|
|
for (const m of (data || [])) {
|
|
const full = m.full_name || m.email || '';
|
|
map[m.user_id] = full;
|
|
}
|
|
memberNameMap.value = map;
|
|
}
|
|
function assigneeLabel(userId) {
|
|
if (!userId) return '';
|
|
const full = memberNameMap.value[userId];
|
|
if (!full) return 'Atribuída';
|
|
const parts = full.trim().split(/\s+/);
|
|
if (parts.length === 1) return parts[0].slice(0, 14);
|
|
return `${parts[0]} ${parts[parts.length - 1][0]}.`;
|
|
}
|
|
|
|
// Abre drawer automaticamente se query ?patient=<uuid>
|
|
async function openThreadByPatientId(patientId) {
|
|
if (!patientId) return;
|
|
await drawerStore.openForPatient(patientId);
|
|
}
|
|
|
|
onMounted(async () => {
|
|
await load();
|
|
subscribeRealtime();
|
|
|
|
// Carrega definições de tags e tags por thread (em paralelo) + nomes de membros
|
|
await Promise.all([tagsApi.loadAllTags(), reloadThreadTags(), loadMemberNames()]);
|
|
|
|
// Se vier com query ?patient=<uuid>, abre o drawer direto
|
|
const patientFromQuery = route.query?.patient;
|
|
if (patientFromQuery) {
|
|
await openThreadByPatientId(String(patientFromQuery));
|
|
}
|
|
});
|
|
|
|
// Recarrega tags + threads quando o drawer fecha (tags/atribuição podem ter mudado)
|
|
watch(() => drawerStore.isOpen, (isOpen) => {
|
|
if (!isOpen) {
|
|
reloadThreadTags();
|
|
load();
|
|
}
|
|
});
|
|
|
|
// Recarrega tags quando a lista de threads muda (nova mensagem cria nova thread)
|
|
watch(() => filteredThreads.value.length, () => { reloadThreadTags(); });
|
|
|
|
// Reage a mudanças de rota (ex: clicou outro paciente)
|
|
watch(
|
|
() => route.query?.patient,
|
|
async (pid) => { if (pid) await openThreadByPatientId(String(pid)); }
|
|
);
|
|
|
|
watch(() => tenantStore.activeTenantId, async () => {
|
|
unsubscribeRealtime();
|
|
await load();
|
|
subscribeRealtime();
|
|
});
|
|
</script>
|
|
|
|
<template>
|
|
<div class="flex min-h-[calc(100vh-4.5rem)] bg-[var(--surface-ground,#f5f7fa)]">
|
|
<!-- Overlay mobile -->
|
|
<div v-if="asideOpen" class="fixed inset-0 bg-black/40 backdrop-blur-sm z-[39] xl:hidden" @click="asideOpen = false" />
|
|
|
|
<!-- ═══════════════════════════════════════
|
|
ASIDE — filtros rápidos + pacientes ativos
|
|
══════════════════════════════════════════ -->
|
|
<aside
|
|
class="aside-drawer flex flex-col overflow-y-auto shrink-0 bg-[var(--surface-card,#fff)] border-r border-[var(--surface-border,#e2e8f0)]"
|
|
:class="asideOpen ? 'translate-x-0 visible' : 'max-xl:-translate-x-full max-xl:invisible'"
|
|
:style="{ left: asideLeft }"
|
|
>
|
|
<!-- Cabeçalho -->
|
|
<div class="p-3.5 pb-2.5 border-b border-[var(--surface-border,#e2e8f0)]">
|
|
<div class="flex items-center gap-1.5 text-xs font-bold uppercase tracking-widest text-[var(--text-color-secondary,#64748b)] mb-2.5">
|
|
<i class="pi pi-filter" /><span>Filtros rápidos</span>
|
|
</div>
|
|
|
|
<div class="flex flex-col gap-1.5">
|
|
<button
|
|
class="flex items-center justify-between gap-2 px-3 py-2 rounded-md text-sm transition-colors border border-[var(--surface-border)] bg-transparent cursor-pointer hover:bg-[var(--surface-hover)]"
|
|
:class="{ 'ring-2 ring-blue-500/40': !filters.unreadOnly && !filters.channel }"
|
|
@click="filters.unreadOnly = false; filters.channel = null; filters.search = ''"
|
|
>
|
|
<span class="flex items-center gap-2"><i class="pi pi-list text-xs" /> Todas</span>
|
|
<Badge :value="summary.total" severity="secondary" />
|
|
</button>
|
|
|
|
<button
|
|
class="flex items-center justify-between gap-2 px-3 py-2 rounded-md text-sm transition-colors border border-[var(--surface-border)] bg-transparent cursor-pointer hover:bg-red-500/5"
|
|
:class="{ 'ring-2 ring-red-500/40 bg-red-500/5': filters.unreadOnly }"
|
|
@click="filters.unreadOnly = !filters.unreadOnly"
|
|
>
|
|
<span class="flex items-center gap-2"><i class="pi pi-bell text-xs text-red-500" /> Não lidas</span>
|
|
<Badge :value="summary.unreadTotal" :severity="summary.unreadTotal > 0 ? 'danger' : 'secondary'" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Atribuição -->
|
|
<div class="p-3.5 pb-2.5 border-b border-[var(--surface-border,#e2e8f0)]">
|
|
<div class="flex items-center gap-1.5 text-xs font-bold uppercase tracking-widest text-[var(--text-color-secondary,#64748b)] mb-2.5">
|
|
<i class="pi pi-user" /><span>Atribuição</span>
|
|
</div>
|
|
<div class="flex flex-col gap-1.5">
|
|
<button
|
|
class="flex items-center justify-between gap-2 px-3 py-1.5 rounded-md text-sm transition-colors border border-[var(--surface-border)] bg-transparent cursor-pointer hover:bg-[var(--surface-hover)]"
|
|
:class="{ 'ring-2 ring-blue-500/40 bg-blue-500/5': !filters.assigned }"
|
|
@click="filters.assigned = null"
|
|
>
|
|
<span class="flex items-center gap-2 text-xs"><i class="pi pi-list text-xs" /> Todas</span>
|
|
</button>
|
|
<button
|
|
class="flex items-center justify-between gap-2 px-3 py-1.5 rounded-md text-sm transition-colors border border-[var(--surface-border)] bg-transparent cursor-pointer hover:bg-[var(--surface-hover)]"
|
|
:class="{ 'ring-2 ring-blue-500/40 bg-blue-500/5': filters.assigned === 'me' }"
|
|
@click="filters.assigned = 'me'"
|
|
>
|
|
<span class="flex items-center gap-2 text-xs"><i class="pi pi-user text-xs text-blue-500" /> Minhas</span>
|
|
<Badge :value="mineCount" severity="secondary" />
|
|
</button>
|
|
<button
|
|
class="flex items-center justify-between gap-2 px-3 py-1.5 rounded-md text-sm transition-colors border border-[var(--surface-border)] bg-transparent cursor-pointer hover:bg-[var(--surface-hover)]"
|
|
:class="{ 'ring-2 ring-amber-500/40 bg-amber-500/5': filters.assigned === 'unassigned' }"
|
|
@click="filters.assigned = 'unassigned'"
|
|
>
|
|
<span class="flex items-center gap-2 text-xs"><i class="pi pi-user-minus text-xs text-amber-500" /> Não atribuídas</span>
|
|
<Badge :value="unassignedCount" :severity="unassignedCount > 0 ? 'warn' : 'secondary'" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Status Kanban (resumo) -->
|
|
<div class="p-3.5 pb-2.5 border-b border-[var(--surface-border,#e2e8f0)]">
|
|
<div class="flex items-center gap-1.5 text-xs font-bold uppercase tracking-widest text-[var(--text-color-secondary,#64748b)] mb-2.5">
|
|
<i class="pi pi-chart-bar" /><span>Por status</span>
|
|
</div>
|
|
|
|
<div class="flex flex-col gap-1.5">
|
|
<div
|
|
v-for="col in KANBAN_COLUMNS"
|
|
:key="col.key"
|
|
class="flex items-center justify-between gap-2 px-3 py-1.5 rounded-md text-sm border border-[var(--surface-border)]"
|
|
:class="{
|
|
'border-red-500/30 bg-red-500/5': col.color === 'red' && summary[col.key] > 0,
|
|
'border-amber-500/30 bg-amber-500/5': col.color === 'amber' && summary[col.key] > 0,
|
|
'border-blue-500/30 bg-blue-500/5': col.color === 'blue' && summary[col.key] > 0,
|
|
'border-emerald-500/30 bg-emerald-500/5': col.color === 'emerald' && summary[col.key] > 0
|
|
}"
|
|
>
|
|
<span class="flex items-center gap-2 text-xs">
|
|
<i :class="col.icon" />
|
|
{{ col.label }}
|
|
</span>
|
|
<Badge :value="summary[col.key] || 0" severity="secondary" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Canais -->
|
|
<div class="p-3.5 pb-2.5 border-b border-[var(--surface-border,#e2e8f0)]">
|
|
<div class="flex items-center gap-1.5 text-xs font-bold uppercase tracking-widest text-[var(--text-color-secondary,#64748b)] mb-2.5">
|
|
<i class="pi pi-send" /><span>Canais</span>
|
|
</div>
|
|
<div class="flex flex-col gap-1.5">
|
|
<button
|
|
v-for="opt in CHANNEL_OPTIONS"
|
|
:key="String(opt.value)"
|
|
class="flex items-center gap-2 px-3 py-1.5 rounded-md text-sm transition-colors border border-[var(--surface-border)] bg-transparent cursor-pointer hover:bg-[var(--surface-hover)]"
|
|
:class="{ 'ring-2 ring-blue-500/40 bg-blue-500/5': filters.channel === opt.value }"
|
|
@click="filters.channel = opt.value"
|
|
>
|
|
<i v-if="opt.value" :class="['pi text-xs', channelIcon(opt.value)]" />
|
|
<i v-else class="pi pi-list text-xs" />
|
|
{{ opt.label }}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Pacientes com atividade recente -->
|
|
<div v-if="recentPatients.length" class="p-3.5 pb-3 border-b border-[var(--surface-border,#e2e8f0)]">
|
|
<div class="flex items-center gap-1.5 text-xs font-bold uppercase tracking-widest text-[var(--text-color-secondary,#64748b)] mb-2.5">
|
|
<i class="pi pi-users" /><span>Recentes</span>
|
|
</div>
|
|
<div class="flex flex-col gap-1">
|
|
<button
|
|
v-for="t in recentPatients"
|
|
:key="t.thread_key"
|
|
class="flex items-center justify-between gap-2 px-2 py-1.5 rounded-md text-xs border-none bg-transparent cursor-pointer text-left hover:bg-[var(--surface-hover)] transition-colors"
|
|
@click="onCardClick(t)"
|
|
>
|
|
<span class="flex items-center gap-2 min-w-0 flex-1">
|
|
<i :class="['pi', channelIcon(t.channel), 'text-[0.65rem] opacity-60']" />
|
|
<span class="truncate text-[var(--text-color)]">{{ contactLabel(t) }}</span>
|
|
</span>
|
|
<span class="flex items-center gap-1 shrink-0">
|
|
<Badge v-if="t.unread_count > 0" :value="t.unread_count" severity="danger" />
|
|
<span class="text-[0.65rem] text-[var(--text-color-secondary)] opacity-75">{{ fmtRelative(t.last_message_at) }}</span>
|
|
</span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Alerta: não vinculados -->
|
|
<div v-if="unlinkedCount > 0" class="p-3.5">
|
|
<div class="flex items-start gap-2 p-2.5 rounded-md border border-amber-500/30 bg-amber-500/5 text-xs">
|
|
<i class="pi pi-exclamation-circle text-amber-600 mt-0.5" />
|
|
<div>
|
|
<div class="font-semibold text-amber-700">{{ unlinkedCount }} conversa(s) sem paciente vinculado</div>
|
|
<div class="opacity-75">Números de telefone que não batem com pacientes cadastrados.</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</aside>
|
|
|
|
<!-- ═══════════════════════════════════════
|
|
ÁREA PRINCIPAL
|
|
══════════════════════════════════════════ -->
|
|
<main class="flex-1 min-w-0 p-4 xl:p-[1.125rem_1.375rem] flex flex-col gap-4 overflow-y-auto" :style="{ marginLeft: isMobileLayout ? undefined : '272px' }">
|
|
<!-- Header -->
|
|
<section class="relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
|
<div class="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden="true">
|
|
<div class="absolute w-72 h-72 -top-16 -right-12 rounded-full blur-[70px] bg-blue-500/10" />
|
|
<div class="absolute w-80 h-80 top-2 -left-20 rounded-full blur-[70px] bg-emerald-400/[0.08]" />
|
|
</div>
|
|
|
|
<div class="relative z-1 flex items-center gap-3 flex-wrap">
|
|
<div class="flex items-center gap-3 flex-1 min-w-0">
|
|
<div class="grid place-items-center w-10 h-10 rounded-md shrink-0 bg-blue-500/10 text-blue-600">
|
|
<i class="pi pi-comments text-lg" />
|
|
</div>
|
|
<div class="min-w-0">
|
|
<div class="text-[1.1rem] font-bold tracking-tight text-[var(--text-color)]">Conversas</div>
|
|
<div class="text-[0.78rem] text-[var(--text-color-secondary)] mt-0.5">
|
|
CRM de WhatsApp · {{ summary.total }} conversa(s)
|
|
<span v-if="summary.unreadTotal > 0" class="ml-2 text-red-500 font-semibold">· {{ summary.unreadTotal }} não lida(s)</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center gap-2 shrink-0">
|
|
<IconField>
|
|
<InputIcon class="pi pi-search" />
|
|
<InputText v-model="filters.search" placeholder="Buscar paciente, número ou mensagem" class="w-64" maxlength="120" />
|
|
</IconField>
|
|
<Button icon="pi pi-refresh" severity="secondary" outlined class="h-9 w-9 rounded-full" :loading="loading" v-tooltip.bottom="'Recarregar'" @click="load" />
|
|
<Button icon="pi pi-cog" severity="secondary" outlined class="h-9 w-9 rounded-full" v-tooltip.bottom="'Configurações'" @click="goSettings" />
|
|
</div>
|
|
</div>
|
|
</section>
|
|
|
|
<!-- Toggle aside — mobile -->
|
|
<button
|
|
class="xl:hidden flex w-full items-center justify-between gap-3 px-4 py-3 bg-[var(--surface-card,#fff)] border border-[var(--surface-border,#e2e8f0)] rounded-md text-sm font-semibold text-[var(--text-color)] cursor-pointer"
|
|
@click="asideOpen = !asideOpen"
|
|
>
|
|
<div class="flex items-center gap-2">
|
|
<i class="pi pi-filter text-[var(--primary-color,#6366f1)]" />
|
|
<span>Filtros & recentes</span>
|
|
</div>
|
|
<i class="pi transition-transform duration-200" :class="asideOpen ? 'pi-chevron-up' : 'pi-chevron-down'" />
|
|
</button>
|
|
|
|
<!-- Kanban -->
|
|
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3">
|
|
<div
|
|
v-for="col in KANBAN_COLUMNS"
|
|
:key="col.key"
|
|
class="flex flex-col rounded-lg border bg-[var(--surface-card)] min-h-[400px]"
|
|
:class="{
|
|
'border-red-500/40': col.color === 'red',
|
|
'border-amber-500/40': col.color === 'amber',
|
|
'border-blue-500/40': col.color === 'blue',
|
|
'border-emerald-500/40': col.color === 'emerald'
|
|
}"
|
|
>
|
|
<!-- Column header -->
|
|
<div
|
|
class="flex items-center justify-between gap-2 px-3 py-2 border-b"
|
|
:class="{
|
|
'border-red-500/30 bg-red-500/5': col.color === 'red',
|
|
'border-amber-500/30 bg-amber-500/5': col.color === 'amber',
|
|
'border-blue-500/30 bg-blue-500/5': col.color === 'blue',
|
|
'border-emerald-500/30 bg-emerald-500/5': col.color === 'emerald'
|
|
}"
|
|
>
|
|
<div class="flex items-center gap-2 text-sm font-semibold">
|
|
<i :class="col.icon" />
|
|
{{ col.label }}
|
|
</div>
|
|
<Badge :value="byKanban[col.key].length" severity="secondary" />
|
|
</div>
|
|
|
|
<!-- Cards -->
|
|
<div class="flex flex-col gap-2 p-2 overflow-y-auto max-h-[calc(100vh-320px)]">
|
|
<div v-if="loading && !byKanban[col.key].length" class="text-xs text-[var(--text-color-secondary)] p-3 text-center">
|
|
<i class="pi pi-spin pi-spinner mr-2" />Carregando...
|
|
</div>
|
|
<div v-else-if="!byKanban[col.key].length" class="text-xs text-[var(--text-color-secondary)] p-6 text-center italic">
|
|
Nenhuma conversa.
|
|
</div>
|
|
|
|
<div
|
|
v-for="t in byKanban[col.key]"
|
|
:key="t.thread_key"
|
|
class="flex flex-col gap-1.5 p-3 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)] cursor-pointer hover:shadow-sm hover:border-blue-500/40 transition-all"
|
|
@click="onCardClick(t)"
|
|
>
|
|
<div class="flex items-center justify-between gap-2 min-w-0">
|
|
<div class="flex items-center gap-2 min-w-0 flex-1">
|
|
<i :class="['pi', channelIcon(t.channel), 'text-[var(--text-color-secondary)]']" />
|
|
<span class="text-sm font-semibold truncate text-[var(--text-color)]">{{ contactLabel(t) }}</span>
|
|
</div>
|
|
<Badge v-if="t.unread_count > 0" :value="t.unread_count" severity="danger" />
|
|
</div>
|
|
|
|
<div class="text-xs text-[var(--text-color-secondary)] truncate">
|
|
<i v-if="t.last_message_direction === 'outbound'" class="pi pi-arrow-right text-[0.6rem] mr-1 opacity-60" />
|
|
{{ truncate(t.last_message_body) }}
|
|
</div>
|
|
|
|
<!-- Tags pills -->
|
|
<div v-if="tagsForThread(t.thread_key).length" class="flex items-center gap-1 flex-wrap">
|
|
<span
|
|
v-for="tag in tagsForThread(t.thread_key)"
|
|
:key="tag.id"
|
|
class="inline-flex items-center gap-1 px-1.5 py-px rounded-full text-[0.62rem] font-semibold leading-tight"
|
|
:style="{
|
|
background: tag.color + '20',
|
|
color: tag.color,
|
|
border: `1px solid ${tag.color}40`
|
|
}"
|
|
>
|
|
<i v-if="tag.icon" :class="tag.icon" class="text-[0.55rem]" />
|
|
{{ tag.name }}
|
|
</span>
|
|
</div>
|
|
|
|
<div class="flex items-center justify-between gap-2 text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">
|
|
<span>{{ fmtRelative(t.last_message_at) }}</span>
|
|
<span
|
|
v-if="t.assigned_to"
|
|
class="inline-flex items-center gap-1 px-1.5 py-px rounded-full text-[0.62rem] font-semibold"
|
|
:class="t.assigned_to === currentUserId
|
|
? 'bg-blue-500/15 text-blue-600 border border-blue-500/30'
|
|
: 'bg-[var(--surface-hover)] text-[var(--text-color)] border border-[var(--surface-border)]'"
|
|
v-tooltip.top="t.assigned_to === currentUserId ? 'Atribuída a mim' : 'Atribuída a ' + (memberNameMap[t.assigned_to] || '')"
|
|
>
|
|
<i class="pi pi-user text-[0.55rem]" />
|
|
{{ t.assigned_to === currentUserId ? 'Eu' : assigneeLabel(t.assigned_to) }}
|
|
</span>
|
|
<span v-else-if="!t.patient_name" class="italic">não vinculado</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</main>
|
|
</div>
|
|
</template>
|
|
|
|
<style scoped>
|
|
.aside-drawer {
|
|
position: fixed;
|
|
top: calc(56px + var(--notice-banner-height, 0px));
|
|
left: 0;
|
|
height: calc(100dvh - 56px - var(--notice-banner-height, 0px));
|
|
width: min(300px, 85vw);
|
|
z-index: 40;
|
|
overflow-y: auto;
|
|
transition:
|
|
transform 0.25s cubic-bezier(0.4, 0, 0.2, 1),
|
|
visibility 0.25s;
|
|
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.15);
|
|
}
|
|
@media (min-width: 1280px) {
|
|
.aside-drawer {
|
|
position: fixed;
|
|
top: calc(56px + var(--notice-banner-height, 0px));
|
|
height: calc(100vh - 56px - var(--notice-banner-height, 0px));
|
|
width: 272px;
|
|
transform: none;
|
|
visibility: visible;
|
|
box-shadow: none;
|
|
z-index: auto;
|
|
}
|
|
}
|
|
</style>
|