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:
@@ -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>
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — pagesIndex.js
|
||||
|--------------------------------------------------------------------------
|
||||
| Índice curado das páginas navegáveis do app. Consumido pelo GlobalSearch
|
||||
| pra dar "ir pra tal página" como resultado da busca.
|
||||
|
|
||||
| Regras:
|
||||
| • `roles` vazio ou ausente → todos logados veem.
|
||||
| • `roles` com valores → apenas esses papéis veem.
|
||||
| • Roles reconhecidos: 'therapist', 'clinic_admin', 'tenant_admin',
|
||||
| 'supervisor', 'saas_admin', 'portal_user'.
|
||||
|
|
||||
| Não duplique aqui o que já está nas STATIC_ACTIONS do GlobalSearch
|
||||
| (Agenda, Pacientes, Financeiro, Documentos, Configurações, etc.).
|
||||
| O foco aqui são *sub-páginas* e telas menos frequentes, que o usuário
|
||||
| raramente lembra onde ficam.
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
// Helpers opcionais pra keywords mais ricas
|
||||
const kw = (...arr) => arr.flat().filter(Boolean);
|
||||
|
||||
export const PAGES = [
|
||||
// ═══════════════════ THERAPIST (/therapist/*) ═══════════════════
|
||||
{ id: 'p_t_dashboard', label: 'Dashboard', icon: 'pi pi-home', sublabel: 'Visão geral', path: '/therapist', roles: ['therapist'], keywords: kw('home','inicio','painel','dashboard') },
|
||||
{ id: 'p_t_conversas', label: 'Conversas', icon: 'pi pi-comments', sublabel: 'Mensagens com pacientes', path: '/therapist/conversas', roles: ['therapist'], keywords: kw('conversas','chat','mensagens','whatsapp') },
|
||||
{ id: 'p_t_agenda_rec', label: 'Recorrências da agenda', icon: 'pi pi-refresh', sublabel: 'Sessões recorrentes', path: '/therapist/agenda/recorrencias', roles: ['therapist'], keywords: kw('recorrencia','repeticao','semanal','sessao fixa') },
|
||||
{ id: 'p_t_agenda_comp', label: 'Compromissos determinados', icon: 'pi pi-bookmark', sublabel: 'Sessões fixas', path: '/therapist/agenda/compromissos', roles: ['therapist'], keywords: kw('compromissos','determinado','fixo') },
|
||||
{ id: 'p_t_plano', label: 'Meu plano', icon: 'pi pi-crown', sublabel: 'Assinatura e billing', path: '/therapist/meu-plano', roles: ['therapist'], keywords: kw('plano','assinatura','pagamento','mensalidade','billing') },
|
||||
{ id: 'p_t_upgrade', label: 'Upgrade de plano', icon: 'pi pi-arrow-up', sublabel: 'Mudar de plano', path: '/therapist/upgrade', roles: ['therapist'], keywords: kw('upgrade','trocar','mudar plano') },
|
||||
{ id: 'p_t_grupos', label: 'Grupos de pacientes', icon: 'pi pi-users', sublabel: 'Organizar pacientes em grupos', path: '/therapist/patients/grupos', roles: ['therapist'], keywords: kw('grupos','segmentacao','categorias') },
|
||||
{ id: 'p_t_tags', label: 'Tags de pacientes', icon: 'pi pi-tags', sublabel: 'Etiquetas', path: '/therapist/patients/tags', roles: ['therapist'], keywords: kw('tags','etiquetas','marcadores','labels') },
|
||||
{ id: 'p_t_medicos', label: 'Médicos referenciadores', icon: 'pi pi-user-edit', sublabel: 'Médicos que encaminham pacientes', path: '/therapist/patients/medicos', roles: ['therapist'], keywords: kw('medicos','encaminhadores','referenciadores','indicacao') },
|
||||
{ id: 'p_t_link_externo', label: 'Link de cadastro externo', icon: 'pi pi-link', sublabel: 'Link público pra pacientes', path: '/therapist/patients/link-externo', roles: ['therapist'], keywords: kw('link','externo','publico','cadastro paciente','convite') },
|
||||
{ id: 'p_t_cad_recebidos', label: 'Cadastros recebidos', icon: 'pi pi-inbox', sublabel: 'Pacientes aguardando aceite', path: '/therapist/patients/cadastro/recebidos', roles: ['therapist'], keywords: kw('recebidos','pendentes','aceitar','intake','novos') },
|
||||
{ id: 'p_t_doc_templates', label: 'Templates de documentos', icon: 'pi pi-file-edit', sublabel: 'Modelos reutilizáveis', path: '/therapist/documents/templates', roles: ['therapist'], keywords: kw('templates','modelos','contratos','documentos') },
|
||||
{ id: 'p_t_online_sched', label: 'Agendamento online', icon: 'pi pi-globe', sublabel: 'Página pública de agendamento', path: '/therapist/online-scheduling', roles: ['therapist'], keywords: kw('online','publico','agendar','landing','pagina','site') },
|
||||
{ id: 'p_t_ag_recebidos', label: 'Agendamentos recebidos', icon: 'pi pi-calendar-plus',sublabel: 'Solicitações da agenda pública', path: '/therapist/agendamentos-recebidos', roles: ['therapist'], keywords: kw('solicitacoes','recebidos','publico','pedidos') },
|
||||
{ id: 'p_t_fin_lanc', label: 'Lançamentos financeiros', icon: 'pi pi-list', sublabel: 'Entradas e saídas', path: '/therapist/financeiro/lancamentos', roles: ['therapist'], keywords: kw('lancamentos','entradas','saidas','fluxo de caixa','receitas','despesas') },
|
||||
{ id: 'p_t_relatorios', label: 'Relatórios', icon: 'pi pi-chart-bar', sublabel: 'Métricas e análises', path: '/therapist/relatorios', roles: ['therapist'], keywords: kw('relatorios','metricas','dashboards','analytics','indicadores') },
|
||||
{ id: 'p_t_security', label: 'Segurança da conta', icon: 'pi pi-shield', sublabel: 'Senha, 2FA, sessões', path: '/therapist/settings/security', roles: ['therapist'], keywords: kw('seguranca','senha','2fa','autenticacao','mfa') },
|
||||
{ id: 'p_t_notificacoes', label: 'Notificações', icon: 'pi pi-bell', sublabel: 'Histórico completo', path: '/therapist/notificacoes', roles: ['therapist'], keywords: kw('notificacoes','historico','alertas','avisos','inbox') },
|
||||
|
||||
// ═══════════════════ CLINIC ADMIN (/admin/*) ═══════════════════
|
||||
{ id: 'p_c_dashboard', label: 'Dashboard (clínica)', icon: 'pi pi-home', sublabel: 'Visão geral da clínica', path: '/admin', roles: ['clinic_admin','tenant_admin'], keywords: kw('dashboard','home','clinica') },
|
||||
{ id: 'p_c_features', label: 'Features da clínica', icon: 'pi pi-th-large', sublabel: 'Recursos habilitados', path: '/admin/clinic/features', roles: ['clinic_admin','tenant_admin'], keywords: kw('features','recursos','modulos','addons') },
|
||||
{ id: 'p_c_professionals', label: 'Profissionais', icon: 'pi pi-user', sublabel: 'Terapeutas da clínica', path: '/admin/clinic/professionals', roles: ['clinic_admin','tenant_admin'], keywords: kw('profissionais','terapeutas','equipe','time') },
|
||||
{ id: 'p_c_agenda_clinica', label: 'Agenda da clínica', icon: 'pi pi-calendar', sublabel: 'Agenda consolidada', path: '/admin/agenda/clinica', roles: ['clinic_admin','tenant_admin'], keywords: kw('agenda','clinica','global','consolidada') },
|
||||
{ id: 'p_c_plano', label: 'Plano da clínica', icon: 'pi pi-crown', sublabel: 'Assinatura', path: '/admin/meu-plano', roles: ['clinic_admin','tenant_admin'], keywords: kw('plano','assinatura','billing','clinica') },
|
||||
|
||||
// ═══════════════════ CONFIGURAÇÕES (/configuracoes/*) ═══════════════════
|
||||
{ id: 'p_cfg_agenda', label: 'Config: Agenda', icon: 'pi pi-calendar', sublabel: 'Horário de atendimento, durações', path: '/configuracoes/agenda', keywords: kw('config','agenda','horario','duracao','expediente') },
|
||||
{ id: 'p_cfg_bloqueios', label: 'Config: Bloqueios', icon: 'pi pi-ban', sublabel: 'Feriados e indisponibilidades', path: '/configuracoes/bloqueios', keywords: kw('bloqueios','feriados','ferias','indisponivel','folga') },
|
||||
{ id: 'p_cfg_agendador', label: 'Config: Agendador público', icon: 'pi pi-globe', sublabel: 'Configurações da página pública', path: '/configuracoes/agendador', keywords: kw('agendador','publico','online','booking','configurar') },
|
||||
{ id: 'p_cfg_pagamento', label: 'Config: Formas de pagamento', icon: 'pi pi-wallet', sublabel: 'Métodos aceitos', path: '/configuracoes/pagamento', keywords: kw('pagamento','metodos','pix','cartao','boleto','dinheiro') },
|
||||
{ id: 'p_cfg_descontos', label: 'Config: Descontos', icon: 'pi pi-percentage', sublabel: 'Regras de desconto', path: '/configuracoes/descontos', keywords: kw('descontos','promocao','reducao','abatimento') },
|
||||
{ id: 'p_cfg_excecoes', label: 'Config: Exceções financeiras', icon: 'pi pi-exclamation-triangle', sublabel: 'Casos especiais', path: '/configuracoes/excecoes-financeiras', keywords: kw('excecoes','financeiras','casos especiais','ajustes','manuais') },
|
||||
{ id: 'p_cfg_convenios', label: 'Config: Convênios', icon: 'pi pi-id-card', sublabel: 'Planos de saúde', path: '/configuracoes/convenios', keywords: kw('convenios','planos','saude','insurance','seguro') },
|
||||
{ id: 'p_cfg_email', label: 'Config: Templates de e-mail', icon: 'pi pi-envelope', sublabel: 'Mensagens automáticas', path: '/configuracoes/email-templates', keywords: kw('email','templates','modelos','notificacoes','mensagens') },
|
||||
{ id: 'p_cfg_empresa', label: 'Config: Empresa', icon: 'pi pi-building', sublabel: 'Dados da sua empresa', path: '/configuracoes/empresa', keywords: kw('empresa','dados','cnpj','razao social','fantasia','endereco') },
|
||||
{ id: 'p_cfg_conv_tags', label: 'Config: Tags de Conversa', icon: 'pi pi-tag', sublabel: 'Etiquetas pro CRM de conversas', path: '/configuracoes/conversas-tags', keywords: kw('tags','etiquetas','conversas','crm','whatsapp','kanban') },
|
||||
{ id: 'p_cfg_conv_autoreply', label: 'Config: Auto-reply WhatsApp', icon: 'pi pi-reply', sublabel: 'Resposta fora do horário', path: '/configuracoes/conversas-autoreply', keywords: kw('auto-reply','autoresposta','fora do horario','whatsapp','automatico','bot') },
|
||||
{ id: 'p_cfg_conv_optouts', label: 'Config: Opt-outs (LGPD)', icon: 'pi pi-ban', sublabel: 'Números bloqueados de envios auto', path: '/configuracoes/conversas-optouts', keywords: kw('opt-out','optout','lgpd','parar','bloqueio','cancelar','compliance','anpd') },
|
||||
{ id: 'p_cfg_lembretes', label: 'Config: Lembretes de Sessão', icon: 'pi pi-bell', sublabel: 'WhatsApp 24h e 2h antes', path: '/configuracoes/lembretes-sessao', keywords: kw('lembretes','sessao','whatsapp','automatico','reduzir faltas','avisar') },
|
||||
{ id: 'p_cfg_creditos_wa', label: 'Config: Créditos WhatsApp', icon: 'pi pi-credit-card', sublabel: 'Saldo, pacotes, extrato', path: '/configuracoes/creditos-whatsapp', keywords: kw('creditos','whatsapp','saldo','pacote','pagamento','pix','comprar','asaas') },
|
||||
{ id: 'p_cfg_canais', label: 'Config: Canais de notificação', icon: 'pi pi-bell', sublabel: 'WhatsApp, SMS, e-mail', path: '/configuracoes/canais', keywords: kw('canais','notificacoes','lembretes','whatsapp','sms','email') },
|
||||
{ id: 'p_cfg_whatsapp', label: 'Config: WhatsApp', icon: 'pi pi-whatsapp', sublabel: 'Canal WhatsApp', path: '/configuracoes/whatsapp', keywords: kw('whatsapp','wa','mensageria') },
|
||||
{ id: 'p_cfg_whatsapp_ofc', label: 'Config: WhatsApp Oficial AgenciaPSI', icon: 'pi pi-verified', sublabel: 'Número oficial gerenciado', path: '/configuracoes/whatsapp-oficial', keywords: kw('whatsapp','oficial','agenciapsi','business','api','meta','creditos') },
|
||||
{ id: 'p_cfg_whatsapp_pes', label: 'Config: WhatsApp Pessoal', icon: 'pi pi-mobile', sublabel: 'Conectar via QR code', path: '/configuracoes/whatsapp-pessoal', keywords: kw('whatsapp','pessoal','qr','gratis','evolution','baileys') },
|
||||
{ id: 'p_cfg_sms', label: 'Config: SMS', icon: 'pi pi-mobile', sublabel: 'Canal SMS', path: '/configuracoes/sms', keywords: kw('sms','torpedo','texto') },
|
||||
{ id: 'p_cfg_sms_canal', label: 'Config: Canal SMS', icon: 'pi pi-mobile', sublabel: 'Provedor e número', path: '/configuracoes/sms-canal', keywords: kw('sms','canal','provedor') },
|
||||
{ id: 'p_cfg_extras', label: 'Config: Recursos extras', icon: 'pi pi-plus-circle', sublabel: 'Addons e créditos', path: '/configuracoes/recursos-extras', keywords: kw('recursos','extras','addons','creditos','saldo') },
|
||||
{ id: 'p_cfg_auditoria', label: 'Config: Auditoria', icon: 'pi pi-history', sublabel: 'Log de ações', path: '/configuracoes/auditoria', keywords: kw('auditoria','log','historico','acoes') },
|
||||
|
||||
// ═══════════════════ CONTA (/account/*) ═══════════════════
|
||||
{ id: 'p_acc_profile', label: 'Meu perfil', icon: 'pi pi-user', sublabel: 'Dados pessoais', path: '/account/profile', keywords: kw('perfil','profile','meus dados','nome','foto','bio') },
|
||||
{ id: 'p_acc_negocio', label: 'Meu negócio', icon: 'pi pi-briefcase', sublabel: 'Dados profissionais', path: '/account/negocio', keywords: kw('negocio','profissional','crp','atuacao','especialidade') },
|
||||
{ id: 'p_acc_security', label: 'Segurança (conta)', icon: 'pi pi-shield', sublabel: 'Senha e autenticação', path: '/account/security', keywords: kw('seguranca','senha','password','2fa') }
|
||||
];
|
||||
|
||||
/**
|
||||
* Filtra páginas pelo papel ativo do usuário.
|
||||
* @param {string|null} role - 'therapist'|'clinic_admin'|'tenant_admin'|'supervisor'|'saas_admin'|'portal_user'
|
||||
* @returns {Array}
|
||||
*/
|
||||
export function filterPagesForRole(role) {
|
||||
if (!role) return PAGES.filter((p) => !p.roles || p.roles.length === 0);
|
||||
return PAGES.filter((p) => !p.roles || p.roles.length === 0 || p.roles.includes(role));
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza string pra busca fuzzy simples (remove acento, minúsculo, trim).
|
||||
*/
|
||||
function _norm(s) {
|
||||
return String(s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca fuzzy em páginas filtradas pelo papel.
|
||||
* @param {string} q
|
||||
* @param {string|null} role
|
||||
* @param {number} limit
|
||||
*/
|
||||
export function searchPages(q, role, limit = 6) {
|
||||
const query = _norm(q);
|
||||
const pool = filterPagesForRole(role);
|
||||
if (!query) return pool.slice(0, limit); // top N quando vazio
|
||||
return pool
|
||||
.filter((p) => {
|
||||
const hay = _norm(p.label + ' ' + p.sublabel + ' ' + (p.keywords || []).join(' '));
|
||||
return hay.includes(query);
|
||||
})
|
||||
.slice(0, limit);
|
||||
}
|
||||
Reference in New Issue
Block a user