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:
@@ -21,6 +21,16 @@ import { useLayout } from '@/layout/composables/layout';
|
||||
import Menu from 'primevue/menu';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useClinicKPIs } from '@/composables/useClinicKPIs';
|
||||
|
||||
// Fase 3a — KPIs financeiros/operacionais da clínica
|
||||
const kpis = useClinicKPIs();
|
||||
const brl = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' });
|
||||
function fmtBRL(v) { return brl.format(Number(v) || 0); }
|
||||
const revenueMax = computed(() => {
|
||||
const arr = kpis.revenueSeries.value || [];
|
||||
return arr.reduce((m, r) => Math.max(m, r.received || 0), 0) || 1;
|
||||
});
|
||||
|
||||
const dashHeroSentinelRef = ref(null);
|
||||
const heroStuck = ref(false);
|
||||
@@ -441,6 +451,9 @@ async function load() {
|
||||
_terapeutasBruto.value = membrosRes.data || [];
|
||||
_solicitacoesBruto.value = solRes.data || [];
|
||||
_cadastrosBruto.value = cadRes.data || [];
|
||||
|
||||
// KPIs financeiros em paralelo (não bloqueante)
|
||||
kpis.load();
|
||||
} catch (e) {
|
||||
console.error('[ClinicDashboard] load:', e);
|
||||
} finally {
|
||||
@@ -612,9 +625,9 @@ onMounted(async () => {
|
||||
<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' }">
|
||||
|
||||
<!-- Hero Header — Skeleton -->
|
||||
<section v-if="loading" class="relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-2.5">
|
||||
<div class="flex items-center gap-3 mb-3">
|
||||
<Skeleton width="40px" height="40px" border-radius="8px" />
|
||||
<section v-if="loading" class="relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-5 mx-3 md:mx-4 mt-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<Skeleton width="40px" height="40px" border-radius="6px" />
|
||||
<div class="flex flex-col gap-1.5 flex-1">
|
||||
<Skeleton width="12rem" height="14px" />
|
||||
<Skeleton width="18rem" height="11px" />
|
||||
@@ -622,32 +635,35 @@ onMounted(async () => {
|
||||
<Skeleton width="36px" height="36px" border-radius="999px" />
|
||||
<Skeleton width="36px" height="36px" border-radius="999px" />
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2.5">
|
||||
<div v-for="n in 4" :key="n" class="flex flex-col gap-1.5 px-4 py-2.5 rounded-md border border-[var(--surface-border)] flex-1 min-w-[90px]">
|
||||
<Skeleton width="2rem" height="20px" />
|
||||
<Skeleton width="4rem" height="10px" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Quick stats — Skeleton -->
|
||||
<section v-if="loading" class="grid grid-cols-2 md:grid-cols-4 gap-2.5 mx-3 md:mx-4 mb-4">
|
||||
<div v-for="n in 4" :key="n" class="flex flex-col gap-1.5 px-4 py-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<Skeleton width="2rem" height="20px" />
|
||||
<Skeleton width="4rem" height="10px" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Hero Header -->
|
||||
<section
|
||||
v-if="!loading"
|
||||
class="relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-2.5"
|
||||
class="sticky mx-3 md:mx-4 mt-4 mb-4 z-20 overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-5"
|
||||
:style="{ top: 'var(--layout-sticky-top, 56px)' }"
|
||||
:class="{ 'rounded-tl-none rounded-tr-none': heroStuck }"
|
||||
>
|
||||
<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-teal-500/10" />
|
||||
<div class="absolute w-80 h-80 top-2 -left-20 rounded-full blur-[70px] bg-indigo-400/[0.08]" />
|
||||
<div class="absolute rounded-full blur-[70px] w-72 h-72 -top-16 -right-20 bg-indigo-400/10" />
|
||||
<div class="absolute rounded-full blur-[70px] w-80 h-80 top-10 -left-24 bg-emerald-400/10" />
|
||||
<div class="absolute rounded-full blur-[70px] w-72 h-72 -bottom-20 right-24 bg-fuchsia-400/10" />
|
||||
</div>
|
||||
|
||||
<div class="relative z-1 flex items-center gap-4">
|
||||
<div class="relative z-10 flex items-center justify-between 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-teal-500/10 text-teal-600">
|
||||
<div class="grid place-items-center w-10 h-10 rounded-md shrink-0 bg-indigo-500/10 text-indigo-600 dark:text-indigo-400">
|
||||
<i class="pi pi-building text-lg" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-[1.1rem] font-bold tracking-tight text-[var(--text-color-secondary)]">{{ saudacao }} <span class="text-[var(--primary-color,#6366f1)]">👋</span></div>
|
||||
<div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)]">{{ saudacao }} <span class="text-[var(--primary-color,#6366f1)]">👋</span></div>
|
||||
<div class="text-[0.78rem] text-[var(--text-color-secondary)] mt-0.5">{{ resumoHoje }}</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -656,35 +672,150 @@ onMounted(async () => {
|
||||
<Button icon="pi pi-cog" severity="secondary" outlined class="h-9 w-9 rounded-full" title="Configurações" @click="$router.push('/configuracoes')" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Divider class="hidden xl:block my-2" />
|
||||
<!-- Quick stats (separados do hero) -->
|
||||
<section v-if="!loading" class="grid grid-cols-2 md:grid-cols-4 gap-2.5 mx-3 md:mx-4 mb-4">
|
||||
<div
|
||||
v-for="s in quickStats"
|
||||
:key="s.label"
|
||||
class="flex flex-col gap-0.5 px-4 py-3 rounded-md border transition-colors duration-150"
|
||||
:class="{
|
||||
'border-red-500/25 bg-red-500/5': s.cls === 'qs-urgente',
|
||||
'border-green-500/25 bg-green-500/5': s.cls === 'qs-ok',
|
||||
'border-[var(--surface-border)] bg-[var(--surface-card)]': !s.cls
|
||||
}"
|
||||
>
|
||||
<div
|
||||
class="text-[1.35rem] font-bold leading-none"
|
||||
:class="{
|
||||
'text-red-500': s.cls === 'qs-urgente',
|
||||
'text-green-500': s.cls === 'qs-ok',
|
||||
'text-[var(--text-color)]': !s.cls
|
||||
}"
|
||||
>
|
||||
{{ s.value }}
|
||||
</div>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Quick stats -->
|
||||
<div class="relative z-1 mt-2">
|
||||
<div class="flex flex-wrap gap-2.5">
|
||||
<div
|
||||
v-for="s in quickStats"
|
||||
:key="s.label"
|
||||
class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border flex-1 min-w-[90px] text-center xl:text-left transition-colors duration-150"
|
||||
:class="{
|
||||
'border-red-500/25 bg-red-500/5': s.cls === 'qs-urgente',
|
||||
'border-green-500/25 bg-green-500/5': s.cls === 'qs-ok',
|
||||
'border-[var(--surface-border)] bg-[var(--surface-ground)]': !s.cls
|
||||
}"
|
||||
>
|
||||
<div
|
||||
class="text-[1.35rem] font-bold leading-none"
|
||||
:class="{
|
||||
'text-red-500': s.cls === 'qs-urgente',
|
||||
'text-green-500': s.cls === 'qs-ok',
|
||||
'text-[var(--text-color)]': !s.cls
|
||||
}"
|
||||
>
|
||||
{{ s.value }}
|
||||
</div>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] opacity-75">{{ s.label }}</div>
|
||||
<!-- ═══════════════════════════════════════
|
||||
KPIs financeiros/operacionais (Fase 3a)
|
||||
══════════════════════════════════════════ -->
|
||||
<section v-if="!loading" class="flex flex-col gap-3">
|
||||
<!-- Cards KPI -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-2.5">
|
||||
<div class="flex flex-col gap-0.5 px-4 py-3 rounded-md border border-emerald-500/25 bg-emerald-500/5">
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] uppercase tracking-wide">Recebido no mês</div>
|
||||
<div class="text-[1.25rem] font-bold text-emerald-600 leading-tight">{{ fmtBRL(kpis.mrrCurrentCents.value) }}</div>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">
|
||||
Ticket médio: {{ fmtBRL(kpis.avgTicket.value) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex flex-col gap-0.5 px-4 py-3 rounded-md border"
|
||||
:class="kpis.overdueCount.value > 0 ? 'border-red-500/25 bg-red-500/5' : 'border-[var(--surface-border)] bg-[var(--surface-ground)]'"
|
||||
>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] uppercase tracking-wide">Inadimplência</div>
|
||||
<div class="text-[1.25rem] font-bold leading-tight" :class="kpis.overdueCount.value > 0 ? 'text-red-500' : 'text-[var(--text-color)]'">
|
||||
{{ fmtBRL(kpis.overdueCents.value) }}
|
||||
</div>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">
|
||||
{{ kpis.overdueCount.value }} recebível(is) em atraso
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-0.5 px-4 py-3 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] uppercase tracking-wide">A receber</div>
|
||||
<div class="text-[1.25rem] font-bold text-[var(--text-color)] leading-tight">{{ fmtBRL(kpis.pendingCents.value) }}</div>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">Pendentes no mês</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-0.5 px-4 py-3 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] uppercase tracking-wide">Pacientes</div>
|
||||
<div class="text-[1.25rem] font-bold text-[var(--text-color)] leading-tight">
|
||||
{{ kpis.activePatients.value }}
|
||||
<span class="text-[0.75rem] text-[var(--text-color-secondary)] font-normal">/ {{ kpis.totalPatients.value }}</span>
|
||||
</div>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">Ativos · {{ kpis.inactivePatients.value }} inativos</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-0.5 px-4 py-3 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] uppercase tracking-wide">Sessões no mês</div>
|
||||
<div class="text-[1.25rem] font-bold text-[var(--text-color)] leading-tight">{{ kpis.sessionsDone.value }}</div>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">
|
||||
de {{ kpis.sessionsScheduled.value }} agendadas
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex flex-col gap-0.5 px-4 py-3 rounded-md border"
|
||||
:class="(kpis.noShowRate.value ?? 0) > 15 ? 'border-amber-500/25 bg-amber-500/5' : 'border-[var(--surface-border)] bg-[var(--surface-ground)]'"
|
||||
>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] uppercase tracking-wide">Taxa de falta</div>
|
||||
<div class="text-[1.25rem] font-bold leading-tight" :class="(kpis.noShowRate.value ?? 0) > 15 ? 'text-amber-600' : 'text-[var(--text-color)]'">
|
||||
{{ kpis.noShowRate.value !== null ? kpis.noShowRate.value + '%' : '—' }}
|
||||
</div>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] opacity-75">
|
||||
{{ kpis.sessionsNoShow.value }} faltas · {{ kpis.sessionsCancelled.value }} cancel.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Grid: gráfico 6 meses + top pacientes -->
|
||||
<div class="grid grid-cols-1 xl:grid-cols-[1fr_320px] gap-3">
|
||||
<!-- Gráfico de receita (barras SVG simples) -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<div class="text-sm font-semibold text-[var(--text-color)]">Receita recebida · últimos 6 meses</div>
|
||||
<i class="pi pi-chart-bar text-[var(--text-color-secondary)]" />
|
||||
</div>
|
||||
<div v-if="!kpis.revenueSeries.value.length" class="text-xs text-[var(--text-color-secondary)] py-6 text-center">
|
||||
Sem dados no período.
|
||||
</div>
|
||||
<div v-else class="flex items-end gap-2 h-40">
|
||||
<div
|
||||
v-for="(m, i) in kpis.revenueSeries.value"
|
||||
:key="i"
|
||||
class="flex-1 flex flex-col items-center gap-1 min-w-0"
|
||||
>
|
||||
<div class="text-[0.65rem] text-[var(--text-color-secondary)] truncate w-full text-center">
|
||||
{{ fmtBRL(m.received) }}
|
||||
</div>
|
||||
<div
|
||||
class="w-full bg-emerald-500/70 rounded-t-md transition-all duration-300 min-h-[2px]"
|
||||
:style="{ height: `${Math.max(2, (m.received / revenueMax) * 130)}px` }"
|
||||
/>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)] uppercase">{{ m.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Top 5 pacientes -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<div class="text-sm font-semibold text-[var(--text-color)]">Top pacientes · 6 meses</div>
|
||||
<i class="pi pi-users text-[var(--text-color-secondary)]" />
|
||||
</div>
|
||||
<div v-if="!kpis.topPatients.value.length" class="text-xs text-[var(--text-color-secondary)] py-6 text-center">
|
||||
Sem dados.
|
||||
</div>
|
||||
<ol v-else class="flex flex-col gap-1.5">
|
||||
<li
|
||||
v-for="(p, i) in kpis.topPatients.value"
|
||||
:key="p.patient_id"
|
||||
class="flex items-center justify-between gap-2 text-xs"
|
||||
>
|
||||
<div class="flex items-center gap-2 min-w-0 flex-1">
|
||||
<span class="w-5 h-5 rounded-full bg-[var(--surface-ground)] grid place-items-center text-[0.65rem] font-bold shrink-0">{{ i + 1 }}</span>
|
||||
<span class="truncate text-[var(--text-color)]">{{ p.nome_completo }}</span>
|
||||
</div>
|
||||
<span class="font-semibold text-emerald-600 shrink-0">{{ fmtBRL(p.total) }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user