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:
@@ -86,6 +86,9 @@ const props = defineProps({
|
||||
|
||||
extraPayload: { type: Object, default: () => ({}) },
|
||||
|
||||
// Pré-preenchimento (usado ao converter número desconhecido em paciente, etc)
|
||||
initialData: { type: Object, default: () => ({}) },
|
||||
|
||||
closeOnCreated: { type: Boolean, default: true },
|
||||
resetOnOpen: { type: Boolean, default: true }
|
||||
});
|
||||
@@ -120,9 +123,10 @@ watch(
|
||||
);
|
||||
|
||||
function reset() {
|
||||
form.nome_completo = '';
|
||||
form.email_principal = '';
|
||||
form.telefone = '';
|
||||
const init = props.initialData || {};
|
||||
form.nome_completo = init.nome_completo ?? '';
|
||||
form.email_principal = init.email_principal ?? '';
|
||||
form.telefone = init.telefone ?? '';
|
||||
}
|
||||
|
||||
function close() {
|
||||
|
||||
@@ -20,7 +20,7 @@ import TabView from 'primevue/tabview';
|
||||
import TabPanel from 'primevue/tabpanel';
|
||||
import Dropdown from 'primevue/dropdown';
|
||||
import InputNumber from 'primevue/inputnumber';
|
||||
import InputSwitch from 'primevue/inputswitch';
|
||||
import ToggleSwitch from 'primevue/toggleswitch';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
|
||||
import { fetchSlotsRegras, upsertSlotRegra } from '@/services/agendaConfigService';
|
||||
@@ -142,7 +142,7 @@ onMounted(load);
|
||||
<TabPanel v-for="d in diasSemana" :key="d.value" :header="d.label">
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div class="col-span-12 flex items-center gap-3">
|
||||
<InputSwitch v-model="model[d.value].ativo" />
|
||||
<ToggleSwitch v-model="model[d.value].ativo" />
|
||||
<div>
|
||||
<div class="text-900 font-medium">Ativo</div>
|
||||
<div class="text-600 text-sm">Se desligado, o online não oferece horários nesse dia.</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,372 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — GlobalInboundNotifier
|
||||
|--------------------------------------------------------------------------
|
||||
| Componente global que escuta INSERTs de conversation_messages (direction
|
||||
| inbound) e mostra card flutuante no canto inferior direito, além de tocar
|
||||
| som opcional. Mesmo estando em outra tela, o usuário é avisado da nova
|
||||
| mensagem e pode clicar "Abrir" pra ir direto à conversa.
|
||||
|
|
||||
| Monta uma vez em AppLayout.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, watch, onMounted, onUnmounted } from 'vue';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
import { logEvent, logError } from '@/support/supportLogger';
|
||||
|
||||
const LOG_SRC = 'GlobalInboundNotifier';
|
||||
|
||||
const tenantStore = useTenantStore();
|
||||
const drawerStore = useConversationDrawerStore();
|
||||
|
||||
const activeNotifs = ref([]); // array de popups ativos
|
||||
let channel = null;
|
||||
|
||||
const SOUND_KEY = 'agenciapsi.inbound_sound_enabled';
|
||||
const soundEnabled = ref(true);
|
||||
|
||||
function loadSoundPref() {
|
||||
try {
|
||||
soundEnabled.value = localStorage.getItem(SOUND_KEY) !== 'false';
|
||||
} catch { soundEnabled.value = true; }
|
||||
}
|
||||
|
||||
function toggleSound() {
|
||||
soundEnabled.value = !soundEnabled.value;
|
||||
try {
|
||||
localStorage.setItem(SOUND_KEY, soundEnabled.value ? 'true' : 'false');
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function playBeep() {
|
||||
if (!soundEnabled.value) return;
|
||||
try {
|
||||
// WebAudio API — beep sintético de 2 tons curtos
|
||||
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
const now = ctx.currentTime;
|
||||
function tone(freq, start, dur, vol = 0.15) {
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.type = 'sine';
|
||||
osc.frequency.value = freq;
|
||||
gain.gain.setValueAtTime(0, now + start);
|
||||
gain.gain.linearRampToValueAtTime(vol, now + start + 0.01);
|
||||
gain.gain.exponentialRampToValueAtTime(0.001, now + start + dur);
|
||||
osc.connect(gain).connect(ctx.destination);
|
||||
osc.start(now + start);
|
||||
osc.stop(now + start + dur);
|
||||
}
|
||||
tone(880, 0, 0.12);
|
||||
tone(1320, 0.14, 0.12);
|
||||
// Fecha o context após som
|
||||
setTimeout(() => { try { ctx.close(); } catch {} }, 500);
|
||||
} catch {
|
||||
// se WebAudio falhar (sem interação prévia, etc), apenas ignora
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(s, n = 80) {
|
||||
if (!s) return '';
|
||||
const str = String(s).replace(/\s+/g, ' ').trim();
|
||||
return str.length > n ? str.slice(0, n - 1) + '…' : str;
|
||||
}
|
||||
|
||||
async function showNotif(msg) {
|
||||
logEvent(LOG_SRC, 'showNotif chamado', { id: msg.id, from: msg.from_number });
|
||||
// Se o drawer dessa thread já está aberto, não notifica (o user já vê)
|
||||
if (drawerStore.isOpen && drawerStore.messageBelongsToCurrentThread(msg)) {
|
||||
logEvent(LOG_SRC, 'suprimido: drawer aberto na thread', { id: msg.id });
|
||||
return;
|
||||
}
|
||||
// Se está na rota /conversas com aba visível, também não notifica (já tá no Kanban)
|
||||
const onConversasRoute = typeof window !== 'undefined' && String(window.location.pathname).includes('/conversas');
|
||||
if (onConversasRoute && document.visibilityState === 'visible') {
|
||||
logEvent(LOG_SRC, 'suprimido: na rota /conversas visível', { id: msg.id });
|
||||
return;
|
||||
}
|
||||
|
||||
let name = msg.from_number || 'Desconhecido';
|
||||
if (msg.patient_id) {
|
||||
const { data } = await supabase.from('patients').select('nome_completo').eq('id', msg.patient_id).maybeSingle();
|
||||
if (data?.nome_completo) name = data.nome_completo;
|
||||
}
|
||||
|
||||
const notif = {
|
||||
id: msg.id,
|
||||
name,
|
||||
body: msg.body || (msg.media_url ? '[mídia]' : ''),
|
||||
patient_id: msg.patient_id,
|
||||
from_number: msg.from_number,
|
||||
channel: msg.channel
|
||||
};
|
||||
|
||||
activeNotifs.value.push(notif);
|
||||
logEvent(LOG_SRC, 'popup push', { total: activeNotifs.value.length });
|
||||
playBeep();
|
||||
|
||||
setTimeout(() => dismiss(notif.id), 10000);
|
||||
}
|
||||
|
||||
function dismiss(id) {
|
||||
activeNotifs.value = activeNotifs.value.filter(n => n.id !== id);
|
||||
}
|
||||
|
||||
async function openNotif(notif) {
|
||||
dismiss(notif.id);
|
||||
if (notif.patient_id) {
|
||||
await drawerStore.openForPatient(notif.patient_id);
|
||||
} else {
|
||||
// thread anônima (número não vinculado a paciente)
|
||||
await drawerStore.openForThread({
|
||||
thread_key: `anon:${notif.from_number}`,
|
||||
tenant_id: tenantStore.activeTenantId,
|
||||
patient_id: null,
|
||||
patient_name: null,
|
||||
contact_number: notif.from_number,
|
||||
channel: notif.channel,
|
||||
message_count: 1,
|
||||
unread_count: 1,
|
||||
kanban_status: 'awaiting_us',
|
||||
last_message_at: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function channelIcon(ch) {
|
||||
const map = { whatsapp: 'pi-whatsapp', sms: 'pi-comment', email: 'pi-envelope' };
|
||||
return map[ch] || 'pi-bell';
|
||||
}
|
||||
|
||||
function subscribe() {
|
||||
const tenantId = tenantStore.activeTenantId;
|
||||
if (!tenantId) {
|
||||
logEvent(LOG_SRC, 'subscribe skipped — sem tenant');
|
||||
return;
|
||||
}
|
||||
if (channel) supabase.removeChannel(channel);
|
||||
logEvent(LOG_SRC, 'subscribing', { tenantId });
|
||||
channel = supabase
|
||||
.channel(`global_inbound_${tenantId}_${Date.now()}`)
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'INSERT',
|
||||
schema: 'public',
|
||||
table: 'conversation_messages',
|
||||
filter: `tenant_id=eq.${tenantId}`
|
||||
},
|
||||
(payload) => {
|
||||
const m = payload.new;
|
||||
logEvent(LOG_SRC, 'INSERT recebido', {
|
||||
id: m.id,
|
||||
direction: m.direction,
|
||||
from: m.from_number,
|
||||
preview: m.body?.slice(0, 40)
|
||||
});
|
||||
if (m.direction !== 'inbound') {
|
||||
logEvent(LOG_SRC, 'ignorando (não é inbound)', { direction: m.direction });
|
||||
return;
|
||||
}
|
||||
showNotif(m);
|
||||
}
|
||||
)
|
||||
.subscribe((status) => {
|
||||
logEvent(LOG_SRC, 'channel status', { status });
|
||||
});
|
||||
}
|
||||
|
||||
function unsubscribe() {
|
||||
if (channel) {
|
||||
supabase.removeChannel(channel);
|
||||
channel = null;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadSoundPref();
|
||||
subscribe();
|
||||
});
|
||||
|
||||
onUnmounted(() => unsubscribe());
|
||||
|
||||
watch(() => tenantStore.activeTenantId, () => subscribe());
|
||||
|
||||
// expõe toggle pra quem quiser usar (ex: na aside do CRM)
|
||||
defineExpose({ soundEnabled, toggleSound });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="global-notif-container" aria-live="polite">
|
||||
<TransitionGroup name="notif-slide" tag="div" class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="n in activeNotifs"
|
||||
:key="n.id"
|
||||
class="global-notif-card"
|
||||
role="alert"
|
||||
>
|
||||
<div class="notif-icon" :class="n.channel === 'whatsapp' ? 'text-emerald-600 bg-emerald-500/10' : 'text-blue-600 bg-blue-500/10'">
|
||||
<i :class="['pi', channelIcon(n.channel)]" />
|
||||
</div>
|
||||
<div class="notif-body">
|
||||
<div class="notif-header">
|
||||
<span class="notif-name">{{ n.name }}</span>
|
||||
<span class="notif-channel">{{ n.channel === 'whatsapp' ? 'WhatsApp' : n.channel }}</span>
|
||||
</div>
|
||||
<div class="notif-preview">{{ truncate(n.body, 80) }}</div>
|
||||
</div>
|
||||
<div class="notif-actions">
|
||||
<Button label="Abrir" size="small" severity="success" class="!text-xs" @click="openNotif(n)" />
|
||||
<button class="notif-close" title="Dispensar" @click="dismiss(n.id)">
|
||||
<i class="pi pi-times" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</TransitionGroup>
|
||||
|
||||
<!-- Toggle de som (mini, aparece se tem notificação ou pode ficar sempre visível) -->
|
||||
<button
|
||||
v-if="activeNotifs.length > 0"
|
||||
class="sound-toggle"
|
||||
:title="soundEnabled ? 'Som ativado (clique pra desativar)' : 'Som desativado'"
|
||||
@click="toggleSound"
|
||||
>
|
||||
<i :class="soundEnabled ? 'pi pi-volume-up' : 'pi pi-volume-off'" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.global-notif-container {
|
||||
position: fixed;
|
||||
bottom: 1.25rem;
|
||||
right: 1.25rem;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
width: min(380px, calc(100vw - 2rem));
|
||||
}
|
||||
|
||||
.global-notif-card {
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
background: var(--surface-card, #fff);
|
||||
border: 1px solid var(--surface-border, #e5e7eb);
|
||||
border-radius: 10px;
|
||||
padding: 0.75rem;
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15), 0 3px 10px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.notif-icon {
|
||||
width: 2.25rem;
|
||||
height: 2.25rem;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.notif-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.notif-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.notif-name {
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-color, #111827);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.notif-channel {
|
||||
font-size: 0.65rem;
|
||||
padding: 0 0.35rem;
|
||||
background: var(--surface-ground, #f3f4f6);
|
||||
color: var(--text-color-secondary, #6b7280);
|
||||
border-radius: 999px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.notif-preview {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-color-secondary, #6b7280);
|
||||
line-height: 1.3;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.notif-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.notif-close {
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-color-secondary, #6b7280);
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 0.75rem;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.notif-close:hover {
|
||||
background: var(--surface-ground, #f3f4f6);
|
||||
}
|
||||
|
||||
.sound-toggle {
|
||||
pointer-events: auto;
|
||||
margin-top: 0.5rem;
|
||||
align-self: flex-end;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--surface-border, #e5e7eb);
|
||||
background: var(--surface-card, #fff);
|
||||
color: var(--text-color-secondary, #6b7280);
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.sound-toggle:hover {
|
||||
background: var(--surface-ground, #f3f4f6);
|
||||
color: var(--text-color, #111827);
|
||||
}
|
||||
|
||||
/* Animação de entrada/saída */
|
||||
.notif-slide-enter-active {
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
.notif-slide-leave-active {
|
||||
transition: all 0.2s ease-in;
|
||||
}
|
||||
.notif-slide-enter-from {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
.notif-slide-leave-to {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -15,15 +15,50 @@
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useNotificationStore } from '@/stores/notificationStore';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import {
|
||||
useNotificationStore,
|
||||
requestBrowserNotificationPermission,
|
||||
setBrowserNotificationEnabled,
|
||||
getBrowserNotificationEnabled
|
||||
} from '@/stores/notificationStore';
|
||||
import NotificationItem from './NotificationItem.vue';
|
||||
|
||||
const store = useNotificationStore();
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
|
||||
const filter = ref('unread'); // 'unread' | 'all'
|
||||
const browserNotifOn = ref(false);
|
||||
|
||||
onMounted(() => {
|
||||
browserNotifOn.value = getBrowserNotificationEnabled();
|
||||
});
|
||||
|
||||
async function toggleBrowserNotif() {
|
||||
if (browserNotifOn.value) {
|
||||
// desliga
|
||||
setBrowserNotificationEnabled(false);
|
||||
browserNotifOn.value = false;
|
||||
toast.add({ severity: 'info', summary: 'Notificações do browser desligadas', life: 2500 });
|
||||
return;
|
||||
}
|
||||
const granted = await requestBrowserNotificationPermission();
|
||||
if (granted) {
|
||||
setBrowserNotificationEnabled(true);
|
||||
browserNotifOn.value = true;
|
||||
toast.add({ severity: 'success', summary: 'Notificações do browser ativadas', life: 2500 });
|
||||
} else {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Permissão negada',
|
||||
detail: 'Habilite nas configurações do browser se mudar de ideia.',
|
||||
life: 4000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const drawerOpen = computed({
|
||||
get: () => store.drawerOpen,
|
||||
@@ -57,6 +92,16 @@ function goToHistory() {
|
||||
<div class="notification-drawer__header-content">
|
||||
<span class="notification-drawer__title">Notificações</span>
|
||||
<Badge v-if="store.unreadCount > 0" :value="store.unreadCount > 99 ? '99+' : store.unreadCount" severity="danger" />
|
||||
<Button
|
||||
:icon="browserNotifOn ? 'pi pi-bell' : 'pi pi-bell-slash'"
|
||||
severity="secondary"
|
||||
text
|
||||
rounded
|
||||
size="small"
|
||||
class="ml-auto"
|
||||
:title="browserNotifOn ? 'Desativar notificações do browser' : 'Ativar notificações do browser'"
|
||||
@click="toggleBrowserNotif"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ import { useRouter } from 'vue-router';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { useNotificationStore } from '@/stores/notificationStore';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
|
||||
const props = defineProps({
|
||||
item: { type: Object, required: true }
|
||||
@@ -29,12 +31,15 @@ const emit = defineEmits(['read', 'archive']);
|
||||
|
||||
const router = useRouter();
|
||||
const store = useNotificationStore();
|
||||
const conversationDrawer = useConversationDrawerStore();
|
||||
const tenantStore = useTenantStore();
|
||||
|
||||
const typeMap = {
|
||||
new_scheduling: { icon: 'pi-inbox', border: 'border-red-500' },
|
||||
new_patient: { icon: 'pi-user-plus', border: 'border-sky-500' },
|
||||
recurrence_alert: { icon: 'pi-refresh', border: 'border-amber-500' },
|
||||
session_status: { icon: 'pi-calendar-times', border: 'border-orange-500' }
|
||||
session_status: { icon: 'pi-calendar-times', border: 'border-orange-500' },
|
||||
inbound_message: { icon: 'pi-whatsapp', border: 'border-emerald-500' }
|
||||
};
|
||||
|
||||
const meta = computed(() => typeMap[props.item.type] || { icon: 'pi-bell', border: 'border-gray-300' });
|
||||
@@ -45,6 +50,31 @@ const timeAgo = computed(() => formatDistanceToNow(new Date(props.item.created_a
|
||||
const initials = computed(() => props.item.payload?.avatar_initials || '?');
|
||||
|
||||
function handleRowClick() {
|
||||
// Inbound message → abre drawer global (evita 403 em rota admin/therapist)
|
||||
if (props.item.type === 'inbound_message') {
|
||||
const payload = props.item.payload || {};
|
||||
if (payload.patient_id) {
|
||||
conversationDrawer.openForPatient(payload.patient_id);
|
||||
} else if (payload.from_number) {
|
||||
conversationDrawer.openForThread({
|
||||
thread_key: `anon:${payload.from_number}`,
|
||||
tenant_id: tenantStore.activeTenantId,
|
||||
patient_id: null,
|
||||
patient_name: null,
|
||||
contact_number: payload.from_number,
|
||||
channel: payload.channel || 'whatsapp',
|
||||
message_count: 1,
|
||||
unread_count: 1,
|
||||
kanban_status: 'awaiting_us',
|
||||
last_message_at: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
store.drawerOpen = false;
|
||||
emit('read', props.item.id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Outros tipos: segue o deeplink normal
|
||||
const deeplink = props.item.payload?.deeplink;
|
||||
if (deeplink) {
|
||||
router.push(deeplink);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Editor de emails polimórfico
|
||||
|--------------------------------------------------------------------------
|
||||
| Uso:
|
||||
| <ContactEmailsEditor entity-type="patient" :entity-id="patient.id" />
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, onMounted, watch, reactive } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { useContactEmails } from '@/composables/useContactEmails';
|
||||
|
||||
const props = defineProps({
|
||||
entityType: { type: String, required: true },
|
||||
entityId: { type: String, required: false, default: null },
|
||||
readonly: { type: Boolean, default: false },
|
||||
confirmGroup: { type: String, default: '' }
|
||||
});
|
||||
|
||||
const emit = defineEmits(['change']);
|
||||
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const api = useContactEmails();
|
||||
|
||||
const showAddForm = ref(false);
|
||||
const newForm = reactive({ contact_email_type_id: null, email: '', notes: '' });
|
||||
|
||||
function openAddForm() {
|
||||
const defaultType = api.typeBySlug('principal') || api.types.value[0];
|
||||
newForm.contact_email_type_id = defaultType?.id || null;
|
||||
newForm.email = '';
|
||||
newForm.notes = '';
|
||||
showAddForm.value = true;
|
||||
}
|
||||
|
||||
function cancelAddForm() {
|
||||
showAddForm.value = false;
|
||||
}
|
||||
|
||||
async function submitAddForm() {
|
||||
if (!newForm.contact_email_type_id || !newForm.email.trim()) return;
|
||||
const res = await api.addEmail(props.entityType, props.entityId, {
|
||||
contact_email_type_id: newForm.contact_email_type_id,
|
||||
email: newForm.email,
|
||||
is_primary: api.emails.value.length === 0,
|
||||
notes: newForm.notes || null
|
||||
});
|
||||
if (res.ok) {
|
||||
showAddForm.value = false;
|
||||
toast.add({ severity: 'success', summary: 'Email adicionado', life: 1800 });
|
||||
emit('change', api.emails.value);
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
const editingId = ref(null);
|
||||
const editForm = reactive({ contact_email_type_id: null, email: '', notes: '' });
|
||||
|
||||
function startEdit(email) {
|
||||
editingId.value = email.id;
|
||||
editForm.contact_email_type_id = email.contact_email_type_id;
|
||||
editForm.email = email.email;
|
||||
editForm.notes = email.notes || '';
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
editingId.value = null;
|
||||
}
|
||||
|
||||
async function saveEdit(email) {
|
||||
const res = await api.updateEmail(props.entityType, props.entityId, email.id, {
|
||||
contact_email_type_id: editForm.contact_email_type_id,
|
||||
email: editForm.email,
|
||||
notes: editForm.notes.trim() || null
|
||||
});
|
||||
if (res.ok) {
|
||||
editingId.value = null;
|
||||
toast.add({ severity: 'success', summary: 'Email atualizado', life: 1800 });
|
||||
emit('change', api.emails.value);
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function setPrimary(email) {
|
||||
if (email.is_primary) return;
|
||||
const res = await api.setPrimary(props.entityType, props.entityId, email.id);
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Email principal atualizado', life: 1800 });
|
||||
emit('change', api.emails.value);
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRemove(email) {
|
||||
const typeName = api.typeById(email.contact_email_type_id)?.name || 'email';
|
||||
confirm.require({
|
||||
group: props.confirmGroup || undefined,
|
||||
message: `Remover este ${typeName}${email.is_primary ? ' (principal)' : ''}?`,
|
||||
header: 'Remover email',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
acceptLabel: 'Remover',
|
||||
rejectLabel: 'Cancelar',
|
||||
accept: async () => {
|
||||
const res = await api.removeEmail(props.entityType, props.entityId, email.id);
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Removido', life: 1800 });
|
||||
emit('change', api.emails.value);
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await api.loadTypes();
|
||||
if (props.entityId) await api.loadEmails(props.entityType, props.entityId);
|
||||
});
|
||||
|
||||
watch(() => props.entityId, async (v) => {
|
||||
if (v) await api.loadEmails(props.entityType, v);
|
||||
else api.emails.value = [];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] flex items-start gap-1.5 px-1">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5 shrink-0" />
|
||||
<span>
|
||||
Marque um email como <strong>principal</strong> — ele é usado pra
|
||||
<strong>envio de faturas, templates e notificações por email</strong>.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="api.loading.value" class="text-xs text-center py-3 text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-spin pi-spinner mr-1" /> Carregando…
|
||||
</div>
|
||||
|
||||
<div v-else-if="!api.emails.value.length && !showAddForm" class="text-xs text-center py-4 italic text-[var(--text-color-secondary)] border border-dashed border-[var(--surface-border)] rounded-md">
|
||||
Nenhum email cadastrado.
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-col gap-1.5">
|
||||
<div
|
||||
v-for="email in api.emails.value"
|
||||
:key="email.id"
|
||||
class="flex items-center gap-2 p-2 rounded-md border border-[var(--surface-border)]"
|
||||
:class="email.is_primary ? 'bg-[var(--primary-color)]/5 border-[var(--primary-color)]/30' : 'bg-[var(--surface-card)]'"
|
||||
>
|
||||
<template v-if="editingId !== email.id">
|
||||
<div class="w-8 h-8 rounded grid place-items-center shrink-0 bg-[var(--surface-ground)]">
|
||||
<i :class="api.typeById(email.contact_email_type_id)?.icon || 'pi pi-envelope'" class="text-sm text-[var(--text-color-secondary)]" />
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-w-0 flex flex-col gap-0.5">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<span class="text-xs font-semibold text-[var(--text-color-secondary)]">{{ api.typeById(email.contact_email_type_id)?.name || 'Email' }}</span>
|
||||
<span v-if="email.is_primary" class="inline-flex items-center px-1.5 py-px rounded-full text-[0.6rem] font-bold uppercase tracking-wide bg-[var(--primary-color)] text-white">Principal</span>
|
||||
</div>
|
||||
<a :href="`mailto:${email.email}`" class="text-sm font-mono truncate text-[var(--primary-color)] hover:underline" @click.stop>{{ email.email }}</a>
|
||||
<span v-if="email.notes" class="text-[0.7rem] italic text-[var(--text-color-secondary)]">{{ email.notes }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!readonly" class="flex items-center gap-0.5 shrink-0">
|
||||
<Button v-if="!email.is_primary" icon="pi pi-star" text size="small" class="h-7 w-7" v-tooltip.top="'Marcar como principal'" :disabled="api.saving.value" @click="setPrimary(email)" />
|
||||
<Button icon="pi pi-pencil" text size="small" class="h-7 w-7" v-tooltip.top="'Editar'" :disabled="api.saving.value" @click="startEdit(email)" />
|
||||
<Button icon="pi pi-trash" text severity="danger" size="small" class="h-7 w-7" v-tooltip.top="'Remover'" :disabled="api.saving.value" @click="confirmRemove(email)" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="flex flex-col gap-1.5 flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<Select
|
||||
v-model="editForm.contact_email_type_id"
|
||||
:options="api.types.value"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
class="text-xs"
|
||||
style="width: 140px"
|
||||
appendTo="body"
|
||||
>
|
||||
<template #option="slotProps">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<i :class="slotProps.option.icon || 'pi pi-envelope'" class="text-xs" />
|
||||
<span>{{ slotProps.option.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Select>
|
||||
<InputText v-model="editForm.email" type="email" class="flex-1 text-sm font-mono" style="min-width: 200px" />
|
||||
</div>
|
||||
<InputText v-model="editForm.notes" placeholder="Observação (opcional)" class="w-full text-xs" :maxlength="200" />
|
||||
</div>
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<Button icon="pi pi-check" severity="primary" size="small" class="h-7 w-7" v-tooltip.top="'Salvar'" :loading="api.saving.value" @click="saveEdit(email)" />
|
||||
<Button icon="pi pi-times" severity="secondary" text size="small" class="h-7 w-7" v-tooltip.top="'Cancelar'" :disabled="api.saving.value" @click="cancelEdit" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showAddForm" class="flex flex-col gap-2 p-2 rounded-md border border-dashed border-[var(--primary-color)]/50 bg-[var(--primary-color)]/5">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<Select
|
||||
v-model="newForm.contact_email_type_id"
|
||||
:options="api.types.value"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
class="text-xs"
|
||||
style="width: 140px"
|
||||
appendTo="body"
|
||||
>
|
||||
<template #option="slotProps">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<i :class="slotProps.option.icon || 'pi pi-envelope'" class="text-xs" />
|
||||
<span>{{ slotProps.option.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Select>
|
||||
<InputText v-model="newForm.email" type="email" placeholder="nome@exemplo.com" class="flex-1 text-sm font-mono" style="min-width: 200px" autofocus />
|
||||
</div>
|
||||
<InputText v-model="newForm.notes" placeholder="Observação (opcional)" class="w-full text-xs" :maxlength="200" />
|
||||
<div class="flex items-center gap-1 justify-end">
|
||||
<Button label="Cancelar" severity="secondary" text size="small" :disabled="api.saving.value" @click="cancelAddForm" />
|
||||
<Button label="Adicionar" icon="pi pi-check" size="small" :loading="api.saving.value" :disabled="!newForm.contact_email_type_id || !newForm.email.trim()" @click="submitAddForm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
v-if="!readonly && !showAddForm"
|
||||
label="Adicionar email"
|
||||
icon="pi pi-plus"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
class="self-start rounded-full"
|
||||
:disabled="!props.entityId"
|
||||
v-tooltip.right="!props.entityId ? 'Salve o cadastro primeiro pra adicionar emails' : null"
|
||||
@click="openAddForm"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,342 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Editor de telefones polimórfico
|
||||
|--------------------------------------------------------------------------
|
||||
| Uso:
|
||||
| <ContactPhonesEditor entity-type="patient" :entity-id="patient.id" />
|
||||
|
|
||||
| Auto-salva mudanças no banco (contact_phones) via useContactPhones.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch, reactive } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { useContactPhones } from '@/composables/useContactPhones';
|
||||
|
||||
const props = defineProps({
|
||||
entityType: { type: String, required: true }, // 'patient' | 'medico'
|
||||
entityId: { type: String, required: false, default: null }, // null = modo pendente (antes de criar entidade)
|
||||
readonly: { type: Boolean, default: false },
|
||||
confirmGroup: { type: String, default: '' } // grupo do ConfirmDialog (pra isolar de outros na página)
|
||||
});
|
||||
|
||||
const emit = defineEmits(['change']);
|
||||
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const api = useContactPhones();
|
||||
|
||||
// ── Mascaras ─────────────────────────────────────────────────
|
||||
const MASK_MOBILE = '(99) 99999-9999';
|
||||
const MASK_FIXED = '(99) 9999-9999';
|
||||
|
||||
function maskForType(typeId) {
|
||||
const t = api.typeById(typeId);
|
||||
return t?.is_mobile ? MASK_MOBILE : MASK_FIXED;
|
||||
}
|
||||
|
||||
// ── Formulário de nova linha ─────────────────────────────────
|
||||
const showAddForm = ref(false);
|
||||
const newForm = reactive({ contact_type_id: null, number: '', notes: '' });
|
||||
|
||||
function openAddForm() {
|
||||
// Default: primeiro tipo system (celular)
|
||||
const defaultType = api.typeBySlug('celular') || api.types.value[0];
|
||||
newForm.contact_type_id = defaultType?.id || null;
|
||||
newForm.number = '';
|
||||
newForm.notes = '';
|
||||
showAddForm.value = true;
|
||||
}
|
||||
|
||||
function cancelAddForm() {
|
||||
showAddForm.value = false;
|
||||
}
|
||||
|
||||
async function submitAddForm() {
|
||||
if (!newForm.contact_type_id || !newForm.number.trim()) return;
|
||||
const res = await api.addPhone(props.entityType, props.entityId, {
|
||||
contact_type_id: newForm.contact_type_id,
|
||||
number: newForm.number,
|
||||
is_primary: api.phones.value.length === 0, // primeiro vira primary
|
||||
notes: newForm.notes || null
|
||||
});
|
||||
if (res.ok) {
|
||||
showAddForm.value = false;
|
||||
toast.add({ severity: 'success', summary: 'Telefone adicionado', life: 1800 });
|
||||
emit('change', api.phones.value);
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Edição inline ────────────────────────────────────────────
|
||||
const editingId = ref(null);
|
||||
const editForm = reactive({ contact_type_id: null, number: '', notes: '' });
|
||||
|
||||
function startEdit(phone) {
|
||||
editingId.value = phone.id;
|
||||
editForm.contact_type_id = phone.contact_type_id;
|
||||
editForm.number = phone.number;
|
||||
editForm.notes = phone.notes || '';
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
editingId.value = null;
|
||||
}
|
||||
|
||||
async function saveEdit(phone) {
|
||||
const res = await api.updatePhone(props.entityType, props.entityId, phone.id, {
|
||||
contact_type_id: editForm.contact_type_id,
|
||||
number: editForm.number,
|
||||
notes: editForm.notes.trim() || null
|
||||
});
|
||||
if (res.ok) {
|
||||
editingId.value = null;
|
||||
toast.add({ severity: 'success', summary: 'Telefone atualizado', life: 1800 });
|
||||
emit('change', api.phones.value);
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Principal ────────────────────────────────────────────────
|
||||
async function setPrimary(phone) {
|
||||
if (phone.is_primary) return;
|
||||
const res = await api.setPrimary(props.entityType, props.entityId, phone.id);
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Telefone principal atualizado', life: 1800 });
|
||||
emit('change', api.phones.value);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Remover ──────────────────────────────────────────────────
|
||||
function confirmRemove(phone) {
|
||||
const typeName = api.typeById(phone.contact_type_id)?.name || 'telefone';
|
||||
confirm.require({
|
||||
group: props.confirmGroup || undefined,
|
||||
message: `Remover este ${typeName}${phone.is_primary ? ' (principal)' : ''}?`,
|
||||
header: 'Remover telefone',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
acceptLabel: 'Remover',
|
||||
rejectLabel: 'Cancelar',
|
||||
accept: async () => {
|
||||
const res = await api.removePhone(props.entityType, props.entityId, phone.id);
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Removido', life: 1800 });
|
||||
emit('change', api.phones.value);
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────
|
||||
function formatDisplay(number) {
|
||||
const s = String(number || '').replace(/\D/g, '');
|
||||
if (s.length === 11) return `(${s.slice(0, 2)}) ${s.slice(2, 7)}-${s.slice(7)}`;
|
||||
if (s.length === 10) return `(${s.slice(0, 2)}) ${s.slice(2, 6)}-${s.slice(6)}`;
|
||||
if (s.length === 13 && s.startsWith('55')) return `+55 (${s.slice(2, 4)}) ${s.slice(4, 9)}-${s.slice(9)}`;
|
||||
if (s.length === 12 && s.startsWith('55')) return `+55 (${s.slice(2, 4)}) ${s.slice(4, 8)}-${s.slice(8)}`;
|
||||
return number;
|
||||
}
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────
|
||||
onMounted(async () => {
|
||||
await api.loadTypes();
|
||||
if (props.entityId) await api.loadPhones(props.entityType, props.entityId);
|
||||
});
|
||||
|
||||
watch(() => props.entityId, async (v) => {
|
||||
if (v) await api.loadPhones(props.entityType, v);
|
||||
else api.phones.value = [];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<!-- Aviso sobre telefone principal -->
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] flex items-start gap-1.5 px-1">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5 shrink-0" />
|
||||
<span>
|
||||
Marque um telefone como <strong>principal</strong> — ele é usado pra
|
||||
<strong>cobranças, lembretes automáticos e contato padrão</strong>.
|
||||
Número vindo do CRM WhatsApp recebe a etiqueta <strong>"vinculado"</strong>.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Lista de telefones -->
|
||||
<div v-if="api.loading.value" class="text-xs text-center py-3 text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-spin pi-spinner mr-1" /> Carregando…
|
||||
</div>
|
||||
|
||||
<div v-else-if="!api.phones.value.length && !showAddForm" class="text-xs text-center py-4 italic text-[var(--text-color-secondary)] border border-dashed border-[var(--surface-border)] rounded-md">
|
||||
Nenhum telefone cadastrado.
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-col gap-1.5">
|
||||
<div
|
||||
v-for="phone in api.phones.value"
|
||||
:key="phone.id"
|
||||
class="flex items-center gap-2 p-2 rounded-md border border-[var(--surface-border)]"
|
||||
:class="phone.is_primary ? 'bg-[var(--primary-color)]/5 border-[var(--primary-color)]/30' : 'bg-[var(--surface-card)]'"
|
||||
>
|
||||
<!-- Modo leitura -->
|
||||
<template v-if="editingId !== phone.id">
|
||||
<!-- Ícone do tipo -->
|
||||
<div class="w-8 h-8 rounded grid place-items-center shrink-0 bg-[var(--surface-ground)]">
|
||||
<i :class="api.typeById(phone.contact_type_id)?.icon || 'pi pi-phone'" class="text-sm text-[var(--text-color-secondary)]" />
|
||||
</div>
|
||||
|
||||
<!-- Tipo + número + badges -->
|
||||
<div class="flex-1 min-w-0 flex flex-col gap-0.5">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<span class="text-xs font-semibold text-[var(--text-color-secondary)]">{{ api.typeById(phone.contact_type_id)?.name || 'Telefone' }}</span>
|
||||
<span v-if="phone.is_primary" class="inline-flex items-center px-1.5 py-px rounded-full text-[0.6rem] font-bold uppercase tracking-wide bg-[var(--primary-color)] text-white">Principal</span>
|
||||
<span v-if="phone.whatsapp_linked_at" class="inline-flex items-center gap-0.5 px-1.5 py-px rounded-full text-[0.6rem] font-bold uppercase tracking-wide bg-emerald-500/15 text-emerald-600">
|
||||
<i class="pi pi-link text-[0.55rem]" /> Vinculado
|
||||
</span>
|
||||
</div>
|
||||
<span class="text-sm font-mono font-semibold">{{ formatDisplay(phone.number) }}</span>
|
||||
<span v-if="phone.notes" class="text-[0.7rem] italic text-[var(--text-color-secondary)]">{{ phone.notes }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Ações -->
|
||||
<div v-if="!readonly" class="flex items-center gap-0.5 shrink-0">
|
||||
<Button
|
||||
v-if="!phone.is_primary"
|
||||
icon="pi pi-star"
|
||||
text
|
||||
size="small"
|
||||
class="h-7 w-7"
|
||||
v-tooltip.top="'Marcar como principal'"
|
||||
:disabled="api.saving.value"
|
||||
@click="setPrimary(phone)"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-pencil"
|
||||
text
|
||||
size="small"
|
||||
class="h-7 w-7"
|
||||
v-tooltip.top="'Editar'"
|
||||
:disabled="api.saving.value"
|
||||
@click="startEdit(phone)"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-trash"
|
||||
text
|
||||
severity="danger"
|
||||
size="small"
|
||||
class="h-7 w-7"
|
||||
v-tooltip.top="'Remover'"
|
||||
:disabled="api.saving.value"
|
||||
@click="confirmRemove(phone)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Modo edição -->
|
||||
<template v-else>
|
||||
<div class="flex flex-col gap-1.5 flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<Select
|
||||
v-model="editForm.contact_type_id"
|
||||
:options="api.types.value"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
class="text-xs"
|
||||
style="width: 140px"
|
||||
appendTo="body"
|
||||
>
|
||||
<template #option="slotProps">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<i :class="slotProps.option.icon || 'pi pi-phone'" class="text-xs" />
|
||||
<span>{{ slotProps.option.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Select>
|
||||
<InputMask
|
||||
v-model="editForm.number"
|
||||
:mask="maskForType(editForm.contact_type_id)"
|
||||
class="flex-1 text-sm font-mono"
|
||||
style="min-width: 140px"
|
||||
/>
|
||||
</div>
|
||||
<InputText
|
||||
v-model="editForm.notes"
|
||||
placeholder="Observação (opcional)"
|
||||
class="w-full text-xs"
|
||||
:maxlength="200"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<Button icon="pi pi-check" severity="primary" size="small" class="h-7 w-7" v-tooltip.top="'Salvar'" :loading="api.saving.value" @click="saveEdit(phone)" />
|
||||
<Button icon="pi pi-times" severity="secondary" text size="small" class="h-7 w-7" v-tooltip.top="'Cancelar'" :disabled="api.saving.value" @click="cancelEdit" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Formulário de nova linha -->
|
||||
<div v-if="showAddForm" class="flex flex-col gap-2 p-2 rounded-md border border-dashed border-[var(--primary-color)]/50 bg-[var(--primary-color)]/5">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<Select
|
||||
v-model="newForm.contact_type_id"
|
||||
:options="api.types.value"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
class="text-xs"
|
||||
style="width: 140px"
|
||||
appendTo="body"
|
||||
>
|
||||
<template #option="slotProps">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<i :class="slotProps.option.icon || 'pi pi-phone'" class="text-xs" />
|
||||
<span>{{ slotProps.option.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Select>
|
||||
<InputMask
|
||||
v-model="newForm.number"
|
||||
:mask="maskForType(newForm.contact_type_id)"
|
||||
class="flex-1 text-sm font-mono"
|
||||
style="min-width: 140px"
|
||||
autofocus
|
||||
/>
|
||||
</div>
|
||||
<InputText
|
||||
v-model="newForm.notes"
|
||||
placeholder="Observação (opcional)"
|
||||
class="w-full text-xs"
|
||||
:maxlength="200"
|
||||
/>
|
||||
<div class="flex items-center gap-1 justify-end">
|
||||
<Button label="Cancelar" severity="secondary" text size="small" :disabled="api.saving.value" @click="cancelAddForm" />
|
||||
<Button
|
||||
label="Adicionar"
|
||||
icon="pi pi-check"
|
||||
size="small"
|
||||
:loading="api.saving.value"
|
||||
:disabled="!newForm.contact_type_id || !newForm.number.trim()"
|
||||
@click="submitAddForm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Botão + -->
|
||||
<Button
|
||||
v-if="!readonly && !showAddForm"
|
||||
label="Adicionar telefone"
|
||||
icon="pi pi-plus"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
class="self-start rounded-full"
|
||||
:disabled="!props.entityId"
|
||||
v-tooltip.right="!props.entityId ? 'Salve o cadastro primeiro pra adicionar telefones' : null"
|
||||
@click="openAddForm"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -116,6 +116,32 @@ async function onCreated(data) {
|
||||
@click="pageRef?.fillRandomPatient?.()"
|
||||
/>
|
||||
|
||||
<!-- Conversar no WhatsApp (só em edição) -->
|
||||
<Button
|
||||
v-if="patientId"
|
||||
icon="pi pi-whatsapp"
|
||||
severity="success"
|
||||
outlined
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:disabled="pageRef?.saving?.value || pageRef?.deleting?.value"
|
||||
title="Conversar no WhatsApp"
|
||||
@click="pageRef?.goToConversation?.(); isOpen = false;"
|
||||
/>
|
||||
|
||||
<!-- Exportar LGPD (só em edição) -->
|
||||
<Button
|
||||
v-if="patientId"
|
||||
icon="pi pi-shield"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:disabled="pageRef?.saving?.value || pageRef?.deleting?.value"
|
||||
title="Exportar dados do paciente (LGPD)"
|
||||
@click="pageRef?.openLgpdDialog?.()"
|
||||
/>
|
||||
|
||||
<!-- Excluir (só em edição) -->
|
||||
<Button
|
||||
v-if="patientId"
|
||||
|
||||
Reference in New Issue
Block a user