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:
Leonardo
2026-04-23 07:05:24 -03:00
parent 037ba3721f
commit 2644e60bb6
191 changed files with 38629 additions and 3756 deletions
+677
View File
@@ -0,0 +1,677 @@
<!--
|--------------------------------------------------------------------------
| Agência PSI GlobalSearch (topbar)
|--------------------------------------------------------------------------
| Busca global com atalho Ctrl+K / +K. Consulta a RPC `search_global` e
| mostra resultados agrupados por entidade + ações rápidas client-side.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import IconField from 'primevue/iconfield';
import InputIcon from 'primevue/inputicon';
import InputText from 'primevue/inputtext';
import { supabase } from '@/lib/supabase/client';
import { useTenantStore } from '@/stores/tenantStore';
import { searchPages } from './pagesIndex';
const router = useRouter();
const tenantStore = useTenantStore();
// ────────────────────────────────────────────────────────────
// State
// ────────────────────────────────────────────────────────────
const rootEl = ref(null);
const inputEl = ref(null);
const query = ref('');
const results = ref({ patients: [], appointments: [], documents: [], services: [], intakes: [] });
const loading = ref(false);
const showPanel = ref(false);
const activeIndex = ref(-1);
// ────────────────────────────────────────────────────────────
// Ações estáticas (client-side, respondem na hora)
// ────────────────────────────────────────────────────────────
const STATIC_ACTIONS = [
{ id: 'act_new_patient', label: 'Novo paciente', icon: 'pi pi-user-plus', sublabel: 'Cadastrar paciente', to: '/therapist/patients/cadastro', keywords: ['novo','paciente','cadastrar','criar','add'] },
{ id: 'act_agenda', label: 'Agenda', icon: 'pi pi-calendar', sublabel: 'Ver calendário', to: '/therapist/agenda', keywords: ['agenda','calendario','sessoes','hoje'] },
{ id: 'act_patients', label: 'Pacientes', icon: 'pi pi-users', sublabel: 'Lista de pacientes', to: '/therapist/patients', keywords: ['pacientes','lista','todos'] },
{ id: 'act_financial', label: 'Financeiro', icon: 'pi pi-dollar', sublabel: 'Dashboard financeiro', to: '/therapist/financeiro', keywords: ['financeiro','cobrancas','pagamentos','dinheiro'] },
{ id: 'act_documents', label: 'Documentos', icon: 'pi pi-file', sublabel: 'Gestão de documentos', to: '/therapist/documents', keywords: ['documentos','arquivos','anexos'] },
{ id: 'act_services', label: 'Serviços', icon: 'pi pi-briefcase', sublabel: 'Precificação de serviços', to: '/configuracoes/precificacao', keywords: ['servicos','precificacao','precos','modalidade'] },
{ id: 'act_settings', label: 'Configurações', icon: 'pi pi-cog', sublabel: 'Preferências', to: '/configuracoes', keywords: ['configuracoes','settings','preferencias','ajustes'] }
];
function normalize(s) {
return String(s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim();
}
const filteredActions = computed(() => {
const q = normalize(query.value);
if (!q) return STATIC_ACTIONS.slice(0, 4); // quick defaults quando vazio
return STATIC_ACTIONS.filter((a) => {
const hay = normalize(a.label + ' ' + (a.keywords || []).join(' '));
return hay.includes(q);
}).slice(0, 4);
});
// Páginas do app (client-side, filtrado por papel ativo)
const filteredPages = computed(() => {
const q = query.value.trim();
const role = tenantStore?.activeRole || null;
if (!q) return []; // só mostra páginas quando o usuário busca algo
return searchPages(q, role, 5);
});
// ────────────────────────────────────────────────────────────
// Flat list pra navegação por teclado
// ────────────────────────────────────────────────────────────
const flatList = computed(() => {
const out = [];
filteredActions.value.forEach((a, i) => out.push({ group: 'actions', item: a, idx: i }));
results.value.patients.forEach((p, i) => out.push({ group: 'patients', item: p, idx: i }));
results.value.intakes.forEach((r, i) => out.push({ group: 'intakes', item: r, idx: i }));
results.value.appointments.forEach((a, i) => out.push({ group: 'appointments', item: a, idx: i }));
results.value.documents.forEach((d, i) => out.push({ group: 'documents', item: d, idx: i }));
results.value.services.forEach((s, i) => out.push({ group: 'services', item: s, idx: i }));
filteredPages.value.forEach((p, i) => out.push({ group: 'pages', item: p, idx: i }));
return out;
});
function findFlatIndex(group, idx) {
return flatList.value.findIndex((e) => e.group === group && e.idx === idx);
}
const hasAnyResult = computed(() =>
filteredActions.value.length
|| results.value.patients.length
|| results.value.intakes.length
|| results.value.appointments.length
|| results.value.documents.length
|| results.value.services.length
|| filteredPages.value.length
);
// ────────────────────────────────────────────────────────────
// Fetch (debounced, com controle de ordem)
// ────────────────────────────────────────────────────────────
let debounceT = null;
let searchSeq = 0;
function resetResults() {
results.value = { patients: [], appointments: [], documents: [], services: [], intakes: [] };
}
watch(query, (v) => {
if (debounceT) clearTimeout(debounceT);
const q = String(v || '').trim();
if (q.length < 2) {
resetResults();
activeIndex.value = flatList.value.length ? 0 : -1;
loading.value = false;
return;
}
loading.value = true;
const mySeq = ++searchSeq;
debounceT = setTimeout(async () => {
try {
const { data, error } = await supabase.rpc('search_global', { p_q: q, p_limit: 6 });
if (mySeq !== searchSeq) return; // resposta antiga, descarta
if (error) {
// eslint-disable-next-line no-console
console.error('[search_global] erro:', error);
resetResults();
} else {
results.value = {
patients: Array.isArray(data?.patients) ? data.patients : [],
appointments: Array.isArray(data?.appointments) ? data.appointments : [],
documents: Array.isArray(data?.documents) ? data.documents : [],
services: Array.isArray(data?.services) ? data.services : [],
intakes: Array.isArray(data?.intakes) ? data.intakes : []
};
}
} catch (e) {
if (mySeq !== searchSeq) return;
// eslint-disable-next-line no-console
console.error('[search_global] exceção:', e);
resetResults();
} finally {
if (mySeq === searchSeq) loading.value = false;
}
activeIndex.value = flatList.value.length ? 0 : -1;
}, 200);
});
// ────────────────────────────────────────────────────────────
// Teclado
// ────────────────────────────────────────────────────────────
function focusInput() {
nextTick(() => {
const inst = inputEl.value;
const el = inst?.$el?.tagName === 'INPUT' ? inst.$el : inst?.$el?.querySelector?.('input');
el?.focus?.();
try { el?.select?.(); } catch { /* ignore */ }
});
}
function onGlobalKeydown(e) {
const isK = e.key?.toLowerCase() === 'k';
const cmd = e.ctrlKey || e.metaKey;
if (cmd && isK) {
e.preventDefault();
e.stopPropagation();
showPanel.value = true;
focusInput();
return;
}
if (e.key === 'Escape' && showPanel.value) {
showPanel.value = false;
}
}
function onInputKeydown(e) {
const n = flatList.value.length;
if (e.key === 'ArrowDown') {
if (!n) return;
e.preventDefault();
activeIndex.value = (activeIndex.value + 1 + n) % n;
} else if (e.key === 'ArrowUp') {
if (!n) return;
e.preventDefault();
activeIndex.value = (activeIndex.value - 1 + n) % n;
} else if (e.key === 'Enter') {
const entry = flatList.value[activeIndex.value];
if (entry) {
e.preventDefault();
goTo(entry);
}
} else if (e.key === 'Escape') {
showPanel.value = false;
const inst = inputEl.value;
const el = inst?.$el?.tagName === 'INPUT' ? inst.$el : inst?.$el?.querySelector?.('input');
el?.blur?.();
}
}
async function goTo(entry) {
const target = entry?.item?.to || entry?.item?.deeplink || entry?.item?.path;
if (!target) return;
showPanel.value = false;
query.value = '';
resetResults();
activeIndex.value = -1;
await router.push(target);
}
function onFocus() {
showPanel.value = true;
if (flatList.value.length && activeIndex.value < 0) activeIndex.value = 0;
}
function onDocMouseDown(e) {
if (!showPanel.value) return;
const el = rootEl.value;
if (!el) return;
if (!el.contains(e.target)) showPanel.value = false;
}
onMounted(() => {
window.addEventListener('keydown', onGlobalKeydown, true);
document.addEventListener('mousedown', onDocMouseDown);
});
onBeforeUnmount(() => {
if (debounceT) clearTimeout(debounceT);
window.removeEventListener('keydown', onGlobalKeydown, true);
document.removeEventListener('mousedown', onDocMouseDown);
});
// ────────────────────────────────────────────────────────────
// UI helpers
// ────────────────────────────────────────────────────────────
const kbdIsMac = typeof navigator !== 'undefined' && /Mac|iP(ad|od|hone)/i.test(navigator.platform || '');
const kbdModifier = kbdIsMac ? '⌘' : 'Ctrl';
</script>
<template>
<div ref="rootEl" class="gs-root">
<div class="gs-field">
<IconField class="gs-field__wrap">
<InputIcon class="pi pi-search gs-field__icon" />
<InputText
ref="inputEl"
v-model="query"
type="search"
autocomplete="off"
spellcheck="false"
placeholder="Buscar pacientes, agenda, documentos…"
class="gs-field__input"
@focus="onFocus"
@keydown="onInputKeydown"
/>
</IconField>
<span class="gs-field__kbd" aria-hidden="true">
<kbd>{{ kbdModifier }}</kbd>
<kbd>K</kbd>
</span>
</div>
<div v-if="showPanel" class="gs-panel" role="listbox">
<div v-if="loading" class="gs-panel__state">
<i class="pi pi-spin pi-spinner" /> buscando
</div>
<div v-else-if="query.trim().length >= 2 && !hasAnyResult" class="gs-panel__state">
Nada encontrado pra <b>{{ query }}</b>.
</div>
<template v-else>
<!-- Ações -->
<div v-if="filteredActions.length" class="gs-group">
<div class="gs-group__title">{{ query.trim() ? 'Ações' : 'Atalhos' }}</div>
<button
v-for="(a, i) in filteredActions"
:key="a.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('actions', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('actions', i)"
@click="goTo({ group: 'actions', item: a, idx: i })"
>
<span class="gs-item__icon"><i :class="a.icon" /></span>
<span class="gs-item__main">
<span class="gs-item__label">{{ a.label }}</span>
<span class="gs-item__sub">{{ a.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Pacientes -->
<div v-if="results.patients.length" class="gs-group">
<div class="gs-group__title">Pacientes</div>
<button
v-for="(p, i) in results.patients"
:key="p.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('patients', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('patients', i)"
@click="goTo({ group: 'patients', item: p, idx: i })"
>
<span class="gs-item__avatar">
<img v-if="p.avatar_url" :src="p.avatar_url" :alt="p.label" />
<i v-else class="pi pi-user" />
</span>
<span class="gs-item__main">
<span class="gs-item__label">{{ p.label }}</span>
<span class="gs-item__sub">{{ p.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Cadastros pendentes (intakes) -->
<div v-if="results.intakes.length" class="gs-group">
<div class="gs-group__title">Cadastros pendentes</div>
<button
v-for="(r, i) in results.intakes"
:key="r.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('intakes', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('intakes', i)"
@click="goTo({ group: 'intakes', item: r, idx: i })"
>
<span class="gs-item__icon gs-item__icon--amber"><i class="pi pi-inbox" /></span>
<span class="gs-item__main">
<span class="gs-item__label">{{ r.label }}</span>
<span class="gs-item__sub">{{ r.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Agendamentos -->
<div v-if="results.appointments.length" class="gs-group">
<div class="gs-group__title">Agendamentos</div>
<button
v-for="(a, i) in results.appointments"
:key="a.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('appointments', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('appointments', i)"
@click="goTo({ group: 'appointments', item: a, idx: i })"
>
<span class="gs-item__icon gs-item__icon--blue"><i class="pi pi-calendar" /></span>
<span class="gs-item__main">
<span class="gs-item__label">{{ a.label }}</span>
<span class="gs-item__sub">{{ a.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Documentos -->
<div v-if="results.documents.length" class="gs-group">
<div class="gs-group__title">Documentos</div>
<button
v-for="(d, i) in results.documents"
:key="d.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('documents', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('documents', i)"
@click="goTo({ group: 'documents', item: d, idx: i })"
>
<span class="gs-item__icon gs-item__icon--purple"><i class="pi pi-file" /></span>
<span class="gs-item__main">
<span class="gs-item__label">{{ d.label }}</span>
<span class="gs-item__sub">{{ d.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Serviços -->
<div v-if="results.services.length" class="gs-group">
<div class="gs-group__title">Serviços</div>
<button
v-for="(s, i) in results.services"
:key="s.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('services', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('services', i)"
@click="goTo({ group: 'services', item: s, idx: i })"
>
<span class="gs-item__icon gs-item__icon--orange"><i class="pi pi-briefcase" /></span>
<span class="gs-item__main">
<span class="gs-item__label">{{ s.label }}</span>
<span class="gs-item__sub">{{ s.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Páginas do app -->
<div v-if="filteredPages.length" class="gs-group">
<div class="gs-group__title">Páginas</div>
<button
v-for="(p, i) in filteredPages"
:key="p.id"
type="button"
class="gs-item"
:class="{ 'is-active': findFlatIndex('pages', i) === activeIndex }"
@mouseenter="activeIndex = findFlatIndex('pages', i)"
@click="goTo({ group: 'pages', item: p, idx: i })"
>
<span class="gs-item__icon gs-item__icon--slate"><i :class="p.icon" /></span>
<span class="gs-item__main">
<span class="gs-item__label">{{ p.label }}</span>
<span class="gs-item__sub">{{ p.sublabel }}</span>
</span>
<i class="gs-item__go pi pi-arrow-right" />
</button>
</div>
<!-- Hint -->
<div v-if="!query.trim()" class="gs-panel__hint">
<i class="pi pi-info-circle" />
Digite ao menos 2 caracteres para buscar em pacientes, agenda, documentos e serviços.
</div>
</template>
</div>
</div>
</template>
<style scoped>
.gs-root {
position: relative;
width: 100%;
max-width: 420px;
min-width: 220px;
flex: 1 1 320px;
}
.gs-field { position: relative; display: flex; align-items: center; }
.gs-field__wrap { flex: 1; min-width: 0; }
.gs-field__icon { font-size: 0.82rem; opacity: 0.6; }
.gs-field__wrap :deep(.p-inputtext) {
width: 100%;
padding: 8px 56px 8px 34px;
font-size: 0.82rem;
height: 36px;
border-radius: 10px;
background: var(--p-content-background, var(--surface-card));
border: 1px solid var(--p-content-border-color, var(--surface-border));
transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
}
.gs-field__wrap :deep(.p-inputtext:hover) {
border-color: color-mix(in srgb, var(--primary-color) 40%, var(--surface-border));
}
.gs-field__wrap :deep(.p-inputtext:focus) {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 18%, transparent);
outline: none;
}
.gs-field__kbd {
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
display: inline-flex;
gap: 3px;
pointer-events: none;
}
.gs-field__kbd kbd {
font-family: inherit;
font-size: 0.6rem;
font-weight: 600;
padding: 2px 5px;
border-radius: 4px;
background: color-mix(in srgb, var(--text-color) 7%, transparent);
border: 1px solid color-mix(in srgb, var(--text-color) 10%, transparent);
color: var(--text-color-secondary);
line-height: 1;
min-width: 16px;
text-align: center;
}
.gs-panel {
position: absolute;
top: calc(100% + 6px);
left: 0;
right: 0;
z-index: 3100;
background: var(--surface-card);
border: 1px solid var(--surface-border);
border-radius: 12px;
box-shadow: 0 16px 40px -14px rgba(0, 0, 0, 0.3);
max-height: 70vh;
overflow-y: auto;
padding: 6px;
min-width: 360px;
}
.gs-panel__state {
padding: 18px;
text-align: center;
font-size: 0.82rem;
color: var(--text-color-secondary);
}
.gs-panel__hint {
padding: 10px 12px;
font-size: 0.72rem;
color: var(--text-color-secondary);
display: flex;
align-items: center;
gap: 7px;
opacity: 0.85;
}
.gs-group + .gs-group {
margin-top: 4px;
border-top: 1px solid var(--surface-border);
padding-top: 4px;
}
.gs-group__title {
padding: 8px 10px 4px;
font-size: 0.62rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.14em;
color: var(--text-color-secondary);
opacity: 0.7;
}
.gs-item {
display: flex;
align-items: center;
width: 100%;
gap: 10px;
padding: 8px 10px;
background: transparent;
border: 1px solid transparent;
border-radius: 8px;
cursor: pointer;
transition: background 0.12s, border-color 0.12s;
text-align: left;
font-family: inherit;
color: var(--text-color);
}
.gs-item.is-active {
background: color-mix(in srgb, var(--primary-color) 10%, transparent);
border-color: color-mix(in srgb, var(--primary-color) 24%, transparent);
}
.gs-item__icon,
.gs-item__avatar {
width: 28px;
height: 28px;
display: grid;
place-items: center;
border-radius: 8px;
flex-shrink: 0;
font-size: 0.82rem;
}
.gs-item__icon {
background: color-mix(in srgb, var(--primary-color) 12%, transparent);
color: var(--primary-color);
}
.gs-item__icon--blue {
background: color-mix(in srgb, #60a5fa 14%, transparent);
color: #60a5fa;
}
.gs-item__icon--purple {
background: color-mix(in srgb, #c084fc 14%, transparent);
color: #c084fc;
}
.gs-item__icon--orange {
background: color-mix(in srgb, #fb923c 14%, transparent);
color: #fb923c;
}
.gs-item__icon--amber {
background: color-mix(in srgb, #f59e0b 14%, transparent);
color: #f59e0b;
}
.gs-item__icon--slate {
background: color-mix(in srgb, var(--text-color) 8%, transparent);
color: var(--text-color-secondary);
}
.gs-item__avatar {
border-radius: 50%;
overflow: hidden;
background: color-mix(in srgb, var(--text-color) 6%, transparent);
color: var(--text-color-secondary);
}
.gs-item__avatar img { width: 100%; height: 100%; object-fit: cover; }
.gs-item__main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.gs-item__label {
font-size: 0.82rem;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.gs-item__sub {
font-size: 0.7rem;
color: var(--text-color-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.gs-item__go {
font-size: 0.7rem;
color: var(--text-color-secondary);
opacity: 0;
transition: opacity 0.12s;
}
.gs-item.is-active .gs-item__go { opacity: 1; color: var(--primary-color); }
/* Responsive */
@media (max-width: 820px) { .gs-root { max-width: 260px; flex-basis: 220px; } }
/* Compact: ≤ 640px → só ícone + kbd visíveis (input textual colapsado) */
@media (max-width: 640px) {
.gs-root {
flex: 0 0 auto;
width: auto;
min-width: 0;
max-width: none;
}
.gs-field__wrap :deep(.p-inputtext) {
width: 92px;
padding: 8px 42px 8px 30px;
color: transparent;
caret-color: transparent;
cursor: pointer;
}
.gs-field__wrap :deep(.p-inputtext::placeholder) {
color: transparent;
}
/* Mantém kbd visível em compact (dica visual do atalho) */
.gs-field__kbd {
display: inline-flex;
right: 6px;
pointer-events: none;
}
.gs-field__kbd kbd {
font-size: 0.55rem;
padding: 1px 4px;
}
/* Focado: expande como overlay sobre o topbar */
.gs-root:focus-within {
position: absolute;
top: 50%;
left: 0.5rem;
right: 0.5rem;
transform: translateY(-50%);
z-index: 110;
}
.gs-root:focus-within .gs-field__wrap :deep(.p-inputtext) {
width: 100%;
padding: 8px 56px 8px 34px;
color: inherit;
caret-color: auto;
cursor: text;
background: var(--p-content-background, var(--surface-card));
}
.gs-root:focus-within .gs-field__wrap :deep(.p-inputtext::placeholder) {
color: var(--text-color-secondary);
opacity: 0.6;
}
}
</style>