CRM WhatsApp Grupo 3 completo + Marco A/B (Asaas) + admin SaaS + refactors polimórficos
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>
This commit is contained in:
@@ -37,6 +37,7 @@ import PatientActionMenu from '@/components/patients/PatientActionMenu.vue';
|
||||
import PatientCadastroDialog from '@/components/ui/PatientCadastroDialog.vue';
|
||||
import PatientCreatePopover from '@/components/ui/PatientCreatePopover.vue';
|
||||
import PatientProntuario from '@/features/patients/prontuario/PatientProntuario.vue';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { logError } from '@/support/supportLogger';
|
||||
import { getSysGroupColor, getSystemGroupDefaultColor } from '@/utils/systemGroupColors.js';
|
||||
@@ -99,6 +100,7 @@ function fmtRecorrencia(r) {
|
||||
}
|
||||
|
||||
const router = useRouter();
|
||||
const conversationDrawerStore = useConversationDrawerStore();
|
||||
const route = useRoute();
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
@@ -132,7 +134,6 @@ const quickDialog = ref(false);
|
||||
const cadastroFullDialog = ref(false);
|
||||
const editPatientId = ref(null);
|
||||
const dialogSaved = ref(false);
|
||||
const searchMobileDlg = ref(false);
|
||||
const createPopoverRef = ref(null);
|
||||
|
||||
const prontuarioOpen = ref(false);
|
||||
@@ -346,6 +347,11 @@ function goEdit(row) {
|
||||
cadastroFullDialog.value = true;
|
||||
}
|
||||
|
||||
function goConversation(row) {
|
||||
if (!row?.id) return;
|
||||
conversationDrawerStore.openForPatient(String(row.id));
|
||||
}
|
||||
|
||||
// ── Filters & Sort ────────────────────────────────────────
|
||||
let searchTimer = null;
|
||||
function onFilterChangedDebounced() {
|
||||
@@ -739,7 +745,7 @@ function isRecent(row) {
|
||||
═══════════════════════════════════════ -->
|
||||
<div
|
||||
ref="headerEl"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
@@ -761,21 +767,8 @@ function isRecent(row) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Busca (desktop) — só o campo de busca, sem "Mais filtros" e sem "Colunas" -->
|
||||
<div class="hidden xl:flex flex-1 min-w-0 mx-2 items-center gap-2">
|
||||
<div class="flex-1 max-w-xs">
|
||||
<FloatLabel variant="on">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText id="patSearch" v-model="filters.search" class="w-full" variant="filled" @input="onFilterChangedDebounced" />
|
||||
</IconField>
|
||||
<label for="patSearch">Buscar por nome, e-mail ou telefone...</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações desktop -->
|
||||
<div class="hidden xl:flex items-center gap-1 shrink-0">
|
||||
<div class="hidden xl:flex items-center gap-1 shrink-0 ml-auto">
|
||||
<Button icon="pi pi-refresh" severity="secondary" outlined class="h-9 w-9 rounded-full" :loading="loading" @click="fetchAll" />
|
||||
<Button icon="pi pi-percentage" severity="secondary" outlined class="h-9 w-9 rounded-full" v-tooltip.top="'Descontos'" @click="router.push('/configuracoes/descontos')" />
|
||||
<Button label="Novo" icon="pi pi-user-plus" class="rounded-full" @click="(e) => createPopoverRef?.toggle(e)" />
|
||||
@@ -785,7 +778,6 @@ function isRecent(row) {
|
||||
|
||||
<!-- Mobile -->
|
||||
<div class="flex xl:hidden items-center gap-1 shrink-0 ml-auto">
|
||||
<Button icon="pi pi-search" severity="secondary" outlined class="h-9 w-9 rounded-full" @click="searchMobileDlg = true" />
|
||||
<Button icon="pi pi-user-plus" class="h-9 w-9 rounded-full" @click="(e) => createPopoverRef?.toggle(e)" />
|
||||
<Button label="Ações" icon="pi pi-ellipsis-v" severity="secondary" size="small" class="rounded-full" @click="(e) => patMobileMenuRef.toggle(e)" />
|
||||
<Menu ref="patMobileMenuRef" :model="patMobileMenuItems" :popup="true" />
|
||||
@@ -812,7 +804,7 @@ function isRecent(row) {
|
||||
<i class="pi pi-calendar-clock text-[var(--primary-color,#6366f1)]" />
|
||||
<span class="text-[1.1rem] font-bold leading-none text-[var(--primary-color,#6366f1)]">Agenda</span>
|
||||
</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Ver meus compromissos</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Ver meus compromissos</div>
|
||||
</div>
|
||||
|
||||
<!-- Descontos -->
|
||||
@@ -824,7 +816,7 @@ function isRecent(row) {
|
||||
<i class="pi pi-percentage text-amber-500" />
|
||||
<span class="text-[1.1rem] font-bold leading-none text-amber-500">Descontos</span>
|
||||
</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Ver descontos aplicados</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Ver descontos aplicados</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -842,7 +834,7 @@ function isRecent(row) {
|
||||
@click="setStatus('Todos')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-[var(--text-color)]">{{ kpis.total }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Total</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Total</div>
|
||||
</div>
|
||||
|
||||
<!-- Ativos -->
|
||||
@@ -852,7 +844,7 @@ function isRecent(row) {
|
||||
@click="setStatus('Ativo')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-green-500">{{ kpis.active }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Ativos</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Ativos</div>
|
||||
</div>
|
||||
|
||||
<!-- Inativos -->
|
||||
@@ -862,7 +854,7 @@ function isRecent(row) {
|
||||
@click="setStatus('Inativo')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-red-500">{{ kpis.inactive }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Inativos</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Inativos</div>
|
||||
</div>
|
||||
|
||||
<!-- Arquivados -->
|
||||
@@ -872,13 +864,13 @@ function isRecent(row) {
|
||||
@click="setStatus('Arquivado')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-slate-500">{{ kpis.archived }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Arquivados</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Arquivados</div>
|
||||
</div>
|
||||
|
||||
<!-- Último atendimento — não clicável -->
|
||||
<div class="flex flex-col gap-1 px-4 py-2.5 rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] min-w-[72px] flex-1">
|
||||
<div class="text-[1.1rem] font-bold leading-none text-[var(--text-color)]">{{ prettyDate(kpis.latestLastAttended) || '—' }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Último atend.</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Último atend.</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -895,19 +887,6 @@ function isRecent(row) {
|
||||
<Button label="Limpar" icon="pi pi-filter-slash" severity="danger" outlined size="small" class="!rounded-full" @click="clearAllFilters" />
|
||||
</div>
|
||||
|
||||
<!-- Dialog busca mobile -->
|
||||
<Dialog v-model:visible="searchMobileDlg" modal :draggable="false" pt:mask:class="backdrop-blur-xs" header="Buscar paciente" class="w-[94vw] max-w-sm">
|
||||
<div class="pt-1">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="filters.search" class="w-full" placeholder="Nome, telefone..." autofocus @input="onFilterChangedDebounced" />
|
||||
</IconField>
|
||||
</div>
|
||||
<template #footer>
|
||||
<Button label="Fechar" severity="secondary" outlined class="rounded-full" @click="searchMobileDlg = false" />
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<!-- TABS -->
|
||||
<Tabs value="pacientes" class="px-3 md:px-4 mb-5">
|
||||
<TabList>
|
||||
@@ -919,7 +898,7 @@ function isRecent(row) {
|
||||
<TabPanels>
|
||||
<TabPanel value="pacientes">
|
||||
<!-- Filters -->
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex flex-col gap-3 mb-4">
|
||||
<div class="flex flex-col md:flex-row md:items-end md:flex-wrap gap-3">
|
||||
<div class="w-full lg:flex-1">
|
||||
<FloatLabel variant="on">
|
||||
@@ -1098,6 +1077,7 @@ function isRecent(row) {
|
||||
<div class="flex gap-2 justify-end">
|
||||
<Button v-if="historySet.has(data.id)" :label="`Sessões × ${sessionCountMap.get(data.id) || 0}`" icon="pi pi-calendar" size="small" severity="info" outlined @click="abrirSessoes(data)" />
|
||||
<Button label="Prontuário" icon="pi pi-file" size="small" @click="openProntuario(data)" />
|
||||
<Button icon="pi pi-whatsapp" severity="success" outlined size="small" v-tooltip.top="'Conversar no WhatsApp'" @click="goConversation(data)" />
|
||||
<Button icon="pi pi-pencil" severity="secondary" outlined size="small" v-tooltip.top="'Editar'" @click="goEdit(data)" />
|
||||
<PatientActionMenu :patient="data" :hasHistory="historySet.has(data.id)" @updated="fetchAll" />
|
||||
</div>
|
||||
@@ -1164,6 +1144,7 @@ function isRecent(row) {
|
||||
<div class="mt-3 flex gap-2 justify-end flex-wrap">
|
||||
<Button v-if="historySet.has(pat.id)" :label="`Sessões × ${sessionCountMap.get(pat.id) || 0}`" icon="pi pi-calendar" size="small" severity="info" outlined @click="abrirSessoes(pat)" />
|
||||
<Button label="Prontuário" icon="pi pi-file" size="small" @click="openProntuario(pat)" />
|
||||
<Button icon="pi pi-whatsapp" severity="success" outlined size="small" v-tooltip.top="'Conversar'" @click="goConversation(pat)" />
|
||||
<Button icon="pi pi-pencil" severity="secondary" outlined size="small" @click="goEdit(pat)" />
|
||||
<PatientActionMenu :patient="pat" :hasHistory="historySet.has(pat.id)" @updated="fetchAll" />
|
||||
</div>
|
||||
|
||||
@@ -69,10 +69,16 @@ import { logError } from '@/support/supportLogger'
|
||||
import { digitsOnly, fmtCPF, fmtRG, fmtPhone, toISODate, generateCPF } from '@/utils/validators'
|
||||
import CadastroRapidoConvenio from '@/components/CadastroRapidoConvenio.vue'
|
||||
import CadastroRapidoMedico from '@/components/CadastroRapidoMedico.vue'
|
||||
import ContactPhonesEditor from '@/components/ui/ContactPhonesEditor.vue'
|
||||
import ContactEmailsEditor from '@/components/ui/ContactEmailsEditor.vue'
|
||||
|
||||
// V#9 — composables/repo da feature pacientes (extração da página gigante)
|
||||
import { useCep } from '@/features/patients/composables/useCep'
|
||||
import { usePatientSupportContacts } from '@/features/patients/composables/usePatientSupportContacts'
|
||||
// Fase 2b — LGPD export (Art. 18, II)
|
||||
import { useLgpdExport } from '@/composables/useLgpdExport'
|
||||
// Fase 5b-7 — drawer global de conversa
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore'
|
||||
import {
|
||||
listGroups as repoListGroups,
|
||||
listTags as repoListTags,
|
||||
@@ -148,6 +154,37 @@ const patientId = computed(() =>
|
||||
)
|
||||
const isEdit = computed(() => !!patientId.value)
|
||||
|
||||
// ─────────────────────────────────────────────────────────
|
||||
// LGPD export (Art. 18, II - portabilidade)
|
||||
// ─────────────────────────────────────────────────────────
|
||||
const lgpdDialog = ref(false)
|
||||
const { loading: lgpdExporting, exportJSON: lgpdExportJSON, exportPDF: lgpdExportPDF } = useLgpdExport()
|
||||
|
||||
async function onLgpdExport(format) {
|
||||
if (!isEdit.value || !patientId.value) return
|
||||
const name = form.nome_completo || 'paciente'
|
||||
try {
|
||||
if (format === 'json') {
|
||||
await lgpdExportJSON(patientId.value, name)
|
||||
} else {
|
||||
await lgpdExportPDF(patientId.value, name, '')
|
||||
}
|
||||
toast.add({ severity: 'success', summary: 'Export LGPD gerado', detail: `Arquivo ${format.toUpperCase()} baixado. O evento foi registrado na auditoria.`, life: 5000 })
|
||||
lgpdDialog.value = false
|
||||
} catch (err) {
|
||||
const msg = err?.message || String(err)
|
||||
toast.add({ severity: 'error', summary: 'Falha no export LGPD', detail: msg, life: 6000 })
|
||||
logError('PatientsCadastroPage.onLgpdExport', msg, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Fase 5b-7 — Abre drawer global (não navega)
|
||||
const conversationDrawer = useConversationDrawerStore()
|
||||
function goToConversation() {
|
||||
if (!isEdit.value || !patientId.value) return
|
||||
conversationDrawer.openForPatient(patientId.value)
|
||||
}
|
||||
|
||||
function getAreaKey () {
|
||||
const seg = String(route.path || '').split('/').filter(Boolean)[0] || 'admin'
|
||||
return seg === 'therapist' ? 'therapist' : 'admin'
|
||||
@@ -424,7 +461,9 @@ const ALLOWED = new Set([
|
||||
'nome_completo','nome_social','pronomes',
|
||||
'data_nascimento','genero','estado_civil','cpf','rg','naturalidade','etnia',
|
||||
'profissao','escolaridade',
|
||||
'telefone','email_principal','email_alternativo','telefone_alternativo',
|
||||
// telefone, telefone_alternativo, email_principal, email_alternativo agora são
|
||||
// gerenciados pelos editors polimórficos (contact_phones / contact_emails);
|
||||
// triggers sincronizam de volta pra essas colunas legadas.
|
||||
'canal_preferido','horario_contato',
|
||||
'cep','pais','cidade','estado','endereco','numero','bairro','complemento',
|
||||
'status','convenio','convenio_id','patient_scope',
|
||||
@@ -876,7 +915,8 @@ function fillRandomPatient () {
|
||||
toast.add({ severity:'info', summary:'Preenchido', detail:'Dados fictícios aplicados.', life:2500 })
|
||||
}
|
||||
|
||||
defineExpose({ fillRandomPatient, onSubmit, confirmDelete, saving, deleting, canSee, isEdit })
|
||||
function openLgpdDialog() { lgpdDialog.value = true }
|
||||
defineExpose({ fillRandomPatient, onSubmit, confirmDelete, saving, deleting, canSee, isEdit, openLgpdDialog, lgpdExporting, goToConversation })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -888,7 +928,7 @@ defineExpose({ fillRandomPatient, onSubmit, confirmDelete, saving, deleting, can
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<section
|
||||
v-if="!dialogMode"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-4 py-2.5 shadow-sm"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-4 py-2.5 shadow-sm"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
<!-- Blobs decorativos -->
|
||||
@@ -957,6 +997,8 @@ defineExpose({ fillRandomPatient, onSubmit, confirmDelete, saving, deleting, can
|
||||
@click="fillRandomPatient"
|
||||
/>
|
||||
<Button icon="pi pi-arrow-left" severity="secondary" outlined class="h-9 w-9 rounded-full" title="Voltar" @click="goBack" />
|
||||
<Button v-if="isEdit" icon="pi pi-whatsapp" severity="success" outlined class="h-9 w-9 rounded-full" title="Conversar no WhatsApp" @click="goToConversation" />
|
||||
<Button v-if="isEdit" icon="pi pi-shield" severity="secondary" outlined class="h-9 w-9 rounded-full" title="Exportar dados do paciente (LGPD)" @click="lgpdDialog = true" />
|
||||
<Button v-if="isEdit" icon="pi pi-trash" severity="danger" outlined class="h-9 w-9 rounded-full" :loading="deleting" @click="confirmDelete" />
|
||||
<Button label="Salvar" icon="pi pi-check" class="rounded-full" :loading="saving" @click="onSubmit" />
|
||||
</div>
|
||||
@@ -1255,42 +1297,32 @@ defineExpose({ fillRandomPatient, onSubmit, confirmDelete, saving, deleting, can
|
||||
<div class="flex-1 h-px" :class="pal.indigo.divLine"/>
|
||||
<span class="text-[0.6rem]" :class="pal.indigo.hint">Card "Contato" no detalhe</span>
|
||||
</div>
|
||||
<!-- Telefones (polimórfico — tipo/número/principal/vinculado) -->
|
||||
<div class="col-span-full">
|
||||
<div class="text-xs font-semibold text-[var(--text-color-secondary)] mb-1.5 flex items-center gap-1.5">
|
||||
<i class="pi pi-phone text-[var(--primary-color)]" />
|
||||
Telefones
|
||||
</div>
|
||||
<ContactPhonesEditor
|
||||
entity-type="patient"
|
||||
:entity-id="patientId || null"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Emails (polimórfico — tipo/endereço/principal) -->
|
||||
<div class="col-span-full">
|
||||
<div class="text-xs font-semibold text-[var(--text-color-secondary)] mb-1.5 flex items-center gap-1.5">
|
||||
<i class="pi pi-envelope text-[var(--primary-color)]" />
|
||||
Emails
|
||||
</div>
|
||||
<ContactEmailsEditor
|
||||
entity-type="patient"
|
||||
:entity-id="patientId || null"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 gap-3.5 xl:grid-cols-2">
|
||||
|
||||
<!-- Telefone -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<IconField><InputIcon class="pi pi-phone"/><InputMask id="f_tel" v-model="form.telefone" mask="(99) 99999-9999" :unmask="false" class="w-full" variant="filled"/></IconField>
|
||||
<label for="f_tel">Telefone / celular *</label>
|
||||
</FloatLabel>
|
||||
<div class="mt-1 text-[0.63rem]" :class="pal.indigo.hint">Exibido como "WhatsApp" clicável no perfil.</div>
|
||||
</div>
|
||||
|
||||
<!-- Telefone alternativo -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<IconField><InputIcon class="pi pi-phone"/><InputMask id="f_tel2" v-model="form.telefone_alternativo" mask="(99) 99999-9999" :unmask="false" class="w-full" variant="filled"/></IconField>
|
||||
<label for="f_tel2">Telefone alternativo</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<!-- E-mail principal -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<IconField><InputIcon class="pi pi-envelope"/><InputText id="f_email" v-model="form.email_principal" class="w-full" variant="filled"/></IconField>
|
||||
<label for="f_email">E-mail principal *</label>
|
||||
</FloatLabel>
|
||||
<div class="mt-1 text-[0.63rem]" :class="pal.indigo.hint">Link mailto: no card Contato.</div>
|
||||
</div>
|
||||
|
||||
<!-- E-mail alternativo -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<IconField><InputIcon class="pi pi-envelope"/><InputText id="f_email2" v-model="form.email_alternativo" class="w-full" variant="filled"/></IconField>
|
||||
<label for="f_email2">E-mail alternativo</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<!-- Canal preferido -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
@@ -1948,4 +1980,38 @@ defineExpose({ fillRandomPatient, onSubmit, confirmDelete, saving, deleting, can
|
||||
@selected="onMedicoSelected"
|
||||
@created="onMedicoSelected"
|
||||
/>
|
||||
|
||||
<!-- ══ Dialog: Export LGPD (Art. 18, II) ═════════════ -->
|
||||
<Dialog
|
||||
v-model:visible="lgpdDialog"
|
||||
modal
|
||||
:draggable="false"
|
||||
:closable="!lgpdExporting"
|
||||
:dismissableMask="!lgpdExporting"
|
||||
class="w-[34rem]"
|
||||
:breakpoints="{ '768px': '94vw' }"
|
||||
header="Exportar dados do paciente (LGPD)"
|
||||
>
|
||||
<div class="flex flex-col gap-3 text-sm">
|
||||
<Message severity="info" :closable="false" class="text-xs">
|
||||
Atendendo ao <strong>art. 18, II da LGPD</strong> — direito de portabilidade do titular.
|
||||
O evento será registrado na auditoria da clínica.
|
||||
</Message>
|
||||
|
||||
<p>Serão exportados: cadastro, contatos, histórico de status, eventos de agenda, registros financeiros, documentos (metadados), notificações enviadas e auditoria de alterações.</p>
|
||||
|
||||
<p class="text-xs text-surface-500">Escolha o formato:</p>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<Button label="JSON (completo)" icon="pi pi-code" severity="secondary" outlined :loading="lgpdExporting" @click="onLgpdExport('json')" />
|
||||
<Button label="PDF (relatório)" icon="pi pi-file-pdf" :loading="lgpdExporting" @click="onLgpdExport('pdf')" />
|
||||
</div>
|
||||
|
||||
<p class="text-[0.7rem] text-surface-400 mt-2">JSON é o formato canônico portável. PDF é legível e adequado pra entregar ao titular.</p>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Fechar" text :disabled="lgpdExporting" @click="lgpdDialog = false" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
@@ -148,7 +148,7 @@ onBeforeUnmount(() => {
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<section
|
||||
ref="headerEl"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
|
||||
@@ -486,7 +486,7 @@ onBeforeUnmount(() => {
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<section
|
||||
ref="headerEl"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
@@ -568,9 +568,9 @@ onBeforeUnmount(() => {
|
||||
<!-- ══════════════════════════════════════════════════════
|
||||
QUICK-STATS
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<div class="flex flex-wrap gap-2 px-3 md:px-4 mb-3">
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-3 md:px-4 mb-3">
|
||||
<template v-if="loading">
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="flex-1 min-w-[72px] rounded-md" />
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
@@ -579,7 +579,7 @@ onBeforeUnmount(() => {
|
||||
@click="toggleStatusFilter('')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-[var(--text-color)]">{{ totals.total }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Total</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Total</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -588,7 +588,7 @@ onBeforeUnmount(() => {
|
||||
@click="toggleStatusFilter('new')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-sky-500">{{ totals.nNew }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Novos</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Novos</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -597,7 +597,7 @@ onBeforeUnmount(() => {
|
||||
@click="toggleStatusFilter('converted')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-green-500">{{ totals.nConv }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Convertidos</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Convertidos</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -606,7 +606,7 @@ onBeforeUnmount(() => {
|
||||
@click="toggleStatusFilter('rejected')"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none text-red-500">{{ totals.nRej }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">Rejeitados</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">Rejeitados</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -421,7 +421,7 @@ function isRecent(row) {
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<section
|
||||
ref="headerEl"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
@@ -490,9 +490,9 @@ function isRecent(row) {
|
||||
<!-- ══════════════════════════════════════════════════════
|
||||
QUICK-STATS
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<div class="flex flex-wrap gap-2 px-3 md:px-4 mb-3">
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-3 md:px-4 mb-3">
|
||||
<template v-if="loading">
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="flex-1 min-w-[80px] rounded-md" />
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
@@ -513,7 +513,7 @@ function isRecent(row) {
|
||||
>
|
||||
{{ s.value }}
|
||||
</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">{{ s.label }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -32,6 +32,8 @@ import {
|
||||
} from '@/services/Medicos.service.js';
|
||||
|
||||
import PatientCadastroDialog from '@/components/ui/PatientCadastroDialog.vue';
|
||||
import ContactPhonesEditor from '@/components/ui/ContactPhonesEditor.vue';
|
||||
import ContactEmailsEditor from '@/components/ui/ContactEmailsEditor.vue';
|
||||
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
@@ -388,7 +390,7 @@ function isRecent(row) {
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<section
|
||||
ref="headerEl"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
@@ -457,9 +459,9 @@ function isRecent(row) {
|
||||
<!-- ══════════════════════════════════════════════════════
|
||||
QUICK-STATS
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<div class="flex flex-wrap gap-2 px-3 md:px-4 mb-3">
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-3 md:px-4 mb-3">
|
||||
<template v-if="loading">
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="flex-1 min-w-[80px] rounded-md" />
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
@@ -480,7 +482,7 @@ function isRecent(row) {
|
||||
>
|
||||
{{ s.value }}
|
||||
</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">{{ s.label }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -772,33 +774,32 @@ function isRecent(row) {
|
||||
<div class="flex-1 h-px bg-teal-200/50" />
|
||||
</div>
|
||||
|
||||
<!-- Telefone profissional -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<InputMask id="dlg_tel_prof" v-model="dlg.telefone_profissional" mask="(99) 99999-9999" :unmask="false" class="w-full" variant="filled" placeholder="(00) 00000-0000" :disabled="dlg.saving" />
|
||||
<label for="dlg_tel_prof">Telefone profissional</label>
|
||||
</FloatLabel>
|
||||
<div class="mt-1 text-[0.63rem] text-[var(--text-color-secondary)] opacity-60">Consultório ou clínica.</div>
|
||||
<!-- Telefones (polimórfico) -->
|
||||
<div v-if="dlg.id">
|
||||
<div class="text-[0.63rem] font-bold uppercase tracking-wider text-[var(--text-color-secondary)] opacity-70 mb-1">Telefones</div>
|
||||
<ContactPhonesEditor
|
||||
entity-type="medico"
|
||||
:entity-id="dlg.id"
|
||||
confirm-group="medicos-dlg"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="text-xs italic text-[var(--text-color-secondary)] py-2 px-3 rounded-md bg-[var(--surface-ground)] border border-dashed border-[var(--surface-border)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mr-1" />
|
||||
Salve o médico primeiro pra adicionar telefones.
|
||||
</div>
|
||||
|
||||
<!-- Telefone pessoal -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<InputMask id="dlg_tel_pes" v-model="dlg.telefone_pessoal" mask="(99) 99999-9999" :unmask="false" class="w-full" variant="filled" placeholder="(00) 00000-0000" :disabled="dlg.saving" />
|
||||
<label for="dlg_tel_pes">Telefone pessoal / WhatsApp</label>
|
||||
</FloatLabel>
|
||||
<div class="mt-1 text-[0.63rem] text-[var(--text-color-secondary)] opacity-60">Pessoal / WhatsApp.</div>
|
||||
<!-- Emails (polimórfico) -->
|
||||
<div v-if="dlg.id">
|
||||
<div class="text-[0.63rem] font-bold uppercase tracking-wider text-[var(--text-color-secondary)] opacity-70 mb-1">Emails</div>
|
||||
<ContactEmailsEditor
|
||||
entity-type="medico"
|
||||
:entity-id="dlg.id"
|
||||
confirm-group="medicos-dlg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Email -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<IconField>
|
||||
<InputIcon class="pi pi-envelope" />
|
||||
<InputText id="dlg_email" v-model="dlg.email" class="w-full" variant="filled" :disabled="dlg.saving" />
|
||||
</IconField>
|
||||
<label for="dlg_email">E-mail profissional</label>
|
||||
</FloatLabel>
|
||||
<div v-else class="text-xs italic text-[var(--text-color-secondary)] py-2 px-3 rounded-md bg-[var(--surface-ground)] border border-dashed border-[var(--surface-border)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mr-1" />
|
||||
Salve o médico primeiro pra adicionar emails.
|
||||
</div>
|
||||
|
||||
<!-- Divider localização -->
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Histórico de conversas na ficha do paciente (CRM 3.6)
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
import { formatDistanceToNow, format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
|
||||
const props = defineProps({
|
||||
patientId: { type: String, required: true },
|
||||
patientName: { type: String, default: '' }
|
||||
});
|
||||
|
||||
const drawerStore = useConversationDrawerStore();
|
||||
const loading = ref(false);
|
||||
const messages = ref([]);
|
||||
const mediaUrls = ref({});
|
||||
const filter = ref('all'); // all | inbound | outbound
|
||||
|
||||
const CHANNEL_ICON = {
|
||||
whatsapp: 'pi pi-whatsapp',
|
||||
sms: 'pi pi-comment',
|
||||
email: 'pi pi-envelope'
|
||||
};
|
||||
|
||||
async function load() {
|
||||
if (!props.patientId) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('conversation_messages')
|
||||
.select('id, channel, direction, from_number, to_number, body, media_url, media_mime, provider, kanban_status, received_at, created_at, responded_at, delivery_status')
|
||||
.eq('patient_id', props.patientId)
|
||||
.order('created_at', { ascending: true })
|
||||
.limit(500);
|
||||
if (error) throw error;
|
||||
messages.value = data || [];
|
||||
// Resolve signed URLs pra mídia do bucket
|
||||
for (const m of messages.value) {
|
||||
if (m.media_url && !/^https?:\/\//i.test(m.media_url)) {
|
||||
const { data: signed } = await supabase.storage.from('whatsapp-media').createSignedUrl(m.media_url, 3600);
|
||||
if (signed?.signedUrl) mediaUrls.value[m.id] = signed.signedUrl;
|
||||
} else if (m.media_url) {
|
||||
mediaUrls.value[m.id] = m.media_url;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[PatientConversationsTab] load:', e?.message);
|
||||
messages.value = [];
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const stats = computed(() => {
|
||||
const total = messages.value.length;
|
||||
const inbound = messages.value.filter((m) => m.direction === 'inbound').length;
|
||||
const outbound = messages.value.filter((m) => m.direction === 'outbound').length;
|
||||
const first = messages.value[0]?.created_at || null;
|
||||
const last = messages.value[messages.value.length - 1]?.created_at || null;
|
||||
const channels = new Set(messages.value.map((m) => m.channel));
|
||||
return { total, inbound, outbound, first, last, channels: [...channels] };
|
||||
});
|
||||
|
||||
const filtered = computed(() => {
|
||||
if (filter.value === 'all') return messages.value;
|
||||
return messages.value.filter((m) => m.direction === filter.value);
|
||||
});
|
||||
|
||||
function fmtTime(iso) {
|
||||
if (!iso) return '';
|
||||
try {
|
||||
return format(new Date(iso), "dd 'de' MMM HH:mm", { locale: ptBR });
|
||||
} catch { return ''; }
|
||||
}
|
||||
function fmtRelative(iso) {
|
||||
if (!iso) return '';
|
||||
try {
|
||||
return formatDistanceToNow(new Date(iso), { addSuffix: true, locale: ptBR });
|
||||
} catch { return ''; }
|
||||
}
|
||||
|
||||
function isImage(mime) { return !!mime && mime.startsWith('image/'); }
|
||||
function isAudio(mime) { return !!mime && mime.startsWith('audio/'); }
|
||||
function isVideo(mime) { return !!mime && mime.startsWith('video/'); }
|
||||
|
||||
function openInDrawer() {
|
||||
drawerStore.openForPatient(props.patientId);
|
||||
}
|
||||
|
||||
onMounted(() => { load(); });
|
||||
watch(() => props.patientId, () => { load(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-3 p-2">
|
||||
<!-- Header com stats + ação -->
|
||||
<div class="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div class="flex items-center gap-4 flex-wrap">
|
||||
<div class="flex flex-col">
|
||||
<span class="text-[0.7rem] uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Mensagens</span>
|
||||
<span class="text-xl font-bold leading-none">{{ stats.total }}</span>
|
||||
</div>
|
||||
<div class="h-8 w-px bg-[var(--surface-border)]" />
|
||||
<div class="flex flex-col">
|
||||
<span class="text-[0.7rem] uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Recebidas</span>
|
||||
<span class="text-base font-bold text-green-600 leading-none">{{ stats.inbound }}</span>
|
||||
</div>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-[0.7rem] uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Enviadas</span>
|
||||
<span class="text-base font-bold text-sky-600 leading-none">{{ stats.outbound }}</span>
|
||||
</div>
|
||||
<div v-if="stats.first" class="flex flex-col">
|
||||
<span class="text-[0.7rem] uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Primeira</span>
|
||||
<span class="text-xs leading-tight">{{ fmtTime(stats.first) }}</span>
|
||||
</div>
|
||||
<div v-if="stats.last" class="flex flex-col">
|
||||
<span class="text-[0.7rem] uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Última</span>
|
||||
<span class="text-xs leading-tight">{{ fmtRelative(stats.last) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<SelectButton
|
||||
v-model="filter"
|
||||
:options="[
|
||||
{ label: 'Todas', value: 'all' },
|
||||
{ label: 'Recebidas', value: 'inbound' },
|
||||
{ label: 'Enviadas', value: 'outbound' }
|
||||
]"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:allowEmpty="false"
|
||||
size="small"
|
||||
/>
|
||||
<Button
|
||||
label="Abrir no CRM"
|
||||
icon="pi pi-external-link"
|
||||
severity="primary"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:disabled="!messages.length"
|
||||
v-tooltip.top="'Abre o drawer de conversa com histórico completo + compose'"
|
||||
@click="openInDrawer"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div v-if="loading" class="flex flex-col gap-2">
|
||||
<Skeleton v-for="n in 5" :key="n" height="4rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<!-- Empty -->
|
||||
<div v-else-if="!messages.length" class="flex flex-col items-center justify-center gap-2 py-12 text-center text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-comments text-4xl opacity-30" />
|
||||
<div class="text-sm">Nenhuma conversa registrada com este paciente ainda.</div>
|
||||
<div class="text-xs opacity-70">
|
||||
Quando {{ props.patientName || 'o paciente' }} enviar uma mensagem pelo WhatsApp (ou você enviar uma), vai aparecer aqui.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Timeline -->
|
||||
<div v-else class="flex flex-col gap-1.5">
|
||||
<div
|
||||
v-for="m in filtered"
|
||||
:key="m.id"
|
||||
class="flex gap-2 items-start p-2 rounded-md border"
|
||||
:class="m.direction === 'inbound'
|
||||
? 'bg-[var(--surface-ground)] border-[var(--surface-border)]'
|
||||
: 'bg-emerald-500/5 border-emerald-500/20'"
|
||||
>
|
||||
<div class="w-7 h-7 rounded-full grid place-items-center shrink-0"
|
||||
:class="m.direction === 'inbound' ? 'bg-sky-500/15 text-sky-500' : 'bg-emerald-500/15 text-emerald-600'">
|
||||
<i :class="m.direction === 'inbound' ? 'pi pi-arrow-down' : 'pi pi-arrow-up'" class="text-[0.7rem]" />
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 text-[0.68rem] text-[var(--text-color-secondary)] mb-0.5 flex-wrap">
|
||||
<i :class="CHANNEL_ICON[m.channel] || 'pi pi-comment'" class="text-[0.65rem]" />
|
||||
<span class="font-semibold">{{ m.direction === 'inbound' ? 'Paciente' : 'Clínica' }}</span>
|
||||
<span class="opacity-50">·</span>
|
||||
<span>{{ fmtTime(m.created_at) }}</span>
|
||||
<span v-if="m.direction === 'outbound' && m.delivery_status === 'read'" class="text-sky-500" v-tooltip.top="'Lida'">
|
||||
<i class="pi pi-check-double text-[0.6rem]" />
|
||||
</span>
|
||||
<span v-else-if="m.direction === 'outbound' && m.delivery_status === 'delivered'" v-tooltip.top="'Entregue'">
|
||||
<i class="pi pi-check-double text-[0.6rem] opacity-60" />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Mídia -->
|
||||
<template v-if="m.media_url">
|
||||
<div v-if="!mediaUrls[m.id]" class="text-xs italic text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-spin pi-spinner mr-1" /> carregando mídia…
|
||||
</div>
|
||||
<template v-else>
|
||||
<img v-if="isImage(m.media_mime)" :src="mediaUrls[m.id]" class="max-w-[200px] rounded-md mt-0.5" />
|
||||
<audio v-else-if="isAudio(m.media_mime)" :src="mediaUrls[m.id]" controls preload="metadata" class="block max-w-full mt-0.5" />
|
||||
<video v-else-if="isVideo(m.media_mime)" :src="mediaUrls[m.id]" controls class="max-w-[260px] rounded-md mt-0.5" />
|
||||
<a v-else :href="mediaUrls[m.id]" target="_blank" rel="noopener" class="text-xs underline text-[var(--primary-color)]">
|
||||
<i class="pi pi-paperclip text-[0.6rem] mr-1" />Baixar anexo
|
||||
</a>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<div v-if="m.body" class="text-sm whitespace-pre-wrap break-words">{{ m.body }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer info -->
|
||||
<div v-if="messages.length && messages.length >= 500" class="text-[0.7rem] text-center italic text-[var(--text-color-secondary)] py-2">
|
||||
Exibindo as últimas 500 mensagens. Abra no CRM pra navegar na conversa completa.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -28,6 +28,7 @@ import { useToast } from 'primevue/usetoast';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
|
||||
import DocumentsListPage from '@/features/documents/DocumentsListPage.vue';
|
||||
import PatientConversationsTab from './PatientConversationsTab.vue';
|
||||
|
||||
// ── PROPS / EMITS ──────────────────────────────────────────────
|
||||
const props = defineProps({
|
||||
@@ -68,6 +69,7 @@ const mainTabs = [
|
||||
{ label: 'Agenda', icon: 'pi pi-calendar' },
|
||||
{ label: 'Financeiro', icon: 'pi pi-wallet' },
|
||||
{ label: 'Documentos', icon: 'pi pi-folder' },
|
||||
{ label: 'Conversas', icon: 'pi pi-whatsapp' },
|
||||
];
|
||||
|
||||
// ── ACCORDION DA ABA PERFIL ────────────────────────────────────
|
||||
@@ -1109,6 +1111,12 @@ Tags: ${(tags.value || []).map(t => t.name).filter(Boolean).join(', ') || '—'}
|
||||
embedded
|
||||
/>
|
||||
</div>
|
||||
<div v-show="activeTab === 5" class="p-2">
|
||||
<PatientConversationsTab
|
||||
:patient-id="patient?.id"
|
||||
:patient-name="patient?.nome_completo || patient?.nome_social || ''"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -15,8 +15,8 @@ import { assertTenantId, getUid } from '@/features/agenda/services/_tenantGuards
|
||||
const PATIENTS_SELECT_BASE = `
|
||||
id, tenant_id, owner_id, user_id, responsible_member_id, therapist_member_id,
|
||||
nome_completo, email_principal, email_alternativo, telefone, telefone_alternativo,
|
||||
cpf, rg, data_nascimento, naturalidade, nacionalidade, genero, estado_civil,
|
||||
profissao, escolaridade, status, status_pagamento,
|
||||
cpf, rg, data_nascimento, naturalidade, genero, estado_civil,
|
||||
profissao, escolaridade, status,
|
||||
cep, endereco, numero, bairro, complemento, cidade, estado, pais,
|
||||
nome_responsavel, telefone_responsavel, cpf_responsavel, observacao_responsavel,
|
||||
cobranca_no_responsavel,
|
||||
@@ -36,7 +36,7 @@ const PATIENTS_SELECT_BASE = `
|
||||
export async function listPatients({ tenantId, ownerId = null, includeInactive = true, limit = null } = {}) {
|
||||
assertTenantId(tenantId);
|
||||
|
||||
let q = supabase.from('patients').select(PATIENTS_SELECT_BASE).eq('tenant_id', tenantId).is('deleted_at', null);
|
||||
let q = supabase.from('patients').select(PATIENTS_SELECT_BASE).eq('tenant_id', tenantId);
|
||||
if (ownerId) q = q.eq('owner_id', ownerId);
|
||||
if (!includeInactive) q = q.neq('status', 'Inativo');
|
||||
if (limit) q = q.limit(limit);
|
||||
@@ -55,7 +55,6 @@ export async function getPatientById(id, { tenantId } = {}) {
|
||||
.select(PATIENTS_SELECT_BASE)
|
||||
.eq('id', id)
|
||||
.eq('tenant_id', tenantId)
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
@@ -90,7 +89,7 @@ export async function softDeletePatient(id, { tenantId } = {}) {
|
||||
assertTenantId(tenantId);
|
||||
const { error } = await supabase
|
||||
.from('patients')
|
||||
.update({ deleted_at: new Date().toISOString(), status: 'Arquivado' })
|
||||
.update({ status: 'Arquivado' })
|
||||
.eq('id', id)
|
||||
.eq('tenant_id', tenantId);
|
||||
if (error) throw error;
|
||||
|
||||
@@ -417,7 +417,7 @@ function isRecent(row) {
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<section
|
||||
ref="headerEl"
|
||||
class="sticky mx-3 md:mx-4 mb-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
>
|
||||
@@ -486,9 +486,9 @@ function isRecent(row) {
|
||||
<!-- ══════════════════════════════════════════════════════
|
||||
QUICK-STATS
|
||||
═══════════════════════════════════════════════════════ -->
|
||||
<div class="flex flex-wrap gap-2 px-3 md:px-4 mb-3">
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-3 md:px-4 mb-3">
|
||||
<template v-if="carregando">
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="flex-1 min-w-[80px] rounded-md" />
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
@@ -501,7 +501,7 @@ function isRecent(row) {
|
||||
}"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none" :class="s.cls === 'qs-ok' ? 'text-green-500' : 'text-[var(--text-color)]'">{{ s.value }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 whitespace-nowrap">{{ s.label }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user