CRM WhatsApp Grupo 3 completo + Marco A/B (Asaas) + admin SaaS + refactors polimórficos
Sessão 11+: fechamento do CRM de WhatsApp com dois providers (Evolution/Twilio),
sistema de créditos com Asaas/PIX, polimorfismo de telefones/emails, e integração
admin SaaS no /saas/addons existente.
═══════════════════════════════════════════════════════════════════════════
GRUPO 3 — WORKFLOW / CRM (completo)
═══════════════════════════════════════════════════════════════════════════
3.1 Tags · migration conversation_tags + seed de 5 system tags · composable
useConversationTags.js · popover + pills no drawer e nos cards do Kanban.
3.2 Atribuição de conversa a terapeuta · migration 20260421000012 com PK
(tenant_id, thread_key), UPSERT, RLS que valida assignee como membro ativo
do mesmo tenant · view conversation_threads expandida com assigned_to +
assigned_at · composable useConversationAssignment.js · drawer com Select
filtrável + botão "Assumir" · inbox com filtro aside (Todas/Minhas/Não
atribuídas) e chip do responsável em cada card (destaca "Eu" em azul).
3.3 Notas internas · migration conversation_notes · composable + seção
colapsável no drawer · apenas o criador pode editar/apagar (RLS).
3.5 Converter desconhecido em paciente · botão + dialog quick-cadastro ·
"Vincular existente" com Select filter de até 500 pacientes · cria
telefone WhatsApp (vinculado) via upsertWhatsappForExisting.
3.6 Histórico de conversa no prontuário · nova aba "Conversas" em
PatientProntuario.vue · PatientConversationsTab.vue com stats (total /
recebidas / enviadas / primeira / última), SelectButton de filtro, timeline
com bolhas por direção, mídia inline (imagem/áudio/vídeo/doc via signed
URL), indicadores ✓ ✓✓ de delivery, botão "Abrir no CRM".
═══════════════════════════════════════════════════════════════════════════
MARCO A — UNIFICAÇÃO WHATSAPP (dois providers mutuamente exclusivos)
═══════════════════════════════════════════════════════════════════════════
- Página chooser ConfiguracoesWhatsappChooserPage.vue com 2 cards (Pessoal/
Oficial), deactivate via edge function deactivate-notification-channel
- send-whatsapp-message refatorada com roteamento por provider; Twilio deduz
1 crédito antes do envio e refunda em falha
- Paridade Twilio (novo): módulo compartilhado supabase/functions/_shared/
whatsapp-hooks.ts com lógica provider-agnóstica (opt-in, opt-out, auto-
reply, schedule helpers em TZ São Paulo, makeTwilioCreditedSendFn que
envolve envio em dedução atômica + rollback). Consumido por Evolution E
Twilio inbound. Evolution refatorado (~290 linhas duplicadas removidas).
- Bucket privado whatsapp-media · decrypt via Evolution getBase64From
MediaMessage · upload com path tenant/yyyy/mm · signed URLs on-demand
═══════════════════════════════════════════════════════════════════════════
MARCO B — SISTEMA DE CRÉDITOS WHATSAPP + ASAAS
═══════════════════════════════════════════════════════════════════════════
Banco:
- Migration 20260421000007_whatsapp_credits (4 tabelas: balance,
transactions, packages, purchases) + RPCs add_whatsapp_credits e
deduct_whatsapp_credits (atômicas com SELECT FOR UPDATE)
- Migration 20260421000013_tenant_cpf_cnpj (coluna em tenants com CHECK
de 11 ou 14 dígitos)
Edge functions:
- create-whatsapp-credit-charge · Asaas v3 (sandbox + prod) · PIX com
QR code · getOrCreateAsaasCustomer patcha customer existente com CPF
quando está faltando
- asaas-webhook · recebe PAYMENT_RECEIVED/CONFIRMED e credita balance
Frontend (tenant):
- Página /configuracoes/creditos-whatsapp com saldo + loja + histórico
- Dialog de confirmação com CPF/CNPJ (validação via isValidCPF/CNPJ de
utils/validators, formatação on-blur, pré-fill de tenants.cpf_cnpj,
persiste no primeiro uso) · fallback sandbox 24971563792 REMOVIDO
- Composable useWhatsappCredits extrai erros amigáveis via
error.context.json()
Frontend (SaaS admin):
- Em /saas/addons (reuso do pattern existente, não criou página paralela):
- Aba 4 "Pacotes WhatsApp" — CRUD whatsapp_credit_packages com DataTable,
toggle is_active inline, dialog de edição com validação
- Aba 5 "Topup WhatsApp" — tenant Select com saldo ao vivo · RPC
add_whatsapp_credits com p_admin_id = auth.uid() (auditoria) · histórico
das últimas 20 transações topup/adjustment/refund
═══════════════════════════════════════════════════════════════════════════
GRUPO 2 — AUTOMAÇÃO
═══════════════════════════════════════════════════════════════════════════
2.3 Auto-reply · conversation_autoreply_settings + conversation_autoreply_
log · 3 modos de schedule (agenda das regras semanais, business_hours
custom, custom_window) · cooldown por thread · respeita opt-out · agora
funciona em Evolution E Twilio (hooks compartilhados)
2.4 Lembretes de sessão · conversation_session_reminders_settings +
_logs · edge send-session-reminders (cron) · janelas 24h e 2h antes ·
Twilio deduz crédito com rollback em falha
═══════════════════════════════════════════════════════════════════════════
GRUPO 5 — COMPLIANCE (LGPD Art. 18 §2)
═══════════════════════════════════════════════════════════════════════════
5.2 Opt-out · conversation_optouts + conversation_optout_keywords (10 system
seed + custom por tenant) · detecção por regex word-boundary e normalização
(lowercase + strip acentos + pontuação) · ack automático (deduz crédito em
Twilio) · opt-in via "voltar", "retornar", "reativar", "restart" ·
página /configuracoes/conversas-optouts com CRUD de keywords
═══════════════════════════════════════════════════════════════════════════
REFACTOR POLIMÓRFICO — TELEFONES + EMAILS
═══════════════════════════════════════════════════════════════════════════
- contact_types + contact_phones (entity_type + entity_id) — migration
20260421000008 · contact_email_types + contact_emails — 20260421000011
- Componentes ContactPhonesEditor.vue e ContactEmailsEditor.vue (add/edit/
remove com confirm, primary selector, WhatsApp linked badge)
- Composables useContactPhones.js + useContactEmails.js com
unsetOtherPrimaries() e validação
- Trocado em PatientsCadastroPage.vue e MedicosPage.vue (removidos campos
legados telefone/telefone_alternativo e email_principal/email_alternativo)
- Migration retroativa v2 (20260421000010) detecta conversation_messages
e cria/atualiza phone como WhatsApp vinculado
═══════════════════════════════════════════════════════════════════════════
POLIMENTO VISUAL + INFRA
═══════════════════════════════════════════════════════════════════════════
- Skeletons simplificados no dashboard do terapeuta
- Animações fade-up com stagger via [--delay:Xms] (fix specificity sobre
.dash-card box-shadow transition)
- ConfirmDialog com group="conversation-drawer" (evita montagem duplicada)
- Image preview PrimeVue com botão de download injetado via MutationObserver
(fetch + blob para funcionar cross-origin)
- Áudio/vídeo com preload="metadata" e controles de velocidade do browser
- friendlySendError() mapeia códigos do edge pra mensagens pt-BR via
error.context.json()
- Teleport #cfg-page-actions para ações globais de Configurações
- Brotli/Gzip + auto-import Vue/PrimeVue + bundle analyzer
- AppLayout consolidado (removidas duplicatas por área) + RouterPassthrough
- Removido console.trace debug que estava em watch de router e queries
Supabase (degradava perf pra todos)
- Realtime em conversation_messages via publication supabase_realtime
- Notifier global flutuante com beep + toggle mute (4 camadas: badge +
sino + popup + browser notification)
═══════════════════════════════════════════════════════════════════════════
MIGRATIONS NOVAS (13)
═══════════════════════════════════════════════════════════════════════════
20260420000001_patient_intake_invite_info_rpc
20260420000002_audit_logs_lgpd
20260420000003_audit_logs_unified_view
20260420000004_lgpd_export_patient_rpc
20260420000005_conversation_messages
20260420000005_search_global_rpc
20260420000006_conv_messages_notifications
20260420000007_notif_channels_saas_admin_insert
20260420000008_conv_messages_realtime
20260420000009_conv_messages_delivery_status
20260421000001_whatsapp_media_bucket
20260421000002_conversation_notes
20260421000003_conversation_tags
20260421000004_conversation_autoreply
20260421000005_conversation_optouts
20260421000006_session_reminders
20260421000007_whatsapp_credits
20260421000008_contact_phones
20260421000009_retroactive_whatsapp_link
20260421000010_retroactive_whatsapp_link_v2
20260421000011_contact_emails
20260421000012_conversation_assignments
20260421000013_tenant_cpf_cnpj
═══════════════════════════════════════════════════════════════════════════
EDGE FUNCTIONS NOVAS / MODIFICADAS
═══════════════════════════════════════════════════════════════════════════
Novas:
- _shared/whatsapp-hooks.ts (módulo compartilhado)
- asaas-webhook
- create-whatsapp-credit-charge
- deactivate-notification-channel
- evolution-webhook-provision
- evolution-whatsapp-inbound
- get-intake-invite-info
- notification-webhook
- send-session-reminders
- send-whatsapp-message
- submit-patient-intake
- twilio-whatsapp-inbound
═══════════════════════════════════════════════════════════════════════════
FRONTEND — RESUMO
═══════════════════════════════════════════════════════════════════════════
Composables novos: useAddonExtrato, useAuditoria, useAutoReplySettings,
useClinicKPIs, useContactEmails, useContactPhones, useConversationAssignment,
useConversationNotes, useConversationOptouts, useConversationTags,
useConversations, useLgpdExport, useSessionReminders, useWhatsappCredits
Stores: conversationDrawerStore
Componentes novos: ConversationDrawer, GlobalInboundNotifier, GlobalSearch,
ContactEmailsEditor, ContactPhonesEditor
Páginas novas: CRMConversasPage, PatientConversationsTab, AddonsExtratoPage,
AuditoriaPage, NotificationsHistoryPage, ConfiguracoesWhatsappChooserPage,
ConfiguracoesConversasAutoreplyPage, ConfiguracoesConversasOptoutsPage,
ConfiguracoesConversasTagsPage, ConfiguracoesCreditosWhatsappPage,
ConfiguracoesLembretesSessaoPage
Utils novos: addonExtratoExport, auditoriaExport, excelExport,
lgpdExportFormats
Páginas existentes alteradas: ClinicDashboard, PatientsCadastroPage,
PatientCadastroDialog, PatientsListPage, MedicosPage, PatientProntuario,
ConfiguracoesWhatsappPage, SaasWhatsappPage, ConfiguracoesRecursosExtrasPage,
ConfiguracoesPage, AgendaTerapeutaPage, AgendaClinicaPage, NotificationItem,
NotificationDrawer, AppLayout, AppTopbar, useMenuBadges,
patientsRepository, SaasAddonsPage (aba 4 + 5 WhatsApp)
Routes: routes.clinic, routes.configs, routes.therapist atualizados
Menus: clinic.menu, therapist.menu, saas.menu atualizados
═══════════════════════════════════════════════════════════════════════════
NOTAS
- Após subir, rodar supabase functions serve --no-verify-jwt
--env-file supabase/functions/.env pra carregar o módulo _shared
- WHATSAPP_SETUP.md reescrito (~400 linhas) com setup completo dos 3
providers + troubleshooting + LGPD
- HANDOFF.md atualizado com estado atual e próximos passos
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,345 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/layout/configuracoes/AddonsExtratoPage.vue
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useAddonExtrato } from '@/composables/useAddonExtrato';
|
||||
import { downloadExtratoCSV, downloadExtratoPDF, formatters } from '@/utils/addonExtratoExport';
|
||||
import { downloadExcel } from '@/utils/excelExport';
|
||||
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
|
||||
const { rows, balances, filters, dateRange, loading, summary, load, loadBalances } = useAddonExtrato();
|
||||
|
||||
const tenantName = ref('');
|
||||
const exportingPdf = ref(false);
|
||||
|
||||
// ── opções dos filtros ──────────────────────────────────────────────────
|
||||
|
||||
const periodOptions = [
|
||||
{ label: 'Este mês', value: 'thisMonth' },
|
||||
{ label: 'Mês anterior', value: 'lastMonth' },
|
||||
{ label: 'Últimos 90 dias', value: 'last90' },
|
||||
{ label: 'Personalizado', value: 'custom' }
|
||||
];
|
||||
|
||||
const addonTypeOptions = [
|
||||
{ label: 'SMS', value: 'sms' },
|
||||
{ label: 'E-mail', value: 'email' },
|
||||
{ label: 'Servidor', value: 'server' },
|
||||
{ label: 'Domínio', value: 'domain' }
|
||||
];
|
||||
|
||||
const movementOptions = [
|
||||
{ label: 'Compra', value: 'purchase' },
|
||||
{ label: 'Consumo', value: 'consumption' },
|
||||
{ label: 'Ajuste', value: 'adjustment' },
|
||||
{ label: 'Reembolso', value: 'refund' },
|
||||
{ label: 'Bônus', value: 'bonus' },
|
||||
{ label: 'Expiração', value: 'expiration' }
|
||||
];
|
||||
|
||||
// ── labels ──────────────────────────────────────────────────────────────
|
||||
|
||||
const periodLabel = computed(() => {
|
||||
const preset = periodOptions.find((p) => p.value === filters.value.periodPreset)?.label ?? '';
|
||||
const { from, to } = dateRange.value;
|
||||
const fmt = (d) => new Date(d).toLocaleDateString('pt-BR');
|
||||
return `${preset} (${fmt(from)} → ${fmt(to)})`;
|
||||
});
|
||||
|
||||
function movementSeverity(type) {
|
||||
const map = { purchase: 'success', consumption: 'warning', adjustment: 'info', refund: 'secondary', bonus: 'success', expiration: 'danger' };
|
||||
return map[type] || 'secondary';
|
||||
}
|
||||
|
||||
function amountClass(r) {
|
||||
if (r.type === 'consumption' || r.type === 'expiration') return 'text-red-500 font-semibold';
|
||||
if (r.type === 'purchase' || r.type === 'bonus' || r.type === 'refund') return 'text-emerald-500 font-semibold';
|
||||
return '';
|
||||
}
|
||||
|
||||
// ── ações ───────────────────────────────────────────────────────────────
|
||||
|
||||
async function reload() {
|
||||
await Promise.all([load(), loadBalances()]);
|
||||
}
|
||||
|
||||
function onFilterChange() {
|
||||
// recarrega apenas quando muda filtro server-side (período/addon/movimento)
|
||||
reload();
|
||||
}
|
||||
|
||||
function slugify(s) {
|
||||
if (!s) return 'clinica';
|
||||
return String(s)
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/(^-|-$)/g, '')
|
||||
.slice(0, 40) || 'clinica';
|
||||
}
|
||||
|
||||
function filenameBase() {
|
||||
const now = new Date();
|
||||
const ym = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
|
||||
return `extrato-addons-${slugify(tenantName.value)}-${ym}`;
|
||||
}
|
||||
|
||||
function onExportCSV() {
|
||||
try {
|
||||
downloadExtratoCSV(rows.value, summary.value, periodLabel.value, `${filenameBase()}.csv`);
|
||||
toast.add({ severity: 'success', summary: 'CSV gerado', detail: `${summary.value.totalRows} registro(s) exportado(s).`, life: 3000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao gerar CSV', detail: err?.message || 'Erro inesperado', life: 5000 });
|
||||
}
|
||||
}
|
||||
|
||||
async function onExportPDF() {
|
||||
if (exportingPdf.value) return;
|
||||
exportingPdf.value = true;
|
||||
try {
|
||||
await downloadExtratoPDF(rows.value, summary.value, periodLabel.value, tenantName.value, `${filenameBase()}.pdf`);
|
||||
toast.add({ severity: 'success', summary: 'PDF gerado', detail: `${summary.value.totalRows} registro(s) exportado(s).`, life: 3000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao gerar PDF', detail: err?.message || 'Erro inesperado', life: 5000 });
|
||||
} finally {
|
||||
exportingPdf.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onExportExcel() {
|
||||
try {
|
||||
await downloadExcel({
|
||||
filename: `${filenameBase()}.xlsx`,
|
||||
sheetName: 'Extrato de addons',
|
||||
headers: [
|
||||
{ key: 'created_at', label: 'Data/Hora', type: 'date', width: 20 },
|
||||
{ key: 'addon_label', label: 'Recurso', type: 'text', width: 14 },
|
||||
{ key: 'movement_label', label: 'Tipo', type: 'text', width: 14 },
|
||||
{ key: 'amount', label: 'Quantidade', type: 'number', width: 14 },
|
||||
{ key: 'balance_after', label: 'Saldo após', type: 'number', width: 14 },
|
||||
{ key: 'description', label: 'Descrição', type: 'text', width: 40 },
|
||||
{ key: 'price_cents', label: 'Valor', type: 'money', width: 14 },
|
||||
{ key: 'payment_method', label: 'Método', type: 'text', width: 14 },
|
||||
{ key: 'payment_reference', label: 'Referência', type: 'text', width: 28 }
|
||||
],
|
||||
rows: rows.value.map((r) => ({
|
||||
...r,
|
||||
addon_label: formatters.addonLabel(r.addon_type),
|
||||
movement_label: formatters.movementLabel(r.type)
|
||||
})),
|
||||
footerRows: [
|
||||
['Período', periodLabel.value],
|
||||
['Total de registros', summary.value.totalRows],
|
||||
['Total comprado (créditos)', summary.value.purchasedCredits],
|
||||
['Total comprado (R$)', summary.value.purchasedCents / 100],
|
||||
['Total consumido (créditos)', summary.value.consumedCredits]
|
||||
]
|
||||
});
|
||||
toast.add({ severity: 'success', summary: 'Excel gerado', detail: `${summary.value.totalRows} registro(s) exportado(s).`, life: 3000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao gerar Excel', detail: err?.message || 'Erro inesperado', life: 5000 });
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTenantName() {
|
||||
const tenantId = tenantStore.activeTenantId;
|
||||
if (!tenantId) return;
|
||||
const { data } = await supabase.from('tenants').select('name').eq('id', tenantId).maybeSingle();
|
||||
tenantName.value = data?.name || '';
|
||||
}
|
||||
|
||||
// ── init ────────────────────────────────────────────────────────────────
|
||||
|
||||
onMounted(async () => {
|
||||
await loadTenantName();
|
||||
await reload();
|
||||
});
|
||||
|
||||
// recarrega quando muda tenant ativo
|
||||
watch(
|
||||
() => tenantStore.activeTenantId,
|
||||
async () => {
|
||||
await loadTenantName();
|
||||
await reload();
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-5">
|
||||
<!-- Header -->
|
||||
<Card>
|
||||
<template #title>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button icon="pi pi-arrow-left" text rounded severity="secondary" class="!w-8 !h-8" @click="router.push({ name: 'ConfiguracoesRecursosExtras' })" v-tooltip.bottom="'Voltar'" />
|
||||
<i class="pi pi-list text-xl" />
|
||||
Extrato de Recursos Extras
|
||||
</div>
|
||||
</template>
|
||||
<template #subtitle> Histórico de compras, consumos e ajustes. Use para disputar cobranças ou planejar renovações. </template>
|
||||
</Card>
|
||||
|
||||
<!-- Filtros -->
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="grid grid-cols-1 md:grid-cols-12 gap-3">
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Período</label>
|
||||
<Select v-model="filters.periodPreset" :options="periodOptions" optionLabel="label" optionValue="value" class="w-full" @change="onFilterChange" />
|
||||
</div>
|
||||
|
||||
<div v-if="filters.periodPreset === 'custom'" class="md:col-span-4">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Intervalo personalizado</label>
|
||||
<DatePicker v-model="filters.customRange" selectionMode="range" dateFormat="dd/mm/yy" :manualInput="false" showIcon class="w-full" @update:model-value="onFilterChange" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Tipo de recurso</label>
|
||||
<MultiSelect v-model="filters.addonTypes" :options="addonTypeOptions" optionLabel="label" optionValue="value" placeholder="Todos" class="w-full" display="chip" :maxSelectedLabels="2" @change="onFilterChange" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Tipo de movimento</label>
|
||||
<MultiSelect v-model="filters.movementTypes" :options="movementOptions" optionLabel="label" optionValue="value" placeholder="Todos" class="w-full" display="chip" :maxSelectedLabels="2" @change="onFilterChange" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-6">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Buscar por referência / descrição / método</label>
|
||||
<IconField>
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="filters.search" placeholder="ex: ID de pagamento, descrição..." class="w-full" maxlength="120" />
|
||||
</IconField>
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-6 flex items-end gap-2">
|
||||
<Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined @click="reload" :loading="loading" />
|
||||
<Button label="Exportar CSV" icon="pi pi-file" severity="secondary" @click="onExportCSV" :disabled="!rows.length" />
|
||||
<Button label="Exportar Excel" icon="pi pi-file-excel" severity="secondary" @click="onExportExcel" :disabled="!rows.length" />
|
||||
<Button label="Exportar PDF" icon="pi pi-file-pdf" severity="secondary" @click="onExportPDF" :disabled="!rows.length" :loading="exportingPdf" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<!-- Resumo -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Registros no período</span>
|
||||
<span class="text-2xl font-bold mt-1">{{ summary.totalRows }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Comprado (créditos)</span>
|
||||
<span class="text-2xl font-bold mt-1 text-emerald-500">+{{ summary.purchasedCredits }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Comprado (R$)</span>
|
||||
<span class="text-2xl font-bold mt-1">{{ formatters.fmtBRL(summary.purchasedCents) || 'R$ 0,00' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Consumido (créditos)</span>
|
||||
<span class="text-2xl font-bold mt-1 text-red-500">-{{ summary.consumedCredits }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<!-- Tabela -->
|
||||
<Card>
|
||||
<template #content>
|
||||
<DataTable
|
||||
:value="rows"
|
||||
:loading="loading"
|
||||
size="small"
|
||||
stripedRows
|
||||
paginator
|
||||
:rows="20"
|
||||
:rowsPerPageOptions="[10, 20, 50, 100]"
|
||||
sortField="created_at"
|
||||
:sortOrder="-1"
|
||||
emptyMessage="Nenhuma transação encontrada no período. Ajuste os filtros ou selecione um intervalo mais amplo."
|
||||
>
|
||||
<Column field="created_at" header="Data" style="min-width: 150px" sortable>
|
||||
<template #body="{ data }">{{ formatters.fmtDate(data.created_at) }}</template>
|
||||
</Column>
|
||||
|
||||
<Column field="addon_type" header="Recurso" style="width: 110px" sortable>
|
||||
<template #body="{ data }">
|
||||
<Tag :value="formatters.addonLabel(data.addon_type)" severity="info" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="type" header="Tipo" style="width: 130px" sortable>
|
||||
<template #body="{ data }">
|
||||
<Tag :value="formatters.movementLabel(data.type)" :severity="movementSeverity(data.type)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="amount" header="Qtd." style="width: 90px" sortable>
|
||||
<template #body="{ data }">
|
||||
<span :class="amountClass(data)">{{ formatters.fmtAmount(data) }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="balance_after" header="Saldo após" style="width: 100px">
|
||||
<template #body="{ data }">{{ data.balance_after }}</template>
|
||||
</Column>
|
||||
|
||||
<Column field="description" header="Descrição">
|
||||
<template #body="{ data }">
|
||||
<span class="text-sm">{{ data.description || '—' }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="price_cents" header="Valor" style="width: 110px">
|
||||
<template #body="{ data }">
|
||||
<span v-if="data.price_cents">{{ formatters.fmtBRL(data.price_cents) }}</span>
|
||||
<span v-else class="text-surface-400">—</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="payment_reference" header="Referência" style="max-width: 180px">
|
||||
<template #body="{ data }">
|
||||
<span class="text-xs text-surface-500 font-mono">{{ data.payment_reference || '—' }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,434 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/layout/configuracoes/AuditoriaPage.vue
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useAuditoria } from '@/composables/useAuditoria';
|
||||
import { downloadAuditCSV, downloadAuditPDF, auditFormatters, sourceLabel, entityLabel } from '@/utils/auditoriaExport';
|
||||
import { downloadExcel } from '@/utils/excelExport';
|
||||
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
|
||||
const { rows, filters, dateRange, loading, summary, userDisplay, load } = useAuditoria();
|
||||
|
||||
const tenantName = ref('');
|
||||
const exportingPdf = ref(false);
|
||||
|
||||
// detalhes do evento clicado
|
||||
const detailDialog = ref(false);
|
||||
const selectedEvent = ref(null);
|
||||
|
||||
// ── opções dos filtros ──────────────────────────────────────────────────
|
||||
|
||||
const periodOptions = [
|
||||
{ label: 'Hoje', value: 'today' },
|
||||
{ label: 'Últimos 7 dias', value: 'last7' },
|
||||
{ label: 'Últimos 30 dias', value: 'last30' },
|
||||
{ label: 'Últimos 90 dias', value: 'last90' },
|
||||
{ label: 'Personalizado', value: 'custom' }
|
||||
];
|
||||
|
||||
const sourceOptions = [
|
||||
{ label: 'Auditoria (CRUD)', value: 'audit_logs' },
|
||||
{ label: 'Acesso a documentos', value: 'document_access_logs' },
|
||||
{ label: 'Status de paciente', value: 'patient_status_history' },
|
||||
{ label: 'Notificações', value: 'notification_logs' },
|
||||
{ label: 'Recursos extras', value: 'addon_transactions' }
|
||||
];
|
||||
|
||||
const entityOptions = [
|
||||
{ label: 'Paciente', value: 'patients' },
|
||||
{ label: 'Evento de agenda', value: 'agenda_eventos' },
|
||||
{ label: 'Registro financeiro', value: 'financial_records' },
|
||||
{ label: 'Documento', value: 'documents' },
|
||||
{ label: 'Membro do tenant', value: 'tenant_members' },
|
||||
{ label: 'Documento (acesso)', value: 'document' },
|
||||
{ label: 'Notificação', value: 'notification' },
|
||||
{ label: 'Status de paciente', value: 'patient_status' },
|
||||
{ label: 'Transação de recurso', value: 'addon_transaction' }
|
||||
];
|
||||
|
||||
const actionOptions = [
|
||||
{ label: 'Criou', value: 'insert' },
|
||||
{ label: 'Alterou', value: 'update' },
|
||||
{ label: 'Excluiu', value: 'delete' },
|
||||
{ label: 'Visualizou', value: 'visualizou' },
|
||||
{ label: 'Baixou', value: 'baixou' },
|
||||
{ label: 'Imprimiu', value: 'imprimiu' },
|
||||
{ label: 'Compartilhou', value: 'compartilhou' },
|
||||
{ label: 'Assinou', value: 'assinou' },
|
||||
{ label: 'Status alterado', value: 'status_change' },
|
||||
{ label: 'Compra', value: 'purchase' },
|
||||
{ label: 'Consumo', value: 'consumption' }
|
||||
];
|
||||
|
||||
// ── labels ─────────────────────────────────────────────────────────────
|
||||
|
||||
const periodLabel = computed(() => {
|
||||
const preset = periodOptions.find((p) => p.value === filters.value.periodPreset)?.label ?? '';
|
||||
const { from, to } = dateRange.value;
|
||||
const fmt = (d) => new Date(d).toLocaleDateString('pt-BR');
|
||||
return `${preset} (${fmt(from)} → ${fmt(to)})`;
|
||||
});
|
||||
|
||||
function sourceSeverity(src) {
|
||||
const map = {
|
||||
audit_logs: 'info',
|
||||
document_access_logs: 'secondary',
|
||||
patient_status_history: 'warning',
|
||||
notification_logs: 'success',
|
||||
addon_transactions: 'help'
|
||||
};
|
||||
return map[src] || 'secondary';
|
||||
}
|
||||
|
||||
function actionSeverity(action) {
|
||||
if (['delete', 'failed', 'bounced'].includes(action)) return 'danger';
|
||||
if (['insert', 'sent', 'delivered', 'purchase'].includes(action)) return 'success';
|
||||
if (['update', 'status_change'].includes(action)) return 'warning';
|
||||
return 'info';
|
||||
}
|
||||
|
||||
// ── ações ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function reload() {
|
||||
await load();
|
||||
}
|
||||
|
||||
function openDetails(ev) {
|
||||
selectedEvent.value = ev;
|
||||
detailDialog.value = true;
|
||||
}
|
||||
|
||||
function prettyJson(obj) {
|
||||
if (!obj) return '';
|
||||
try {
|
||||
return JSON.stringify(obj, null, 2);
|
||||
} catch {
|
||||
return String(obj);
|
||||
}
|
||||
}
|
||||
|
||||
function slugify(s) {
|
||||
if (!s) return 'clinica';
|
||||
return (
|
||||
String(s)
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/(^-|-$)/g, '')
|
||||
.slice(0, 40) || 'clinica'
|
||||
);
|
||||
}
|
||||
|
||||
function filenameBase() {
|
||||
const now = new Date();
|
||||
const ym = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
|
||||
return `auditoria-${slugify(tenantName.value)}-${ym}`;
|
||||
}
|
||||
|
||||
function onExportCSV() {
|
||||
try {
|
||||
downloadAuditCSV(rows.value, summary.value, periodLabel.value, userDisplay, `${filenameBase()}.csv`);
|
||||
toast.add({ severity: 'success', summary: 'CSV gerado', detail: `${summary.value.totalRows} evento(s) exportado(s).`, life: 3000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao gerar CSV', detail: err?.message || 'Erro inesperado', life: 5000 });
|
||||
}
|
||||
}
|
||||
|
||||
async function onExportPDF() {
|
||||
if (exportingPdf.value) return;
|
||||
exportingPdf.value = true;
|
||||
try {
|
||||
await downloadAuditPDF(rows.value, summary.value, periodLabel.value, tenantName.value, userDisplay, `${filenameBase()}.pdf`);
|
||||
toast.add({ severity: 'success', summary: 'PDF gerado', detail: `${summary.value.totalRows} evento(s) exportado(s).`, life: 3000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao gerar PDF', detail: err?.message || 'Erro inesperado', life: 5000 });
|
||||
} finally {
|
||||
exportingPdf.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onExportExcel() {
|
||||
try {
|
||||
await downloadExcel({
|
||||
filename: `${filenameBase()}.xlsx`,
|
||||
sheetName: 'Auditoria',
|
||||
headers: [
|
||||
{ key: 'occurred_at', label: 'Data/Hora', type: 'date', width: 20 },
|
||||
{ key: 'source_label', label: 'Origem', type: 'text', width: 18 },
|
||||
{ key: 'entity_label', label: 'Entidade', type: 'text', width: 18 },
|
||||
{ key: 'entity_id', label: 'ID entidade', type: 'text', width: 38 },
|
||||
{ key: 'action', label: 'Ação', type: 'text', width: 14 },
|
||||
{ key: 'description', label: 'Descrição', type: 'text', width: 60 },
|
||||
{ key: 'user_display', label: 'Usuário', type: 'text', width: 24 }
|
||||
],
|
||||
rows: rows.value.map((r) => ({
|
||||
...r,
|
||||
source_label: sourceLabel(r.source),
|
||||
entity_label: entityLabel(r.entity_type),
|
||||
user_display: userDisplay(r.user_id)
|
||||
})),
|
||||
footerRows: [
|
||||
['Período', periodLabel.value],
|
||||
['Total de registros', summary.value.totalRows],
|
||||
['Usuários distintos', summary.value.distinctUsers]
|
||||
]
|
||||
});
|
||||
toast.add({ severity: 'success', summary: 'Excel gerado', detail: `${summary.value.totalRows} evento(s) exportado(s).`, life: 3000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao gerar Excel', detail: err?.message || 'Erro inesperado', life: 5000 });
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTenantName() {
|
||||
const tenantId = tenantStore.activeTenantId;
|
||||
if (!tenantId) return;
|
||||
const { data } = await supabase.from('tenants').select('name').eq('id', tenantId).maybeSingle();
|
||||
tenantName.value = data?.name || '';
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadTenantName();
|
||||
await reload();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => tenantStore.activeTenantId,
|
||||
async () => {
|
||||
await loadTenantName();
|
||||
await reload();
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-5">
|
||||
<!-- Header -->
|
||||
<Card>
|
||||
<template #title>
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-shield text-xl" />
|
||||
Auditoria da Clínica
|
||||
</div>
|
||||
</template>
|
||||
<template #subtitle>
|
||||
Registro imutável de operações de tratamento. Exigido pela <strong>LGPD Art. 37</strong>. Use para responder solicitações do titular ou investigar inconsistências.
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<!-- Filtros -->
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="grid grid-cols-1 md:grid-cols-12 gap-3">
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Período</label>
|
||||
<Select v-model="filters.periodPreset" :options="periodOptions" optionLabel="label" optionValue="value" class="w-full" @change="reload" />
|
||||
</div>
|
||||
|
||||
<div v-if="filters.periodPreset === 'custom'" class="md:col-span-4">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Intervalo personalizado</label>
|
||||
<DatePicker v-model="filters.customRange" selectionMode="range" dateFormat="dd/mm/yy" :manualInput="false" showIcon class="w-full" @update:model-value="reload" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Origem</label>
|
||||
<MultiSelect v-model="filters.sources" :options="sourceOptions" optionLabel="label" optionValue="value" placeholder="Todas" class="w-full" display="chip" :maxSelectedLabels="2" @change="reload" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Tipo de entidade</label>
|
||||
<MultiSelect v-model="filters.entityTypes" :options="entityOptions" optionLabel="label" optionValue="value" placeholder="Todas" class="w-full" display="chip" :maxSelectedLabels="2" @change="reload" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-3">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Ação</label>
|
||||
<MultiSelect v-model="filters.actions" :options="actionOptions" optionLabel="label" optionValue="value" placeholder="Todas" class="w-full" display="chip" :maxSelectedLabels="2" @change="reload" />
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-6">
|
||||
<label class="text-xs font-medium text-surface-500 mb-1 block">Buscar (descrição, entidade, ação, usuário)</label>
|
||||
<IconField>
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="filters.search" placeholder="ex: paciente, login, email..." class="w-full" maxlength="120" />
|
||||
</IconField>
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-6 flex items-end gap-2">
|
||||
<Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined @click="reload" :loading="loading" />
|
||||
<Button label="Exportar CSV" icon="pi pi-file" severity="secondary" @click="onExportCSV" :disabled="!rows.length" />
|
||||
<Button label="Exportar Excel" icon="pi pi-file-excel" severity="secondary" @click="onExportExcel" :disabled="!rows.length" />
|
||||
<Button label="Exportar PDF" icon="pi pi-file-pdf" severity="secondary" @click="onExportPDF" :disabled="!rows.length" :loading="exportingPdf" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<!-- Resumo -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Eventos no período</span>
|
||||
<span class="text-2xl font-bold mt-1">{{ summary.totalRows }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Usuários distintos</span>
|
||||
<span class="text-2xl font-bold mt-1">{{ summary.distinctUsers }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">CRUD (criar/alterar/excluir)</span>
|
||||
<span class="text-2xl font-bold mt-1">
|
||||
{{ (summary.byAction.insert || 0) + (summary.byAction.update || 0) + (summary.byAction.delete || 0) }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<Card>
|
||||
<template #content>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-surface-500 uppercase tracking-wide">Acessos a documento</span>
|
||||
<span class="text-2xl font-bold mt-1">{{ summary.bySource.document_access_logs || 0 }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<!-- Tabela -->
|
||||
<Card>
|
||||
<template #content>
|
||||
<DataTable
|
||||
:value="rows"
|
||||
:loading="loading"
|
||||
size="small"
|
||||
stripedRows
|
||||
paginator
|
||||
:rows="25"
|
||||
:rowsPerPageOptions="[10, 25, 50, 100, 200]"
|
||||
sortField="occurred_at"
|
||||
:sortOrder="-1"
|
||||
emptyMessage="Nenhum evento auditado no período. Ajuste os filtros."
|
||||
:pt="{
|
||||
bodyRow: ({ context }) => ({ class: 'cursor-pointer hover:bg-primary/5' })
|
||||
}"
|
||||
@row-click="(ev) => openDetails(ev.data)"
|
||||
>
|
||||
<Column field="occurred_at" header="Data/Hora" style="min-width: 160px" sortable>
|
||||
<template #body="{ data }">{{ auditFormatters.fmtDate(data.occurred_at) }}</template>
|
||||
</Column>
|
||||
|
||||
<Column field="source" header="Origem" style="width: 140px" sortable>
|
||||
<template #body="{ data }">
|
||||
<Tag :value="auditFormatters.sourceLabel(data.source)" :severity="sourceSeverity(data.source)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="entity_type" header="Entidade" style="width: 130px" sortable>
|
||||
<template #body="{ data }">{{ auditFormatters.entityLabel(data.entity_type) }}</template>
|
||||
</Column>
|
||||
|
||||
<Column field="action" header="Ação" style="width: 120px" sortable>
|
||||
<template #body="{ data }">
|
||||
<Tag :value="data.action" :severity="actionSeverity(data.action)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="description" header="Descrição">
|
||||
<template #body="{ data }">
|
||||
<span class="text-sm">{{ data.description || '—' }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="user_id" header="Usuário" style="width: 180px">
|
||||
<template #body="{ data }">
|
||||
<span class="text-xs">{{ userDisplay(data.user_id) }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<!-- Dialog de detalhes -->
|
||||
<Dialog
|
||||
v-model:visible="detailDialog"
|
||||
modal
|
||||
:draggable="false"
|
||||
:closable="true"
|
||||
:dismissableMask="true"
|
||||
maximizable
|
||||
class="dc-dialog w-[60rem]"
|
||||
:breakpoints="{ '1199px': '92vw', '768px': '96vw' }"
|
||||
header="Detalhes do evento"
|
||||
>
|
||||
<div v-if="selectedEvent" class="flex flex-col gap-3">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
|
||||
<div><strong>Data/Hora:</strong> {{ auditFormatters.fmtDate(selectedEvent.occurred_at) }}</div>
|
||||
<div><strong>Origem:</strong> {{ auditFormatters.sourceLabel(selectedEvent.source) }}</div>
|
||||
<div><strong>Entidade:</strong> {{ auditFormatters.entityLabel(selectedEvent.entity_type) }}</div>
|
||||
<div><strong>Ação:</strong> {{ selectedEvent.action }}</div>
|
||||
<div><strong>ID da entidade:</strong> <span class="font-mono text-xs">{{ selectedEvent.entity_id || '—' }}</span></div>
|
||||
<div><strong>Usuário:</strong> {{ userDisplay(selectedEvent.user_id) }}</div>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
<div>
|
||||
<strong class="text-sm">Descrição:</strong>
|
||||
<p class="text-sm mt-1">{{ selectedEvent.description }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedEvent.details && selectedEvent.details.changed_fields?.length">
|
||||
<strong class="text-sm">Campos alterados:</strong>
|
||||
<div class="flex flex-wrap gap-1 mt-1">
|
||||
<Tag v-for="f in selectedEvent.details.changed_fields" :key="f" :value="f" severity="warning" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedEvent.details?.old_values">
|
||||
<strong class="text-sm">Estado anterior:</strong>
|
||||
<pre class="text-xs bg-surface-50 p-2 rounded border border-surface-200 overflow-auto max-h-64 mt-1">{{ prettyJson(selectedEvent.details.old_values) }}</pre>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedEvent.details?.new_values">
|
||||
<strong class="text-sm">Estado novo:</strong>
|
||||
<pre class="text-xs bg-surface-50 p-2 rounded border border-surface-200 overflow-auto max-h-64 mt-1">{{ prettyJson(selectedEvent.details.new_values) }}</pre>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedEvent.details && !selectedEvent.details.old_values && !selectedEvent.details.new_values">
|
||||
<strong class="text-sm">Metadados:</strong>
|
||||
<pre class="text-xs bg-surface-50 p-2 rounded border border-surface-200 overflow-auto max-h-64 mt-1">{{ prettyJson(selectedEvent.details) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Fechar" icon="pi pi-times" text @click="detailDialog = false" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -574,11 +574,11 @@ onMounted(load);
|
||||
<span class="text-sm font-medium" :class="cfg.ativo ? 'text-green-600' : 'text-surface-400'">
|
||||
{{ cfg.ativo ? 'Ativo' : 'Inativo' }}
|
||||
</span>
|
||||
<InputSwitch :modelValue="cfg.ativo" @update:modelValue="toggleAtivo" />
|
||||
<ToggleSwitch :modelValue="cfg.ativo" @update:modelValue="toggleAtivo" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<Tag value="Plano não inclui" severity="warn" class="text-xs" />
|
||||
<InputSwitch :modelValue="false" disabled v-tooltip.left="'Seu plano não inclui o Agendador Online'" />
|
||||
<ToggleSwitch :modelValue="false" disabled v-tooltip.left="'Seu plano não inclui o Agendador Online'" />
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -752,7 +752,7 @@ onMounted(load);
|
||||
<div class="font-semibold">Botão "Como chegar"</div>
|
||||
<div class="text-surface-400 mt-0.5">Exibe um botão que abre o mapa para o paciente.</div>
|
||||
</div>
|
||||
<InputSwitch v-model="cfg.botao_como_chegar_ativo" />
|
||||
<ToggleSwitch v-model="cfg.botao_como_chegar_ativo" />
|
||||
</div>
|
||||
<div v-if="cfg.botao_como_chegar_ativo" class="flex flex-col gap-1">
|
||||
<label class="cfg-label">URL do Google Maps <span class="font-normal opacity-60">(opcional)</span></label>
|
||||
@@ -986,14 +986,14 @@ onMounted(load);
|
||||
<div class="font-semibold">Motivo da consulta</div>
|
||||
<div class="text-surface-400 mt-0.5">Campo de texto livre opcional para o paciente informar o motivo.</div>
|
||||
</div>
|
||||
<InputSwitch v-model="cfg.triagem_motivo" />
|
||||
<ToggleSwitch v-model="cfg.triagem_motivo" />
|
||||
</div>
|
||||
<div class="flex items-center justify-between p-3 bg-surface-50 dark:bg-surface-800 rounded-[6px]">
|
||||
<div>
|
||||
<div class="font-semibold">Como nos conheceu?</div>
|
||||
<div class="text-surface-400 mt-0.5">Pergunta de origem (indicação, redes sociais, busca…).</div>
|
||||
</div>
|
||||
<InputSwitch v-model="cfg.triagem_como_conheceu" />
|
||||
<ToggleSwitch v-model="cfg.triagem_como_conheceu" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1007,14 +1007,14 @@ onMounted(load);
|
||||
<div class="font-semibold">Verificação de e-mail</div>
|
||||
<div class="text-surface-400 mt-0.5">Paciente confirma o e-mail antes de concluir o agendamento.</div>
|
||||
</div>
|
||||
<InputSwitch v-model="cfg.verificacao_email" />
|
||||
<ToggleSwitch v-model="cfg.verificacao_email" />
|
||||
</div>
|
||||
<div class="flex items-center justify-between p-3 bg-surface-50 dark:bg-surface-800 rounded-[6px]">
|
||||
<div>
|
||||
<div class="font-semibold">Aceite obrigatório de termos (LGPD)</div>
|
||||
<div class="text-surface-400 mt-0.5">Exige que o paciente marque o aceite da política de privacidade antes de finalizar.</div>
|
||||
</div>
|
||||
<InputSwitch v-model="cfg.exigir_aceite_lgpd" />
|
||||
<ToggleSwitch v-model="cfg.exigir_aceite_lgpd" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Auto-reply fora do horário (CRM Grupo 2.3)
|
||||
|--------------------------------------------------------------------------
|
||||
| Configurações de resposta automática quando paciente manda mensagem fora
|
||||
| do horário de atendimento.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useAutoReplySettings } from '@/composables/useAutoReplySettings';
|
||||
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
const api = useAutoReplySettings();
|
||||
|
||||
const DIAS = [
|
||||
{ dow: 0, label: 'Dom' },
|
||||
{ dow: 1, label: 'Seg' },
|
||||
{ dow: 2, label: 'Ter' },
|
||||
{ dow: 3, label: 'Qua' },
|
||||
{ dow: 4, label: 'Qui' },
|
||||
{ dow: 5, label: 'Sex' },
|
||||
{ dow: 6, label: 'Sáb' }
|
||||
];
|
||||
|
||||
const agendaWindows = ref([]);
|
||||
|
||||
// ── Preview do status atual ─────────────────────────────────
|
||||
const now = ref(new Date());
|
||||
let _tick = null;
|
||||
|
||||
const currentWindows = computed(() => {
|
||||
if (api.settings.value.schedule_mode === 'agenda') return agendaWindows.value;
|
||||
if (api.settings.value.schedule_mode === 'business_hours') return api.settings.value.business_hours || [];
|
||||
if (api.settings.value.schedule_mode === 'custom') return api.settings.value.custom_window || [];
|
||||
return [];
|
||||
});
|
||||
|
||||
function hhmmToMin(s) {
|
||||
const m = String(s || '').match(/^(\d{1,2}):(\d{2})/);
|
||||
return m ? parseInt(m[1], 10) * 60 + parseInt(m[2], 10) : -1;
|
||||
}
|
||||
|
||||
const isWithinHoursNow = computed(() => {
|
||||
const d = now.value;
|
||||
// Hora de São Paulo
|
||||
const fmt = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'America/Sao_Paulo',
|
||||
weekday: 'short',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false
|
||||
});
|
||||
const parts = fmt.formatToParts(d);
|
||||
const weekday = parts.find((p) => p.type === 'weekday')?.value || 'Sun';
|
||||
const h = parseInt(parts.find((p) => p.type === 'hour')?.value || '0', 10);
|
||||
const mm = parseInt(parts.find((p) => p.type === 'minute')?.value || '0', 10);
|
||||
const dowMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
||||
const dow = dowMap[weekday] ?? 0;
|
||||
const mins = h * 60 + mm;
|
||||
for (const w of currentWindows.value) {
|
||||
if (w.dow !== dow) continue;
|
||||
const s = hhmmToMin(w.start);
|
||||
const e = hhmmToMin(w.end);
|
||||
if (s < 0 || e < 0) continue;
|
||||
if (mins >= s && mins < e) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const nowLabel = computed(() => {
|
||||
return new Intl.DateTimeFormat('pt-BR', {
|
||||
timeZone: 'America/Sao_Paulo',
|
||||
weekday: 'long',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(now.value);
|
||||
});
|
||||
|
||||
// ── Editor de janelas (business_hours / custom_window) ──────
|
||||
function targetArrayKey() {
|
||||
if (api.settings.value.schedule_mode === 'business_hours') return 'business_hours';
|
||||
if (api.settings.value.schedule_mode === 'custom') return 'custom_window';
|
||||
return null;
|
||||
}
|
||||
|
||||
function addWindow(dow) {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
const arr = [...(api.settings.value[key] || [])];
|
||||
arr.push({ dow, start: '08:00', end: '18:00' });
|
||||
arr.sort((a, b) => a.dow - b.dow || hhmmToMin(a.start) - hhmmToMin(b.start));
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function updateWindow(idx, patch) {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
const arr = [...(api.settings.value[key] || [])];
|
||||
arr[idx] = { ...arr[idx], ...patch };
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function removeWindow(idx) {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
const arr = [...(api.settings.value[key] || [])];
|
||||
arr.splice(idx, 1);
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function applyDefaultWindow() {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
// Seg-Sex 09h-18h
|
||||
const arr = [1, 2, 3, 4, 5].map((dow) => ({ dow, start: '09:00', end: '18:00' }));
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function clearWindows() {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
api.settings.value = { ...api.settings.value, [key]: [] };
|
||||
}
|
||||
|
||||
const editableWindows = computed(() => {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return [];
|
||||
return api.settings.value[key] || [];
|
||||
});
|
||||
|
||||
// ── Ações ───────────────────────────────────────────────────
|
||||
async function onSave() {
|
||||
const res = await api.save();
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Salvo', life: 2000 });
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAgenda() {
|
||||
agendaWindows.value = await api.loadAgendaWindows();
|
||||
}
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────
|
||||
onMounted(async () => {
|
||||
await Promise.all([api.load(), refreshAgenda()]);
|
||||
_tick = setInterval(() => { now.value = new Date(); }, 30000);
|
||||
});
|
||||
|
||||
watch(() => tenantStore.activeTenantId, async () => {
|
||||
await Promise.all([api.load(), refreshAgenda()]);
|
||||
});
|
||||
|
||||
import { onBeforeUnmount } from 'vue';
|
||||
onBeforeUnmount(() => { if (_tick) clearInterval(_tick); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Ações no header do parent -->
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
label="Salvar"
|
||||
icon="pi pi-check"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:loading="api.saving.value"
|
||||
:disabled="api.loading.value"
|
||||
@click="onSave"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="api.loading.value"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="api.load()"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Preview de status atual -->
|
||||
<div
|
||||
class="rounded-md border p-3 flex items-center gap-3"
|
||||
:class="api.settings.value.enabled
|
||||
? (isWithinHoursNow
|
||||
? 'border-green-500/30 bg-green-500/5'
|
||||
: 'border-amber-500/30 bg-amber-500/5')
|
||||
: 'border-[var(--surface-border)] bg-[var(--surface-card)] opacity-80'"
|
||||
>
|
||||
<i
|
||||
class="pi text-lg shrink-0"
|
||||
:class="!api.settings.value.enabled
|
||||
? 'pi-pause-circle text-[var(--text-color-secondary)]'
|
||||
: isWithinHoursNow
|
||||
? 'pi-check-circle text-green-500'
|
||||
: 'pi-bolt text-amber-500'"
|
||||
/>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-sm font-semibold text-[var(--text-color)]">
|
||||
<template v-if="!api.settings.value.enabled">Auto-reply desabilitado</template>
|
||||
<template v-else-if="isWithinHoursNow">Dentro do horário — auto-reply NÃO disparará</template>
|
||||
<template v-else>Fora do horário — auto-reply disparará para novas mensagens</template>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5 capitalize">
|
||||
{{ nowLabel }} · fuso São Paulo
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toggle + mensagem -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<ToggleSwitch v-model="api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">
|
||||
{{ api.settings.value.enabled ? 'Auto-reply ativado' : 'Auto-reply desativado' }}
|
||||
</span>
|
||||
</label>
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">
|
||||
Envia resposta automática quando mensagem chega fora do horário configurado.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Mensagem automática</label>
|
||||
<Textarea
|
||||
v-model="api.settings.value.message"
|
||||
rows="3"
|
||||
autoResize
|
||||
:maxlength="2000"
|
||||
class="w-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] mt-1">
|
||||
{{ (api.settings.value.message || '').length }} / 2000
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">
|
||||
Cooldown por paciente: <span class="text-[var(--text-color)]">{{ api.settings.value.cooldown_minutes }} min</span>
|
||||
</label>
|
||||
<div class="flex flex-col sm:flex-row sm:items-center gap-2">
|
||||
<InputNumber
|
||||
v-model="api.settings.value.cooldown_minutes"
|
||||
:min="0"
|
||||
:max="43200"
|
||||
suffix=" min"
|
||||
inputClass="!w-28"
|
||||
class="shrink-0"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<span class="text-xs text-[var(--text-color-secondary)] flex-1 min-w-0 leading-snug">
|
||||
Tempo mínimo entre auto-replies para a mesma conversa (evita spam). Sugestão: 180 min (3h).
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modo de horário -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-clock text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Quando disparar</span>
|
||||
</div>
|
||||
|
||||
<SelectButton
|
||||
v-model="api.settings.value.schedule_mode"
|
||||
:options="[
|
||||
{ label: 'Seguir minha agenda', value: 'agenda' },
|
||||
{ label: 'Horário de funcionamento', value: 'business_hours' },
|
||||
{ label: 'Personalizado', value: 'custom' }
|
||||
]"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:allowEmpty="false"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">
|
||||
<template v-if="api.settings.value.schedule_mode === 'agenda'">
|
||||
Usa automaticamente os horários da <strong>Agenda</strong> (agenda_regras_semanais) de todos os profissionais ativos do tenant. Se alguém está trabalhando agora, é considerado "dentro do horário".
|
||||
</template>
|
||||
<template v-else-if="api.settings.value.schedule_mode === 'business_hours'">
|
||||
Define um horário geral da clínica, reutilizável por outras automações. Independe das agendas individuais.
|
||||
</template>
|
||||
<template v-else>
|
||||
Define um horário exclusivo para este auto-reply. Útil se você quer que responda antes/depois do expediente normal.
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Preview das janelas do modo 'agenda' (read-only) -->
|
||||
<div v-if="api.settings.value.schedule_mode === 'agenda'" class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)] p-3">
|
||||
<div v-if="!agendaWindows.length" class="text-xs text-[var(--text-color-secondary)] italic">
|
||||
Nenhuma regra semanal ativa encontrada na agenda. Configure em <a href="/configuracoes/agenda" class="text-[var(--primary-color)] underline">Configurações → Agenda</a>.
|
||||
</div>
|
||||
<div v-else class="grid grid-cols-7 gap-1">
|
||||
<div v-for="d in DIAS" :key="d.dow" class="flex flex-col items-center gap-1">
|
||||
<div class="text-[0.7rem] font-semibold text-[var(--text-color-secondary)] uppercase">{{ d.label }}</div>
|
||||
<div class="flex flex-col gap-0.5 w-full">
|
||||
<div
|
||||
v-for="(w, i) in agendaWindows.filter(x => x.dow === d.dow)"
|
||||
:key="i"
|
||||
class="text-[0.65rem] text-center font-mono rounded bg-[var(--primary-color)]/10 text-[var(--primary-color)] px-1 py-0.5"
|
||||
>
|
||||
{{ w.start }}–{{ w.end }}
|
||||
</div>
|
||||
<div v-if="!agendaWindows.some(x => x.dow === d.dow)" class="text-[0.65rem] text-center text-[var(--text-color-secondary)] opacity-40">—</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Editor de janelas (business_hours / custom) -->
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Button
|
||||
label="Aplicar padrão Seg-Sex 09h-18h"
|
||||
icon="pi pi-calendar"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="rounded-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@click="applyDefaultWindow"
|
||||
/>
|
||||
<Button
|
||||
label="Limpar"
|
||||
icon="pi pi-times"
|
||||
size="small"
|
||||
severity="danger"
|
||||
text
|
||||
:disabled="!api.settings.value.enabled || !editableWindows.length"
|
||||
@click="clearWindows"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-7 gap-1.5 border border-[var(--surface-border)] rounded-md bg-[var(--surface-ground)] p-2">
|
||||
<div v-for="d in DIAS" :key="d.dow" class="flex flex-col gap-1 min-h-[80px]">
|
||||
<div class="text-[0.7rem] font-bold text-[var(--text-color-secondary)] uppercase text-center">{{ d.label }}</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div
|
||||
v-for="(w, idx) in editableWindows.map((x, i) => ({ ...x, _idx: i })).filter(x => x.dow === d.dow)"
|
||||
:key="w._idx"
|
||||
class="flex flex-col gap-0.5 bg-[var(--surface-card)] rounded p-1"
|
||||
>
|
||||
<input
|
||||
type="time"
|
||||
:value="w.start"
|
||||
class="text-[0.68rem] px-1 py-0.5 rounded border border-[var(--surface-border)] bg-[var(--surface-card)] w-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@change="(e) => updateWindow(w._idx, { start: e.target.value })"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
:value="w.end"
|
||||
class="text-[0.68rem] px-1 py-0.5 rounded border border-[var(--surface-border)] bg-[var(--surface-card)] w-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@change="(e) => updateWindow(w._idx, { end: e.target.value })"
|
||||
/>
|
||||
<button
|
||||
class="text-[0.6rem] text-red-500 hover:text-red-700 bg-transparent border-0 cursor-pointer p-0 leading-tight"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@click="removeWindow(w._idx)"
|
||||
>
|
||||
<i class="pi pi-times text-[0.55rem]" /> remover
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
class="text-[0.65rem] text-[var(--text-color-secondary)] hover:text-[var(--primary-color)] bg-transparent border border-dashed border-[var(--surface-border)] rounded py-0.5 cursor-pointer"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@click="addWindow(d.dow)"
|
||||
>
|
||||
+ adicionar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Info sobre dependências -->
|
||||
<div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5" />
|
||||
<div>
|
||||
<strong>Pré-requisito:</strong> o WhatsApp do tenant precisa estar conectado em
|
||||
<a href="/configuracoes/whatsapp" class="text-[var(--primary-color)] underline">Configurações → WhatsApp</a>.
|
||||
O auto-reply é enviado via o mesmo canal.
|
||||
<br/>
|
||||
Todas as datas/horas são tratadas no fuso <strong>America/Sao_Paulo</strong>.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,374 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Opt-outs do CRM WhatsApp (LGPD Art. 18 Sec.2)
|
||||
|--------------------------------------------------------------------------
|
||||
| Lista de números que pediram pra não receber mensagens automáticas.
|
||||
| Configuração das palavras-chave de opt-out.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch, reactive } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useConversationOptouts } from '@/composables/useConversationOptouts';
|
||||
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const tenantStore = useTenantStore();
|
||||
const api = useConversationOptouts();
|
||||
|
||||
const activeTab = ref(0);
|
||||
|
||||
// Dialog de adicionar manual
|
||||
const dlg = reactive({ open: false, phone: '', notes: '' });
|
||||
|
||||
function openAddManual() {
|
||||
dlg.open = true;
|
||||
dlg.phone = '';
|
||||
dlg.notes = '';
|
||||
}
|
||||
|
||||
async function saveManual() {
|
||||
const res = await api.addManual({ phone: dlg.phone, notes: dlg.notes.trim() || null });
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Opt-out adicionado', life: 2200 });
|
||||
dlg.open = false;
|
||||
} else if (res.error === 'already_opted_out') {
|
||||
toast.add({ severity: 'warn', summary: 'Já existe', detail: 'Este número já está opted-out ativo.', life: 3500 });
|
||||
} else if (res.error === 'invalid_phone_format') {
|
||||
toast.add({ severity: 'error', summary: 'Telefone inválido', detail: 'Use formato DDD + número (11 dígitos).', life: 3500 });
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRestore(optout) {
|
||||
const label = optout._patient_name || optout.phone;
|
||||
confirm.require({
|
||||
message: `Restaurar ${label}? A pessoa voltará a receber mensagens automáticas.`,
|
||||
header: 'Restaurar opt-out',
|
||||
icon: 'pi pi-undo',
|
||||
acceptLabel: 'Restaurar',
|
||||
rejectLabel: 'Cancelar',
|
||||
accept: async () => {
|
||||
const res = await api.restore(optout.id);
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Restaurado', life: 2000 });
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Keywords
|
||||
const newKeyword = ref('');
|
||||
async function addKw() {
|
||||
const res = await api.addKeyword(newKeyword.value);
|
||||
if (res.ok) {
|
||||
newKeyword.value = '';
|
||||
toast.add({ severity: 'success', summary: 'Keyword adicionada', life: 1800 });
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function onToggleKw(kw, enabled) {
|
||||
const res = await api.toggleKeyword(kw.id, enabled);
|
||||
if (!res.ok) toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
|
||||
function confirmDeleteKw(kw) {
|
||||
confirm.require({
|
||||
message: `Remover keyword "${kw.keyword}"?`,
|
||||
header: 'Remover',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
acceptLabel: 'Remover',
|
||||
rejectLabel: 'Cancelar',
|
||||
accept: async () => {
|
||||
const res = await api.deleteKeyword(kw.id);
|
||||
if (res.ok) toast.add({ severity: 'success', summary: 'Removida', life: 1800 });
|
||||
else toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Helpers
|
||||
function formatPhoneDisplay(phone) {
|
||||
const s = String(phone || '').replace(/\D/g, '');
|
||||
// 55 11 98765-4321
|
||||
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 `+${s}`;
|
||||
}
|
||||
|
||||
function formatDate(iso) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleString('pt-BR', {
|
||||
day: '2-digit', month: '2-digit', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
const quickStats = computed(() => [
|
||||
{ label: 'Ativos', value: api.activeOptouts.value.length, cls: api.activeOptouts.value.length > 0 ? 'qs-warn' : '' },
|
||||
{ label: 'Por keyword', value: api.activeOptouts.value.filter((o) => o.source === 'keyword').length, cls: '' },
|
||||
{ label: 'Adicionados manual', value: api.activeOptouts.value.filter((o) => o.source === 'manual').length, cls: '' },
|
||||
{ label: 'Histórico (restaurados)', value: api.historyOptouts.value.length, cls: '' }
|
||||
]);
|
||||
|
||||
onMounted(() => { api.load(); });
|
||||
watch(() => tenantStore.activeTenantId, () => { api.load(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ConfirmDialog />
|
||||
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
v-if="activeTab === 0"
|
||||
label="Adicionar manualmente"
|
||||
icon="pi pi-plus"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
@click="openAddManual"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="api.loading.value"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="api.load()"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Info LGPD -->
|
||||
<div class="rounded-md border border-amber-500/25 bg-amber-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
|
||||
<i class="pi pi-shield text-amber-500 mt-0.5 text-base" />
|
||||
<div>
|
||||
<strong>LGPD — Direito de oposição (Art. 18, §2):</strong>
|
||||
quando o paciente envia "PARAR" (ou similar), o sistema bloqueia automaticamente envios de auto-reply, lembretes e outras mensagens automáticas.
|
||||
O terapeuta ainda pode escrever manualmente — a relação terapêutica existe.
|
||||
Pra voltar a receber, o paciente envia "VOLTAR".
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Quick stats -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-2">
|
||||
<div
|
||||
v-for="s in quickStats"
|
||||
:key="s.label"
|
||||
class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border transition-colors"
|
||||
:class="s.cls === 'qs-warn' ? 'border-amber-500/25 bg-amber-500/5' : 'border-[var(--surface-border)] bg-[var(--surface-card)]'"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none" :class="s.cls === 'qs-warn' ? 'text-amber-500' : 'text-[var(--text-color)]'">{{ s.value }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabs -->
|
||||
<Tabs :value="activeTab" @update:value="activeTab = $event">
|
||||
<TabList>
|
||||
<Tab :value="0"><i class="pi pi-ban mr-2" />Opt-outs</Tab>
|
||||
<Tab :value="1"><i class="pi pi-key mr-2" />Palavras-chave</Tab>
|
||||
</TabList>
|
||||
|
||||
<TabPanels>
|
||||
<!-- Tab 0: Lista de opt-outs -->
|
||||
<TabPanel :value="0">
|
||||
<div v-if="api.loading.value" class="flex flex-col gap-2 pt-3">
|
||||
<Skeleton v-for="n in 5" :key="n" height="3.5rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!api.optouts.value.length" class="flex flex-col items-center justify-center gap-2 py-12 text-center">
|
||||
<i class="pi pi-check-circle text-4xl text-green-500 opacity-40" />
|
||||
<div class="text-[1rem] font-semibold">Nenhum opt-out ainda</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">Quando um paciente enviar "PARAR" ou similar, aparece aqui.</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-col gap-2 pt-3">
|
||||
<div
|
||||
v-for="o in api.optouts.value"
|
||||
:key="o.id"
|
||||
class="flex items-center gap-3 p-3 rounded-md border transition-all"
|
||||
:class="o.opted_back_in_at
|
||||
? 'border-[var(--surface-border)] bg-[var(--surface-ground)] opacity-70'
|
||||
: 'border-amber-500/30 bg-amber-500/5'"
|
||||
>
|
||||
<i
|
||||
class="pi text-lg shrink-0"
|
||||
:class="o.opted_back_in_at ? 'pi-check-circle text-green-500' : 'pi-ban text-amber-500'"
|
||||
/>
|
||||
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="font-semibold text-[var(--text-color)] truncate">
|
||||
{{ o._patient_name || formatPhoneDisplay(o.phone) }}
|
||||
</span>
|
||||
<span
|
||||
class="inline-flex items-center px-1.5 py-px rounded text-[0.62rem] font-bold uppercase"
|
||||
:class="o.source === 'keyword'
|
||||
? 'bg-indigo-500/10 text-indigo-500'
|
||||
: 'bg-slate-500/10 text-slate-500'"
|
||||
>
|
||||
{{ o.source === 'keyword' ? `Keyword: ${o.keyword_matched}` : 'Manual' }}
|
||||
</span>
|
||||
<span v-if="o.opted_back_in_at" class="inline-flex items-center px-1.5 py-px rounded text-[0.62rem] font-bold uppercase bg-green-500/10 text-green-500">
|
||||
Restaurado
|
||||
</span>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5 flex items-center gap-2 flex-wrap">
|
||||
<span v-if="o._patient_name">{{ formatPhoneDisplay(o.phone) }}</span>
|
||||
<span>·</span>
|
||||
<span>{{ formatDate(o.opted_out_at) }}</span>
|
||||
<span v-if="o.opted_back_in_at">· restaurado em {{ formatDate(o.opted_back_in_at) }}</span>
|
||||
</div>
|
||||
<div v-if="o.original_message" class="text-xs text-[var(--text-color-secondary)] italic mt-1 truncate" :title="o.original_message">
|
||||
"{{ o.original_message }}"
|
||||
</div>
|
||||
<div v-if="o.notes" class="text-xs text-[var(--text-color)] mt-1">{{ o.notes }}</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0">
|
||||
<Button
|
||||
v-if="!o.opted_back_in_at"
|
||||
label="Restaurar"
|
||||
icon="pi pi-undo"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="rounded-full"
|
||||
:loading="api.saving.value"
|
||||
@click="confirmRestore(o)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabPanel>
|
||||
|
||||
<!-- Tab 1: Keywords -->
|
||||
<TabPanel :value="1">
|
||||
<div class="flex flex-col gap-3 pt-3">
|
||||
<!-- Add -->
|
||||
<div class="flex gap-2 items-center">
|
||||
<InputText
|
||||
v-model="newKeyword"
|
||||
placeholder="Adicionar palavra-chave (ex: não quero receber)"
|
||||
class="flex-1"
|
||||
:maxlength="100"
|
||||
@keyup.enter="addKw"
|
||||
/>
|
||||
<Button
|
||||
label="Adicionar"
|
||||
icon="pi pi-plus"
|
||||
:loading="api.saving.value"
|
||||
:disabled="!newKeyword.trim()"
|
||||
@click="addKw"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Lista -->
|
||||
<div v-if="api.loading.value" class="flex flex-col gap-2">
|
||||
<Skeleton v-for="n in 5" :key="n" height="3rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!api.keywords.value.length" class="text-sm text-[var(--text-color-secondary)] italic text-center py-6">
|
||||
Nenhuma palavra-chave ainda.
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-col gap-1.5">
|
||||
<div
|
||||
v-for="kw in api.keywords.value"
|
||||
:key="kw.id"
|
||||
class="flex items-center gap-3 p-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)]"
|
||||
>
|
||||
<i class="pi pi-key text-sm shrink-0" :class="kw.enabled ? 'text-[var(--primary-color)]' : 'text-[var(--text-color-secondary)] opacity-40'" />
|
||||
|
||||
<span class="font-mono text-sm flex-1" :class="!kw.enabled ? 'opacity-50 line-through' : ''">{{ kw.keyword }}</span>
|
||||
|
||||
<span
|
||||
class="inline-flex items-center px-1.5 py-px rounded text-[0.6rem] font-bold uppercase shrink-0"
|
||||
:class="kw.is_system ? 'bg-slate-500/10 text-slate-500' : 'bg-indigo-500/10 text-indigo-500'"
|
||||
>
|
||||
{{ kw.is_system ? 'Sistema' : 'Custom' }}
|
||||
</span>
|
||||
|
||||
<ToggleSwitch
|
||||
:modelValue="kw.enabled"
|
||||
@update:modelValue="(v) => onToggleKw(kw, v)"
|
||||
:disabled="api.saving.value"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-if="!kw.is_system"
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
text
|
||||
class="h-8 w-8"
|
||||
v-tooltip.top="'Remover'"
|
||||
:disabled="api.saving.value"
|
||||
@click="confirmDeleteKw(kw)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-[var(--text-color-secondary)] italic">
|
||||
Palavras-chave do sistema não podem ser removidas, mas podem ser desabilitadas.
|
||||
Match é case-insensitive e ignora acentos. Exemplo: "PARAR", "parar", "PARÁR" todos funcionam.
|
||||
</div>
|
||||
</div>
|
||||
</TabPanel>
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<!-- Dialog adicionar manual -->
|
||||
<Dialog
|
||||
v-model:visible="dlg.open"
|
||||
header="Adicionar opt-out manualmente"
|
||||
modal
|
||||
:style="{ width: 'min(440px, 95vw)' }"
|
||||
:closable="!api.saving.value"
|
||||
>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Telefone (com DDD)</label>
|
||||
<InputText
|
||||
v-model="dlg.phone"
|
||||
placeholder="11987654321"
|
||||
class="w-full"
|
||||
@keydown.enter="saveManual"
|
||||
/>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] mt-1">
|
||||
Só dígitos. DDI 55 é adicionado automaticamente se faltar.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Motivo (opcional)</label>
|
||||
<Textarea
|
||||
v-model="dlg.notes"
|
||||
rows="2"
|
||||
autoResize
|
||||
class="w-full"
|
||||
:maxlength="500"
|
||||
placeholder="Ex: paciente pediu por telefone pra parar de receber"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Cancelar" severity="secondary" text :disabled="api.saving.value" @click="dlg.open = false" />
|
||||
<Button label="Adicionar" :loading="api.saving.value" :disabled="!dlg.phone.trim()" @click="saveManual" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,391 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Tags de Conversa (configurações)
|
||||
|--------------------------------------------------------------------------
|
||||
| CRUD de tags custom. Tags do sistema aparecem em modo leitura.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, reactive, watch } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useConversationTags } from '@/composables/useConversationTags';
|
||||
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const tenantStore = useTenantStore();
|
||||
const tagsApi = useConversationTags();
|
||||
|
||||
// ── Usage count (quantas threads usam cada tag) ──────────────
|
||||
const usageByTag = ref({}); // { [tagId]: count }
|
||||
|
||||
async function loadUsage() {
|
||||
const tenantId = tenantStore.activeTenantId;
|
||||
if (!tenantId) {
|
||||
usageByTag.value = {};
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('conversation_thread_tags')
|
||||
.select('tag_id')
|
||||
.eq('tenant_id', tenantId);
|
||||
if (error) throw error;
|
||||
const counts = {};
|
||||
for (const row of data || []) {
|
||||
counts[row.tag_id] = (counts[row.tag_id] || 0) + 1;
|
||||
}
|
||||
usageByTag.value = counts;
|
||||
} catch (e) {
|
||||
console.error('[ConfiguracoesConversasTags] loadUsage:', e?.message);
|
||||
usageByTag.value = {};
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all([tagsApi.loadAllTags(), loadUsage()]);
|
||||
}
|
||||
|
||||
// ── Quick stats ─────────────────────────────────────────────
|
||||
const quickStats = computed(() => {
|
||||
const all = tagsApi.allTags.value || [];
|
||||
const system = all.filter((t) => t.is_system).length;
|
||||
const custom = all.filter((t) => !t.is_system).length;
|
||||
const emUso = Object.keys(usageByTag.value).length;
|
||||
return [
|
||||
{ label: 'Total de tags', value: all.length, cls: '' },
|
||||
{ label: 'Sistema', value: system, cls: '' },
|
||||
{ label: 'Minhas tags', value: custom, cls: custom > 0 ? 'qs-ok' : '' },
|
||||
{ label: 'Em uso', value: emUso, cls: emUso > 0 ? 'qs-ok' : '' }
|
||||
];
|
||||
});
|
||||
|
||||
// ── Dialog create/edit ──────────────────────────────────────
|
||||
const presetColors = [
|
||||
'#ef4444', '#f97316', '#f59e0b', '#eab308',
|
||||
'#84cc16', '#22c55e', '#14b8a6', '#06b6d4',
|
||||
'#0ea5e9', '#6366f1', '#8b5cf6', '#a855f7',
|
||||
'#ec4899', '#64748b', '#292524'
|
||||
];
|
||||
|
||||
const presetIcons = [
|
||||
{ icon: 'pi pi-tag', label: 'Tag' },
|
||||
{ icon: 'pi pi-exclamation-triangle', label: 'Alerta' },
|
||||
{ icon: 'pi pi-exclamation-circle', label: 'Exclamação' },
|
||||
{ icon: 'pi pi-info-circle', label: 'Info' },
|
||||
{ icon: 'pi pi-check-circle', label: 'Check' },
|
||||
{ icon: 'pi pi-star', label: 'Estrela' },
|
||||
{ icon: 'pi pi-heart', label: 'Coração' },
|
||||
{ icon: 'pi pi-flag', label: 'Bandeira' },
|
||||
{ icon: 'pi pi-bookmark', label: 'Marcador' },
|
||||
{ icon: 'pi pi-user', label: 'Usuário' },
|
||||
{ icon: 'pi pi-user-plus', label: 'Novo usuário' },
|
||||
{ icon: 'pi pi-users', label: 'Grupo' },
|
||||
{ icon: 'pi pi-calendar', label: 'Calendário' },
|
||||
{ icon: 'pi pi-calendar-times', label: 'Calendário cancelado' },
|
||||
{ icon: 'pi pi-clock', label: 'Relógio' },
|
||||
{ icon: 'pi pi-phone', label: 'Telefone' },
|
||||
{ icon: 'pi pi-comment', label: 'Balão' },
|
||||
{ icon: 'pi pi-whatsapp', label: 'WhatsApp' },
|
||||
{ icon: 'pi pi-envelope', label: 'Envelope' },
|
||||
{ icon: 'pi pi-send', label: 'Enviar' },
|
||||
{ icon: 'pi pi-reply', label: 'Responder' },
|
||||
{ icon: 'pi pi-bolt', label: 'Raio' },
|
||||
{ icon: 'pi pi-dollar', label: 'Dinheiro' },
|
||||
{ icon: 'pi pi-shield', label: 'Escudo' }
|
||||
];
|
||||
|
||||
const dlg = reactive({
|
||||
open: false,
|
||||
mode: 'create',
|
||||
id: '',
|
||||
name: '',
|
||||
color: '#6366f1',
|
||||
icon: 'pi pi-tag'
|
||||
});
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(dlg, {
|
||||
open: true,
|
||||
mode: 'create',
|
||||
id: '',
|
||||
name: '',
|
||||
color: '#6366f1',
|
||||
icon: 'pi pi-tag'
|
||||
});
|
||||
}
|
||||
|
||||
function openEdit(tag) {
|
||||
Object.assign(dlg, {
|
||||
open: true,
|
||||
mode: 'edit',
|
||||
id: tag.id,
|
||||
name: tag.name,
|
||||
color: tag.color,
|
||||
icon: tag.icon || 'pi pi-tag'
|
||||
});
|
||||
}
|
||||
|
||||
async function saveTag() {
|
||||
const clean = (dlg.name || '').trim();
|
||||
if (!clean) {
|
||||
toast.add({ severity: 'warn', summary: 'Nome obrigatório', life: 2500 });
|
||||
return;
|
||||
}
|
||||
let res;
|
||||
if (dlg.mode === 'create') {
|
||||
res = await tagsApi.createCustomTag({ name: clean, color: dlg.color, icon: dlg.icon });
|
||||
} else {
|
||||
res = await tagsApi.updateCustomTag(dlg.id, { name: clean, color: dlg.color, icon: dlg.icon });
|
||||
}
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: dlg.mode === 'create' ? 'Tag criada' : 'Tag atualizada', life: 2000 });
|
||||
dlg.open = false;
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error || 'Falha ao salvar', life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDelete(tag) {
|
||||
const usage = usageByTag.value[tag.id] || 0;
|
||||
const msg = usage > 0
|
||||
? `A tag "${tag.name}" está aplicada em ${usage} conversa${usage > 1 ? 's' : ''}. Ao remover, ela sai de todas. Continuar?`
|
||||
: `Remover a tag "${tag.name}"?`;
|
||||
confirm.require({
|
||||
message: msg,
|
||||
header: 'Remover tag',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: 'Remover',
|
||||
rejectLabel: 'Cancelar',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: async () => {
|
||||
const res = await tagsApi.deleteCustomTag(tag.id);
|
||||
if (res.ok) {
|
||||
await loadUsage();
|
||||
toast.add({ severity: 'success', summary: 'Tag removida', life: 2000 });
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────
|
||||
onMounted(() => { refresh(); });
|
||||
|
||||
watch(() => tenantStore.activeTenantId, () => { refresh(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ConfirmDialog />
|
||||
|
||||
<!-- Botões teleportados pro header do ConfiguracoesPage -->
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
label="Nova tag"
|
||||
icon="pi pi-plus"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
@click="openCreate"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="tagsApi.loading.value"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="refresh"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
|
||||
<!-- Quick stats -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-2">
|
||||
<template v-if="tagsApi.loading.value">
|
||||
<Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="s in quickStats"
|
||||
:key="s.label"
|
||||
class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border transition-colors"
|
||||
:class="[
|
||||
s.cls === 'qs-ok'
|
||||
? 'border-green-500/25 bg-green-500/5'
|
||||
: 'border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)]'
|
||||
]"
|
||||
>
|
||||
<div class="text-[1.35rem] font-bold leading-none" :class="s.cls === 'qs-ok' ? 'text-green-500' : 'text-[var(--text-color)]'">{{ s.value }}</div>
|
||||
<div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Lista de tags -->
|
||||
<div>
|
||||
<div v-if="tagsApi.loading.value" class="flex flex-col gap-2">
|
||||
<Skeleton v-for="n in 6" :key="n" height="4rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!tagsApi.allTags.value.length" class="flex flex-col items-center justify-center gap-2 py-12 text-center">
|
||||
<i class="pi pi-tag text-4xl text-[var(--text-color-secondary)] opacity-40" />
|
||||
<div class="text-[1rem] font-semibold">Nenhuma tag ainda</div>
|
||||
<Button label="Criar primeira tag" icon="pi pi-plus" size="small" @click="openCreate" />
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="tag in tagsApi.allTags.value"
|
||||
:key="tag.id"
|
||||
class="flex items-center gap-3 p-3 rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] hover:border-indigo-300/50 hover:shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all"
|
||||
>
|
||||
<!-- Preview da pill -->
|
||||
<span
|
||||
class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[0.78rem] font-semibold shrink-0"
|
||||
:style="{
|
||||
background: tag.color + '20',
|
||||
color: tag.color,
|
||||
border: `1px solid ${tag.color}40`
|
||||
}"
|
||||
>
|
||||
<i v-if="tag.icon" :class="tag.icon" class="text-[0.7rem]" />
|
||||
{{ tag.name }}
|
||||
</span>
|
||||
|
||||
<div class="flex-1 min-w-0 flex flex-col">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-xs font-mono text-[var(--text-color-secondary)]">{{ tag.slug }}</span>
|
||||
<span
|
||||
v-if="tag.is_system"
|
||||
class="inline-flex items-center px-1.5 py-px rounded text-[0.65rem] font-bold uppercase tracking-wide bg-slate-500/10 text-slate-500"
|
||||
>
|
||||
Sistema
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex items-center px-1.5 py-px rounded text-[0.65rem] font-bold uppercase tracking-wide bg-indigo-500/10 text-indigo-500"
|
||||
>
|
||||
Custom
|
||||
</span>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">
|
||||
<span v-if="usageByTag[tag.id]">
|
||||
Em {{ usageByTag[tag.id] }} conversa{{ usageByTag[tag.id] > 1 ? 's' : '' }}
|
||||
</span>
|
||||
<span v-else class="italic opacity-60">Não utilizada</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-1 shrink-0">
|
||||
<Button
|
||||
v-if="!tag.is_system"
|
||||
icon="pi pi-pencil"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-8 w-8 rounded-full"
|
||||
v-tooltip.top="'Editar'"
|
||||
:disabled="tagsApi.saving.value"
|
||||
@click="openEdit(tag)"
|
||||
/>
|
||||
<Button
|
||||
v-if="!tag.is_system"
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
outlined
|
||||
class="h-8 w-8 rounded-full"
|
||||
v-tooltip.top="'Remover'"
|
||||
:disabled="tagsApi.saving.value"
|
||||
@click="confirmDelete(tag)"
|
||||
/>
|
||||
<span v-if="tag.is_system" class="text-[0.7rem] text-[var(--text-color-secondary)] italic opacity-60 px-2">
|
||||
bloqueada
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div><!-- /flex flex-col gap-3 wrapper -->
|
||||
|
||||
<!-- Dialog create/edit -->
|
||||
<Dialog
|
||||
v-model:visible="dlg.open"
|
||||
:header="dlg.mode === 'create' ? 'Nova tag' : 'Editar tag'"
|
||||
modal
|
||||
:style="{ width: 'min(460px, 95vw)' }"
|
||||
:closable="!tagsApi.saving.value"
|
||||
>
|
||||
<div class="flex flex-col gap-3">
|
||||
<!-- Preview -->
|
||||
<div class="flex items-center justify-center py-3 bg-[var(--surface-ground)] rounded-md">
|
||||
<span
|
||||
class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold"
|
||||
:style="{
|
||||
background: dlg.color + '20',
|
||||
color: dlg.color,
|
||||
border: `1px solid ${dlg.color}40`
|
||||
}"
|
||||
>
|
||||
<i v-if="dlg.icon" :class="dlg.icon" class="text-xs" />
|
||||
{{ dlg.name.trim() || 'Preview' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Nome -->
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Nome</label>
|
||||
<InputText v-model="dlg.name" placeholder="Ex: Aguardando confirmação" :maxlength="40" class="w-full" @keydown.enter="saveTag" />
|
||||
</div>
|
||||
|
||||
<!-- Cor -->
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Cor</label>
|
||||
<div class="flex items-center flex-wrap gap-1.5">
|
||||
<button
|
||||
v-for="c in presetColors"
|
||||
:key="c"
|
||||
type="button"
|
||||
class="w-7 h-7 rounded-full border-2 transition-transform cursor-pointer"
|
||||
:class="dlg.color === c ? 'border-[var(--text-color)] scale-110' : 'border-transparent hover:scale-105'"
|
||||
:style="{ background: c }"
|
||||
:aria-label="c"
|
||||
@click="dlg.color = c"
|
||||
/>
|
||||
<input
|
||||
type="color"
|
||||
v-model="dlg.color"
|
||||
class="w-7 h-7 rounded-full border-0 cursor-pointer"
|
||||
aria-label="Cor personalizada"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ícone -->
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Ícone</label>
|
||||
<div class="grid grid-cols-8 gap-1 max-h-[180px] overflow-y-auto pr-1 border border-[var(--surface-border)] rounded-md p-2 bg-[var(--surface-ground)]">
|
||||
<button
|
||||
v-for="p in presetIcons"
|
||||
:key="p.icon"
|
||||
type="button"
|
||||
class="w-9 h-9 rounded-md flex items-center justify-center bg-transparent border cursor-pointer transition-all hover:scale-105"
|
||||
:class="dlg.icon === p.icon ? 'border-[var(--primary-color)] bg-[var(--primary-color)]/10 text-[var(--primary-color)]' : 'border-[var(--surface-border)] text-[var(--text-color-secondary)]'"
|
||||
v-tooltip.top="p.label"
|
||||
@click="dlg.icon = p.icon"
|
||||
>
|
||||
<i :class="p.icon" class="text-sm" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Cancelar" severity="secondary" text :disabled="tagsApi.saving.value" @click="dlg.open = false" />
|
||||
<Button :label="dlg.mode === 'create' ? 'Criar' : 'Salvar'" :loading="tagsApi.saving.value" :disabled="!dlg.name.trim()" @click="saveTag" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,425 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Créditos WhatsApp (Marco B)
|
||||
|--------------------------------------------------------------------------
|
||||
| Saldo + loja de pacotes + histórico de compras e uso.
|
||||
| Créditos são consumidos apenas no canal Oficial AgenciaPSI (Twilio);
|
||||
| WhatsApp Pessoal (Evolution) é gratuito.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch, reactive } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useWhatsappCredits } from '@/composables/useWhatsappCredits';
|
||||
import { isValidCPF, fmtCPF, isValidCNPJ, fmtCNPJ } from '@/utils/validators';
|
||||
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
const api = useWhatsappCredits();
|
||||
|
||||
// Dialog de confirmação (coleta CPF/CNPJ antes de criar a cobrança)
|
||||
const confirmDlg = reactive({
|
||||
open: false,
|
||||
pkg: null,
|
||||
docInput: '',
|
||||
error: ''
|
||||
});
|
||||
|
||||
// Dialog de pagamento PIX
|
||||
const pixDlg = reactive({
|
||||
open: false,
|
||||
purchase: null,
|
||||
});
|
||||
|
||||
function formatDoc(digits) {
|
||||
const d = String(digits || '').replace(/\D/g, '');
|
||||
if (d.length === 11) return fmtCPF(d);
|
||||
if (d.length === 14) return fmtCNPJ(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
function validateDoc(raw) {
|
||||
const d = String(raw || '').replace(/\D/g, '');
|
||||
if (!d) return { ok: false, error: 'Informe o CPF ou CNPJ do titular.' };
|
||||
if (d.length === 11) {
|
||||
if (!isValidCPF(d)) return { ok: false, error: 'CPF inválido. Confira os dígitos.' };
|
||||
return { ok: true, digits: d };
|
||||
}
|
||||
if (d.length === 14) {
|
||||
if (!isValidCNPJ(d)) return { ok: false, error: 'CNPJ inválido. Confira os dígitos.' };
|
||||
return { ok: true, digits: d };
|
||||
}
|
||||
return { ok: false, error: 'Informe 11 dígitos (CPF) ou 14 (CNPJ).' };
|
||||
}
|
||||
|
||||
function openConfirm(pkg) {
|
||||
confirmDlg.pkg = pkg;
|
||||
confirmDlg.docInput = formatDoc(api.tenantCpfCnpj.value);
|
||||
confirmDlg.error = '';
|
||||
confirmDlg.open = true;
|
||||
}
|
||||
|
||||
async function onConfirmBuy() {
|
||||
const v = validateDoc(confirmDlg.docInput);
|
||||
if (!v.ok) { confirmDlg.error = v.error; return; }
|
||||
confirmDlg.error = '';
|
||||
|
||||
const res = await api.createPurchase(confirmDlg.pkg.id, v.digits);
|
||||
if (!res.ok) {
|
||||
const msg = res.message
|
||||
|| (res.error?.includes('não configurado')
|
||||
? 'Sistema de pagamento não está configurado. Contate o suporte.'
|
||||
: res.error || 'Falha ao criar cobrança');
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: msg, life: 5000 });
|
||||
return;
|
||||
}
|
||||
confirmDlg.open = false;
|
||||
pixDlg.purchase = res.purchase;
|
||||
pixDlg.open = true;
|
||||
}
|
||||
|
||||
function copyPix() {
|
||||
const code = pixDlg.purchase?.asaas_pix_copy_paste;
|
||||
if (!code) return;
|
||||
navigator.clipboard.writeText(code).then(
|
||||
() => toast.add({ severity: 'success', summary: 'Código copiado', life: 1800 }),
|
||||
() => toast.add({ severity: 'error', summary: 'Falha ao copiar', life: 2500 })
|
||||
);
|
||||
}
|
||||
|
||||
// Threshold edit
|
||||
const editingThreshold = ref(false);
|
||||
const thresholdInput = ref(20);
|
||||
|
||||
function startEditThreshold() {
|
||||
thresholdInput.value = api.balance.value?.low_balance_threshold ?? 20;
|
||||
editingThreshold.value = true;
|
||||
}
|
||||
|
||||
async function saveThreshold() {
|
||||
const res = await api.updateLowBalanceThreshold(thresholdInput.value);
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Alerta atualizado', life: 2000 });
|
||||
editingThreshold.value = false;
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Formatters
|
||||
function brl(v) {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(Number(v) || 0);
|
||||
}
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
const kindLabel = {
|
||||
purchase: { label: 'Compra', icon: 'pi pi-shopping-cart', cls: 'text-green-500' },
|
||||
topup_manual: { label: 'Topup manual', icon: 'pi pi-plus-circle', cls: 'text-sky-500' },
|
||||
usage: { label: 'Uso', icon: 'pi pi-send', cls: 'text-orange-500' },
|
||||
refund: { label: 'Estorno', icon: 'pi pi-replay', cls: 'text-amber-500' },
|
||||
adjustment: { label: 'Ajuste', icon: 'pi pi-pencil', cls: 'text-slate-500' }
|
||||
};
|
||||
|
||||
const statusLabel = {
|
||||
pending: { label: 'Aguardando pagamento', cls: 'bg-amber-500/10 text-amber-600' },
|
||||
paid: { label: 'Pago', cls: 'bg-green-500/10 text-green-600' },
|
||||
failed: { label: 'Falhou', cls: 'bg-red-500/10 text-red-600' },
|
||||
expired: { label: 'Expirado', cls: 'bg-slate-500/10 text-slate-600' },
|
||||
cancelled: { label: 'Cancelado', cls: 'bg-slate-500/10 text-slate-600' },
|
||||
refunded: { label: 'Estornado', cls: 'bg-orange-500/10 text-orange-600' }
|
||||
};
|
||||
|
||||
const pendingPurchases = computed(() => api.purchases.value.filter((p) => p.status === 'pending'));
|
||||
|
||||
function reopenPixDialog(purchase) {
|
||||
pixDlg.purchase = purchase;
|
||||
pixDlg.open = true;
|
||||
}
|
||||
|
||||
onMounted(() => { api.loadAll(); });
|
||||
watch(() => tenantStore.activeTenantId, () => { api.loadAll(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="api.loading.value"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="api.loadAll()"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Saldo atual -->
|
||||
<div
|
||||
class="rounded-md border p-4 flex items-center gap-4 flex-wrap"
|
||||
:class="api.isLow.value && api.currentBalance.value > 0
|
||||
? 'border-amber-500/30 bg-amber-500/5'
|
||||
: api.currentBalance.value === 0
|
||||
? 'border-red-500/30 bg-red-500/5'
|
||||
: 'border-emerald-500/25 bg-emerald-500/5'"
|
||||
>
|
||||
<div class="grid place-items-center w-14 h-14 rounded-md shrink-0" :class="api.currentBalance.value === 0 ? 'bg-red-500/10 text-red-500' : api.isLow.value ? 'bg-amber-500/10 text-amber-500' : 'bg-emerald-500/10 text-emerald-500'">
|
||||
<i class="pi pi-credit-card text-2xl" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-xs uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Saldo atual</div>
|
||||
<div class="text-3xl font-bold leading-tight">
|
||||
<template v-if="api.loading.value && !api.balance.value">
|
||||
<Skeleton width="8rem" height="2rem" />
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ api.currentBalance.value }} <span class="text-base font-normal text-[var(--text-color-secondary)]">créditos</span>
|
||||
</template>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
<span v-if="api.balance.value">
|
||||
Comprados: <strong>{{ api.balance.value.lifetime_purchased || 0 }}</strong>
|
||||
· Usados: <strong>{{ api.balance.value.lifetime_used || 0 }}</strong>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<template v-if="!editingThreshold">
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">
|
||||
Alerta abaixo de <strong>{{ api.balance.value?.low_balance_threshold ?? 20 }}</strong>
|
||||
</span>
|
||||
<Button icon="pi pi-pencil" severity="secondary" text size="small" class="h-7 w-7" v-tooltip.top="'Editar'" @click="startEditThreshold" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<InputNumber v-model="thresholdInput" :min="0" :max="10000" inputClass="!w-20 text-xs" />
|
||||
<Button icon="pi pi-check" size="small" severity="primary" class="h-7 w-7" @click="saveThreshold" />
|
||||
<Button icon="pi pi-times" severity="secondary" text size="small" class="h-7 w-7" @click="editingThreshold = false" />
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Info: só Oficial consome -->
|
||||
<div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5" />
|
||||
<div>
|
||||
Créditos são consumidos apenas no canal <strong>WhatsApp Oficial AgenciaPSI</strong>. O <strong>WhatsApp Pessoal</strong> (via QR code) é gratuito mas tem limitações (celular precisa estar ligado, sem SLA, risco de ban).
|
||||
<br/>
|
||||
<strong>1 crédito = 1 mensagem enviada.</strong> Mensagens recebidas não consomem. Saldo não expira.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ordens pendentes (CTA pra pagar) -->
|
||||
<div v-if="pendingPurchases.length" class="rounded-md border border-amber-500/30 bg-amber-500/5 p-4">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<i class="pi pi-clock text-amber-500" />
|
||||
<span class="text-sm font-bold">{{ pendingPurchases.length }} cobrança{{ pendingPurchases.length > 1 ? 's' : '' }} aguardando pagamento</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<div v-for="p in pendingPurchases" :key="p.id" class="flex items-center justify-between gap-2 p-2 rounded bg-[var(--surface-card)] text-sm">
|
||||
<span class="truncate">{{ p.package_name }} — {{ p.credits }} créditos · {{ brl(p.amount_brl) }}</span>
|
||||
<Button label="Pagar" icon="pi pi-qrcode" size="small" class="rounded-full" @click="reopenPixDialog(p)" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loja de pacotes -->
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-shopping-cart text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Comprar créditos</span>
|
||||
</div>
|
||||
|
||||
<div v-if="api.loading.value && !api.packages.value.length" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
|
||||
<Skeleton v-for="n in 4" :key="n" height="12rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!api.packages.value.length" class="text-center py-8 text-sm text-[var(--text-color-secondary)] italic">
|
||||
Nenhum pacote disponível no momento. Contate o suporte.
|
||||
</div>
|
||||
|
||||
<div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
|
||||
<div
|
||||
v-for="pkg in api.packages.value"
|
||||
:key="pkg.id"
|
||||
class="relative flex flex-col gap-3 p-4 rounded-md border-2 bg-[var(--surface-card)] transition-all hover:shadow-md"
|
||||
:class="pkg.is_featured ? 'border-emerald-500 shadow-[0_0_0_3px_rgba(34,197,94,0.1)]' : 'border-[var(--surface-border)] hover:border-indigo-300'"
|
||||
>
|
||||
<span v-if="pkg.is_featured" class="absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[0.6rem] font-bold uppercase tracking-wide bg-emerald-500 text-white">
|
||||
⭐ Mais vendido
|
||||
</span>
|
||||
<div class="text-sm font-bold text-[var(--text-color)]">{{ pkg.name }}</div>
|
||||
<div v-if="pkg.description" class="text-xs text-[var(--text-color-secondary)]">{{ pkg.description }}</div>
|
||||
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<div class="text-[1.6rem] font-bold leading-none text-[var(--primary-color)]">{{ pkg.credits }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">mensagens</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-0.5 mt-auto">
|
||||
<div class="text-2xl font-bold">{{ brl(pkg.price_brl) }}</div>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)]">{{ brl(pkg.price_brl / pkg.credits) }} / mensagem</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
label="Comprar"
|
||||
icon="pi pi-shopping-cart"
|
||||
:severity="pkg.is_featured ? 'primary' : 'secondary'"
|
||||
:outlined="!pkg.is_featured"
|
||||
class="rounded-full"
|
||||
:loading="api.creating.value"
|
||||
@click="openConfirm(pkg)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Histórico de compras -->
|
||||
<div v-if="api.purchases.value.length" class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2 mb-1">
|
||||
<i class="pi pi-receipt text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Histórico de compras</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5 max-h-[360px] overflow-y-auto">
|
||||
<div
|
||||
v-for="p in api.purchases.value"
|
||||
:key="p.id"
|
||||
class="flex items-center gap-2 p-2 rounded-md border border-[var(--surface-border)] text-sm"
|
||||
>
|
||||
<span class="inline-flex items-center px-1.5 py-px rounded text-[0.65rem] font-bold uppercase shrink-0" :class="statusLabel[p.status]?.cls">
|
||||
{{ statusLabel[p.status]?.label || p.status }}
|
||||
</span>
|
||||
<span class="flex-1 truncate">{{ p.package_name }} — {{ p.credits }} créditos</span>
|
||||
<span class="font-semibold">{{ brl(p.amount_brl) }}</span>
|
||||
<span class="text-xs text-[var(--text-color-secondary)] shrink-0">{{ fmtDate(p.paid_at || p.created_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Extrato -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2 mb-1">
|
||||
<i class="pi pi-list text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Extrato (50 últimos)</span>
|
||||
</div>
|
||||
<div v-if="!api.transactions.value.length" class="text-xs text-[var(--text-color-secondary)] italic text-center py-4">
|
||||
Nenhuma transação ainda.
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-0.5 max-h-[300px] overflow-y-auto text-xs">
|
||||
<div
|
||||
v-for="tx in api.transactions.value"
|
||||
:key="tx.id"
|
||||
class="grid grid-cols-[auto_1fr_auto_auto] items-center gap-2 py-1.5 px-2 rounded hover:bg-[var(--surface-hover)]"
|
||||
>
|
||||
<i :class="[kindLabel[tx.kind]?.icon || 'pi pi-circle', kindLabel[tx.kind]?.cls || '']" />
|
||||
<span>{{ kindLabel[tx.kind]?.label || tx.kind }}<span v-if="tx.note" class="ml-1 text-[var(--text-color-secondary)]">— {{ tx.note }}</span></span>
|
||||
<span class="font-bold font-mono" :class="tx.amount > 0 ? 'text-green-600' : 'text-orange-600'">
|
||||
{{ tx.amount > 0 ? '+' : '' }}{{ tx.amount }}
|
||||
</span>
|
||||
<span class="text-[var(--text-color-secondary)]">{{ fmtDate(tx.created_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dialog de confirmação (CPF/CNPJ + resumo) -->
|
||||
<Dialog
|
||||
v-model:visible="confirmDlg.open"
|
||||
:header="`Comprar ${confirmDlg.pkg?.name || 'pacote'}`"
|
||||
modal
|
||||
:style="{ width: 'min(440px, 95vw)' }"
|
||||
@hide="confirmDlg.error = ''"
|
||||
>
|
||||
<div v-if="confirmDlg.pkg" class="flex flex-col gap-3">
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)] p-3 flex items-center justify-between">
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs uppercase tracking-wide text-[var(--text-color-secondary)] font-semibold">{{ confirmDlg.pkg.name }}</span>
|
||||
<span class="text-sm">{{ confirmDlg.pkg.credits }} créditos (mensagens WhatsApp)</span>
|
||||
</div>
|
||||
<span class="text-xl font-bold text-[var(--primary-color)]">{{ brl(confirmDlg.pkg.price_brl) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">
|
||||
CPF ou CNPJ do titular <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<InputText
|
||||
v-model="confirmDlg.docInput"
|
||||
placeholder="000.000.000-00"
|
||||
:invalid="!!confirmDlg.error"
|
||||
@input="confirmDlg.error = ''"
|
||||
@blur="confirmDlg.docInput = formatDoc(confirmDlg.docInput)"
|
||||
@keydown.enter="onConfirmBuy"
|
||||
maxlength="20"
|
||||
/>
|
||||
<small v-if="confirmDlg.error" class="text-red-500">{{ confirmDlg.error }}</small>
|
||||
<small v-else class="text-[var(--text-color-secondary)]">
|
||||
Exigido pelo gateway (Asaas). Fica salvo no seu tenant pras próximas compras.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="rounded-md bg-[var(--surface-ground)] p-2 text-xs text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-info-circle mr-1 text-sky-500" />
|
||||
Ao confirmar, geramos um QR Code PIX. Os créditos aparecem automaticamente após o pagamento (poucos segundos).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Cancelar" severity="secondary" text @click="confirmDlg.open = false" />
|
||||
<Button
|
||||
label="Gerar cobrança PIX"
|
||||
icon="pi pi-qrcode"
|
||||
:loading="api.creating.value"
|
||||
@click="onConfirmBuy"
|
||||
/>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<!-- Dialog PIX -->
|
||||
<Dialog
|
||||
v-model:visible="pixDlg.open"
|
||||
header="Pagamento PIX"
|
||||
modal
|
||||
:style="{ width: 'min(420px, 95vw)' }"
|
||||
>
|
||||
<div v-if="pixDlg.purchase" class="flex flex-col gap-3">
|
||||
<div class="text-center">
|
||||
<div class="text-xs uppercase text-[var(--text-color-secondary)] font-semibold tracking-wide mb-1">Valor total</div>
|
||||
<div class="text-3xl font-bold text-[var(--primary-color)]">{{ brl(pixDlg.purchase.amount_brl) }}</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">{{ pixDlg.purchase.package_name }} · {{ pixDlg.purchase.credits }} créditos</div>
|
||||
</div>
|
||||
|
||||
<div v-if="pixDlg.purchase.asaas_pix_qrcode" class="flex flex-col items-center gap-2">
|
||||
<img :src="`data:image/png;base64,${pixDlg.purchase.asaas_pix_qrcode}`" alt="QR Code PIX" class="w-48 h-48 rounded-md border border-[var(--surface-border)]" />
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">Aponte a câmera do banco pro QR Code</span>
|
||||
</div>
|
||||
|
||||
<div v-if="pixDlg.purchase.asaas_pix_copy_paste" class="flex flex-col gap-1">
|
||||
<span class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">Ou copie o código PIX</span>
|
||||
<div class="flex gap-1">
|
||||
<InputText :modelValue="pixDlg.purchase.asaas_pix_copy_paste" readonly class="flex-1 text-xs font-mono" />
|
||||
<Button icon="pi pi-copy" severity="secondary" outlined v-tooltip.top="'Copiar'" @click="copyPix" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="pixDlg.purchase.asaas_payment_link" class="text-center">
|
||||
<a :href="pixDlg.purchase.asaas_payment_link" target="_blank" rel="noopener" class="text-xs text-[var(--primary-color)] underline">
|
||||
Ou pague com cartão (link externo)
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="rounded-md bg-[var(--surface-ground)] p-2 text-xs text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-info-circle mr-1 text-sky-500" />
|
||||
Assim que o pagamento for confirmado (PIX é instantâneo), seu saldo é atualizado automaticamente. Pode fechar essa janela — a confirmação aparece aqui quando concluída.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Fechar" severity="secondary" text @click="pixDlg.open = false" />
|
||||
<Button label="Já paguei, atualizar" icon="pi pi-refresh" @click="api.loadAll(); pixDlg.open = false;" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,348 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Lembretes automáticos de sessão (CRM Grupo 2.4)
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useSessionReminders } from '@/composables/useSessionReminders';
|
||||
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
const api = useSessionReminders();
|
||||
|
||||
const VARIABLES = [
|
||||
{ key: '{{nome_paciente}}', label: 'Nome do paciente' },
|
||||
{ key: '{{data_sessao}}', label: 'Data (ex: 22 de abril)' },
|
||||
{ key: '{{hora_sessao}}', label: 'Hora (ex: 14:30)' },
|
||||
{ key: '{{modalidade}}', label: 'Online / presencial' },
|
||||
{ key: '{{nome_clinica}}', label: 'Nome da clínica' }
|
||||
];
|
||||
|
||||
const template24Ref = ref(null);
|
||||
const template2Ref = ref(null);
|
||||
|
||||
function insertVariable(field, variable) {
|
||||
const el = field === '24h' ? template24Ref.value?.$el?.querySelector('textarea') : template2Ref.value?.$el?.querySelector('textarea');
|
||||
if (!el) return;
|
||||
const start = el.selectionStart ?? 0;
|
||||
const end = el.selectionEnd ?? 0;
|
||||
const key = field === '24h' ? 'template_24h' : 'template_2h';
|
||||
const before = api.settings.value[key].slice(0, start);
|
||||
const after = api.settings.value[key].slice(end);
|
||||
api.settings.value[key] = before + variable + after;
|
||||
setTimeout(() => {
|
||||
el.focus();
|
||||
const pos = start + variable.length;
|
||||
el.setSelectionRange(pos, pos);
|
||||
}, 10);
|
||||
}
|
||||
|
||||
async function onSave() {
|
||||
const res = await api.save();
|
||||
if (res.ok) toast.add({ severity: 'success', summary: 'Salvo', life: 2000 });
|
||||
else toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
|
||||
async function onRunNow() {
|
||||
const res = await api.runNow();
|
||||
if (res.ok) {
|
||||
const s = res.stats || {};
|
||||
const sent = s.sent || 0;
|
||||
const considered = s.considered || 0;
|
||||
const skippedTotal = Object.values(s.skipped || {}).reduce((a, b) => a + b, 0);
|
||||
toast.add({
|
||||
severity: sent > 0 ? 'success' : 'info',
|
||||
summary: `Execução concluída`,
|
||||
detail: `Considerados: ${considered} · Enviados: ${sent} · Pulados: ${skippedTotal}`,
|
||||
life: 5000
|
||||
});
|
||||
await api.load();
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Preview renderizado
|
||||
const previewVars = {
|
||||
nome_paciente: 'Maria Silva',
|
||||
data_sessao: '22 de abril',
|
||||
hora_sessao: '14:30',
|
||||
modalidade: 'presencial',
|
||||
nome_clinica: 'Clínica Exemplo'
|
||||
};
|
||||
|
||||
function renderPreview(tpl) {
|
||||
return String(tpl || '')
|
||||
.replaceAll('{{nome_paciente}}', previewVars.nome_paciente)
|
||||
.replaceAll('{{data_sessao}}', previewVars.data_sessao)
|
||||
.replaceAll('{{hora_sessao}}', previewVars.hora_sessao)
|
||||
.replaceAll('{{modalidade}}', previewVars.modalidade)
|
||||
.replaceAll('{{nome_clinica}}', previewVars.nome_clinica);
|
||||
}
|
||||
|
||||
const preview24 = computed(() => renderPreview(api.settings.value.template_24h));
|
||||
const preview2h = computed(() => renderPreview(api.settings.value.template_2h));
|
||||
|
||||
// Stats
|
||||
const recentSent = computed(() => api.recentLogs.value.filter((l) => l.provider !== 'skipped').length);
|
||||
const recentSkipped = computed(() => api.recentLogs.value.filter((l) => l.provider === 'skipped').length);
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleString('pt-BR', {
|
||||
day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function formatPhone(p) {
|
||||
const s = String(p || '').replace(/\D/g, '');
|
||||
if (s.length === 13 && s.startsWith('55')) return `(${s.slice(2, 4)}) ${s.slice(4, 9)}-${s.slice(9)}`;
|
||||
return p;
|
||||
}
|
||||
|
||||
onMounted(() => { api.load(); });
|
||||
watch(() => tenantStore.activeTenantId, () => { api.load(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
label="Testar agora"
|
||||
icon="pi pi-bolt"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:loading="api.saving.value"
|
||||
v-tooltip.bottom="'Roda o processo manualmente (útil pra testar ou fazer catch-up)'"
|
||||
@click="onRunNow"
|
||||
/>
|
||||
<Button
|
||||
label="Salvar"
|
||||
icon="pi pi-check"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:loading="api.saving.value"
|
||||
:disabled="api.loading.value"
|
||||
@click="onSave"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="api.loading.value"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="api.load()"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Info -->
|
||||
<div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5" />
|
||||
<div>
|
||||
<strong>Como funciona:</strong> a cada 15 minutos o sistema verifica sessões agendadas que estão chegando em
|
||||
<strong>24h ± 15min</strong> ou <strong>2h ± 15min</strong>, e envia WhatsApp pro paciente usando o canal ativo.
|
||||
Respeita opt-out (LGPD), quiet hours, e só envia uma vez por sessão+tipo.
|
||||
<br/>
|
||||
<strong>Pré-requisito:</strong> WhatsApp ativo (Oficial AgenciaPSI ou Pessoal) + paciente com telefone cadastrado.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toggle principal + stats -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<ToggleSwitch v-model="api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">
|
||||
{{ api.settings.value.enabled ? 'Lembretes ativados' : 'Lembretes desativados' }}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="text-[1.35rem] font-bold leading-none text-green-500">{{ recentSent }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Enviados (últimos 30)</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="text-[1.35rem] font-bold leading-none text-slate-500">{{ recentSkipped }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Pulados (opt-out, duplicata, etc)</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Lead times + templates -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-clock text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Lembretes a enviar</span>
|
||||
</div>
|
||||
|
||||
<!-- 24h -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<ToggleSwitch v-model="api.settings.value.send_24h" :disabled="!api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">24h antes da sessão</span>
|
||||
</div>
|
||||
<div v-if="api.settings.value.send_24h" class="flex flex-col gap-2 pl-10">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<Button
|
||||
v-for="v in VARIABLES"
|
||||
:key="v.key"
|
||||
:label="v.key"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="!text-[0.7rem] !py-0.5 !px-1.5 font-mono"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
v-tooltip.top="v.label"
|
||||
@click="insertVariable('24h', v.key)"
|
||||
/>
|
||||
</div>
|
||||
<Textarea
|
||||
ref="template24Ref"
|
||||
v-model="api.settings.value.template_24h"
|
||||
rows="3"
|
||||
autoResize
|
||||
class="w-full text-sm"
|
||||
:maxlength="2000"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] p-2 rounded bg-[var(--surface-ground)] italic">
|
||||
<strong class="not-italic">Preview:</strong> {{ preview24 }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 2h -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<ToggleSwitch v-model="api.settings.value.send_2h" :disabled="!api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">2h antes da sessão</span>
|
||||
</div>
|
||||
<div v-if="api.settings.value.send_2h" class="flex flex-col gap-2 pl-10">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<Button
|
||||
v-for="v in VARIABLES"
|
||||
:key="v.key"
|
||||
:label="v.key"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="!text-[0.7rem] !py-0.5 !px-1.5 font-mono"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
v-tooltip.top="v.label"
|
||||
@click="insertVariable('2h', v.key)"
|
||||
/>
|
||||
</div>
|
||||
<Textarea
|
||||
ref="template2Ref"
|
||||
v-model="api.settings.value.template_2h"
|
||||
rows="3"
|
||||
autoResize
|
||||
class="w-full text-sm"
|
||||
:maxlength="2000"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] p-2 rounded bg-[var(--surface-ground)] italic">
|
||||
<strong class="not-italic">Preview:</strong> {{ preview2h }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Quiet hours + LGPD -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-moon text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Horário silencioso & compliance</span>
|
||||
</div>
|
||||
|
||||
<!-- Quiet hours -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<ToggleSwitch v-model="api.settings.value.quiet_hours_enabled" :disabled="!api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">Não enviar em horário silencioso</span>
|
||||
</div>
|
||||
<div v-if="api.settings.value.quiet_hours_enabled" class="flex items-center gap-2 pl-10 flex-wrap">
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">Das</span>
|
||||
<input
|
||||
type="time"
|
||||
v-model="api.settings.value.quiet_hours_start"
|
||||
class="text-sm px-2 py-1 rounded border border-[var(--surface-border)] bg-[var(--surface-card)]"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">até</span>
|
||||
<input
|
||||
type="time"
|
||||
v-model="api.settings.value.quiet_hours_end"
|
||||
class="text-sm px-2 py-1 rounded border border-[var(--surface-border)] bg-[var(--surface-card)]"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<span class="text-xs text-[var(--text-color-secondary)] italic">(fuso São Paulo)</span>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] pl-10">
|
||||
Sessões que caem dentro do horário silencioso não disparam o lembrete — mesmo que "24h/2h antes" batam nessa janela.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Opt-out -->
|
||||
<div class="flex flex-col gap-2 pt-2 border-t border-[var(--surface-border)]">
|
||||
<div class="flex items-center gap-2">
|
||||
<ToggleSwitch v-model="api.settings.value.respect_opt_out" :disabled="!api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">Respeitar opt-out (LGPD)</span>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] pl-10">
|
||||
Pacientes que enviaram "PARAR" não recebem lembretes. <strong>Recomendado manter ativado</strong>
|
||||
— LGPD Art. 18 §2 (direito de oposição). Desligar só com base legal específica.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Log recente -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-history text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Histórico recente (30 últimos)</span>
|
||||
</div>
|
||||
|
||||
<div v-if="api.loading.value" class="flex flex-col gap-1.5">
|
||||
<Skeleton v-for="n in 4" :key="n" height="2.5rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!api.recentLogs.value.length" class="text-xs text-[var(--text-color-secondary)] italic text-center py-4">
|
||||
Nenhum lembrete processado ainda. Clique em "Testar agora" pra executar manualmente.
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-col gap-1 max-h-[360px] overflow-y-auto">
|
||||
<div
|
||||
v-for="log in api.recentLogs.value"
|
||||
:key="log.id"
|
||||
class="flex items-center gap-2 p-2 rounded-md border text-xs"
|
||||
:class="log.provider === 'skipped'
|
||||
? 'border-[var(--surface-border)] bg-[var(--surface-ground)] opacity-80'
|
||||
: 'border-green-500/25 bg-green-500/5'"
|
||||
>
|
||||
<i
|
||||
class="pi shrink-0"
|
||||
:class="log.provider === 'skipped' ? 'pi-forward text-[var(--text-color-secondary)]' : 'pi-send text-green-500'"
|
||||
/>
|
||||
<span class="font-semibold text-[0.7rem] uppercase px-1.5 py-px rounded shrink-0" :class="log.reminder_type === '24h' ? 'bg-indigo-500/10 text-indigo-500' : 'bg-amber-500/10 text-amber-500'">
|
||||
{{ log.reminder_type }}
|
||||
</span>
|
||||
<span v-if="log.to_phone" class="font-mono">{{ formatPhone(log.to_phone) }}</span>
|
||||
<span v-if="log.provider === 'skipped'" class="italic text-[var(--text-color-secondary)]">
|
||||
{{ log.skip_reason }}
|
||||
</span>
|
||||
<span v-else class="text-green-600">enviado</span>
|
||||
<span class="ml-auto text-[var(--text-color-secondary)]">{{ fmtDate(log.sent_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -16,12 +16,14 @@
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
const router = useRouter();
|
||||
|
||||
// ── Contexto ──────────────────────────────────────────────────
|
||||
const userId = ref(null);
|
||||
@@ -138,9 +140,12 @@ onMounted(async () => {
|
||||
<!-- Header -->
|
||||
<Card>
|
||||
<template #title>
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-box text-xl" />
|
||||
Recursos Extras
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-box text-xl" />
|
||||
Recursos Extras
|
||||
</div>
|
||||
<Button label="Ver extrato" icon="pi pi-list" severity="secondary" outlined size="small" @click="router.push({ name: 'ConfiguracoesRecursosExtrasExtrato' })" />
|
||||
</div>
|
||||
</template>
|
||||
<template #subtitle>Amplie as funcionalidades da sua clínica com recursos adicionais.</template>
|
||||
|
||||
@@ -170,7 +170,13 @@ onMounted(async () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4 p-4">
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<router-link to="/configuracoes/whatsapp">
|
||||
<Button label="Trocar canal" icon="pi pi-arrow-left" severity="secondary" outlined size="small" class="rounded-full" />
|
||||
</router-link>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Loading inicial ───────────────────────────────────────────── -->
|
||||
<div v-if="store.loadingMyChannel" class="flex justify-center py-12">
|
||||
<ProgressSpinner style="width: 40px; height: 40px" />
|
||||
@@ -253,13 +259,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<span class="info-label">Provedor</span>
|
||||
<span>Twilio WhatsApp Business</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<span class="info-label">Subconta ID</span>
|
||||
<span class="font-mono text-xs text-(--text-color-secondary)">
|
||||
{{ store.myChannel?.twilio_subaccount_sid?.slice(0, 20) ?? '—' }}…
|
||||
</span>
|
||||
<span>WhatsApp Business Oficial — AgenciaPSI</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<span class="info-label">Ativado em</span>
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — WhatsApp Chooser (landing)
|
||||
|--------------------------------------------------------------------------
|
||||
| Apresenta os 2 canais WhatsApp disponíveis e gerencia exclusividade.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const tenantStore = useTenantStore();
|
||||
|
||||
const loading = ref(true);
|
||||
const switching = ref(false);
|
||||
const activeChannel = ref(null); // row de notification_channels (provider, is_active, etc) ou null
|
||||
|
||||
const activeProvider = computed(() => {
|
||||
if (!activeChannel.value) return null;
|
||||
return activeChannel.value.provider; // 'twilio' | 'evolution'
|
||||
});
|
||||
|
||||
async function loadChannel() {
|
||||
const tenantId = tenantStore.activeTenantId;
|
||||
if (!tenantId) {
|
||||
activeChannel.value = null;
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await supabase
|
||||
.from('notification_channels')
|
||||
.select('id, provider, is_active, connection_status, twilio_phone_number, credentials, updated_at')
|
||||
.eq('tenant_id', tenantId)
|
||||
.eq('channel', 'whatsapp')
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle();
|
||||
activeChannel.value = data || null;
|
||||
} catch (e) {
|
||||
console.error('[whatsapp-chooser] load:', e?.message);
|
||||
activeChannel.value = null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function goSetup(provider) {
|
||||
if (provider === 'evolution') router.push('/configuracoes/whatsapp-pessoal');
|
||||
else if (provider === 'twilio') router.push('/configuracoes/whatsapp-oficial');
|
||||
}
|
||||
|
||||
async function handleChoose(provider) {
|
||||
// Se nao tem canal ativo, segue direto pro setup
|
||||
if (!activeProvider.value) {
|
||||
goSetup(provider);
|
||||
return;
|
||||
}
|
||||
// Mesmo provider → so navega
|
||||
if (activeProvider.value === provider) {
|
||||
goSetup(provider);
|
||||
return;
|
||||
}
|
||||
// Provider diferente → confirmar troca
|
||||
const from = activeProvider.value === 'twilio' ? 'Oficial AgenciaPSI' : 'Pessoal';
|
||||
const to = provider === 'twilio' ? 'Oficial AgenciaPSI' : 'Pessoal';
|
||||
confirm.require({
|
||||
message: `Você está usando o WhatsApp ${from}. Trocar pro ${to} vai desativar o canal atual e você vai precisar reconfigurar. Continuar?`,
|
||||
header: 'Trocar canal WhatsApp',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: 'Trocar',
|
||||
rejectLabel: 'Cancelar',
|
||||
acceptClass: 'p-button-warning',
|
||||
accept: async () => {
|
||||
await deactivateCurrent();
|
||||
goSetup(provider);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function deactivateCurrent() {
|
||||
if (!activeChannel.value) return;
|
||||
switching.value = true;
|
||||
try {
|
||||
// 1ª tentativa: UPDATE direto (funciona se owner_id = user atual)
|
||||
const { error } = await supabase
|
||||
.from('notification_channels')
|
||||
.update({ is_active: false, deleted_at: new Date().toISOString() })
|
||||
.eq('id', activeChannel.value.id);
|
||||
|
||||
if (error) {
|
||||
// Fallback: canal criado pelo SaaS admin (RLS bloqueia update do tenant).
|
||||
// Usa edge function com service_role pra deativar.
|
||||
const { data: fnData, error: fnErr } = await supabase.functions.invoke('deactivate-notification-channel', {
|
||||
body: { channel_id: activeChannel.value.id }
|
||||
});
|
||||
if (fnErr || !fnData?.ok) {
|
||||
// Nem via edge function. Segue em frente — o setup do novo provider cuida.
|
||||
console.warn('[chooser] deactivate failed:', error.message, fnErr?.message);
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Canal anterior não foi desativado',
|
||||
detail: 'Prossiga com o novo canal. Se o envio ainda usar o antigo, contate o suporte.',
|
||||
life: 4500
|
||||
});
|
||||
activeChannel.value = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
activeChannel.value = null;
|
||||
toast.add({ severity: 'info', summary: 'Canal anterior desativado', life: 2500 });
|
||||
} catch (e) {
|
||||
console.warn('[chooser] deactivate unexpected error:', e?.message);
|
||||
activeChannel.value = null; // limpa pra UI não ficar travada
|
||||
} finally {
|
||||
switching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const providerLabel = computed(() => {
|
||||
if (!activeProvider.value) return null;
|
||||
return activeProvider.value === 'twilio' ? 'WhatsApp Oficial AgenciaPSI' : 'WhatsApp Pessoal';
|
||||
});
|
||||
|
||||
const providerIcon = computed(() => activeProvider.value === 'twilio' ? 'pi-verified' : 'pi-mobile');
|
||||
|
||||
const connectionDot = computed(() => {
|
||||
const s = activeChannel.value?.connection_status;
|
||||
const active = activeChannel.value?.is_active;
|
||||
if (!active) return { cls: 'bg-slate-400', label: 'Inativo' };
|
||||
if (s === 'open' || s === 'connected') return { cls: 'bg-green-500', label: 'Conectado' };
|
||||
if (s === 'close' || s === 'disconnected') return { cls: 'bg-red-500', label: 'Desconectado' };
|
||||
return { cls: 'bg-amber-400', label: 'Aguardando' };
|
||||
});
|
||||
|
||||
onMounted(() => { loadChannel(); });
|
||||
watch(() => tenantStore.activeTenantId, () => { loadChannel(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ConfirmDialog />
|
||||
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="loading"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="loadChannel"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Skeleton inicial -->
|
||||
<div v-if="loading" class="flex flex-col gap-3">
|
||||
<Skeleton height="5rem" class="rounded-md" />
|
||||
<Skeleton height="14rem" class="rounded-md" />
|
||||
<Skeleton height="14rem" class="rounded-md" />
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<!-- Canal atual ativo -->
|
||||
<div
|
||||
v-if="activeProvider"
|
||||
class="rounded-md border p-4 flex items-center gap-3"
|
||||
:class="activeProvider === 'twilio' ? 'border-emerald-500/25 bg-emerald-500/5' : 'border-indigo-500/25 bg-indigo-500/5'"
|
||||
>
|
||||
<div
|
||||
class="grid place-items-center w-11 h-11 rounded-md shrink-0"
|
||||
:class="activeProvider === 'twilio' ? 'bg-emerald-500/15 text-emerald-500' : 'bg-indigo-500/15 text-indigo-500'"
|
||||
>
|
||||
<i :class="['pi', providerIcon, 'text-xl']" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-sm font-bold text-[var(--text-color)]">Canal ativo: {{ providerLabel }}</span>
|
||||
<span class="inline-flex items-center gap-1 text-[0.7rem] font-semibold">
|
||||
<span class="w-1.5 h-1.5 rounded-full" :class="connectionDot.cls" />
|
||||
{{ connectionDot.label }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="activeProvider === 'twilio' && activeChannel?.twilio_phone_number" class="text-xs text-[var(--text-color-secondary)] mt-0.5 font-mono">
|
||||
{{ activeChannel.twilio_phone_number }}
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">
|
||||
Escolha outro canal abaixo pra trocar, ou clique em "Gerenciar" pra configurar o atual.
|
||||
</div>
|
||||
</div>
|
||||
<router-link :to="activeProvider === 'twilio' ? '/configuracoes/whatsapp-oficial' : '/configuracoes/whatsapp-pessoal'">
|
||||
<Button
|
||||
label="Gerenciar"
|
||||
icon="pi pi-cog"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
/>
|
||||
</router-link>
|
||||
</div>
|
||||
|
||||
<!-- Título -->
|
||||
<div class="text-xs font-bold uppercase tracking-wide text-[var(--text-color-secondary)] opacity-65 mt-1">
|
||||
{{ activeProvider ? 'Outros canais disponíveis' : 'Escolha como conectar seu WhatsApp' }}
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
||||
<!-- Cartão: WhatsApp Oficial AgenciaPSI (Twilio) -->
|
||||
<button
|
||||
class="flex flex-col text-left gap-3 p-5 rounded-md border-2 bg-[var(--surface-card)] cursor-pointer transition-all hover:shadow-md"
|
||||
:class="activeProvider === 'twilio'
|
||||
? 'border-emerald-500 shadow-[0_0_0_4px_rgba(34,197,94,0.12)]'
|
||||
: 'border-[var(--surface-border)] hover:border-emerald-400/50'"
|
||||
:disabled="switching"
|
||||
@click="handleChoose('twilio')"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="grid place-items-center w-12 h-12 rounded-md shrink-0 bg-emerald-500/10 text-emerald-500">
|
||||
<i class="pi pi-verified text-2xl" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-[1rem] font-bold text-[var(--text-color)]">WhatsApp Oficial AgenciaPSI</span>
|
||||
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[0.65rem] font-bold bg-emerald-500 text-white">⭐ Recomendado</span>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">
|
||||
Canal oficial gerenciado pela AgenciaPSI. Máxima confiabilidade e compliance.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="flex flex-col gap-1.5 text-xs">
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-check-circle text-emerald-500 mt-0.5" />
|
||||
<span><strong>Zero risco de banimento</strong> — aprovado pela Meta, API oficial</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-check-circle text-emerald-500 mt-0.5" />
|
||||
<span><strong>Número exclusivo</strong> da clínica, sem celular intermediário</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-check-circle text-emerald-500 mt-0.5" />
|
||||
<span><strong>Conexão gerenciada</strong> — 99,9% uptime, zero manutenção</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-check-circle text-emerald-500 mt-0.5" />
|
||||
<span><strong>Compliance LGPD + auditoria</strong> completa</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-dollar text-emerald-500 mt-0.5" />
|
||||
<span>Consome <strong>créditos por mensagem</strong> enviada</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="mt-auto pt-2 border-t border-[var(--surface-border)] flex items-center justify-between">
|
||||
<span class="text-[0.7rem] text-[var(--text-color-secondary)]">
|
||||
Ideal pra <strong>clínicas</strong> e alto volume
|
||||
</span>
|
||||
<span class="text-[0.72rem] font-bold text-emerald-500 flex items-center gap-1">
|
||||
{{ activeProvider === 'twilio' ? 'Ativo' : 'Ativar' }} <i class="pi pi-arrow-right text-[0.6rem]" />
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<!-- Cartão: WhatsApp Pessoal (Evolution) -->
|
||||
<button
|
||||
class="flex flex-col text-left gap-3 p-5 rounded-md border-2 bg-[var(--surface-card)] cursor-pointer transition-all hover:shadow-md"
|
||||
:class="activeProvider === 'evolution'
|
||||
? 'border-indigo-500 shadow-[0_0_0_4px_rgba(99,102,241,0.12)]'
|
||||
: 'border-[var(--surface-border)] hover:border-indigo-400/50'"
|
||||
:disabled="switching"
|
||||
@click="handleChoose('evolution')"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="grid place-items-center w-12 h-12 rounded-md shrink-0 bg-indigo-500/10 text-indigo-500">
|
||||
<i class="pi pi-mobile text-2xl" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-[1rem] font-bold text-[var(--text-color)]">WhatsApp Pessoal</span>
|
||||
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[0.65rem] font-bold bg-slate-500/10 text-slate-600">Gratuito</span>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">
|
||||
Conecta seu WhatsApp pessoal via QR code. Sem custo por mensagem.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="flex flex-col gap-1.5 text-xs">
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-check-circle text-indigo-500 mt-0.5" />
|
||||
<span><strong>Gratuito</strong> — sem custo por mensagem</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-check-circle text-indigo-500 mt-0.5" />
|
||||
<span>Setup rápido via <strong>QR code</strong></span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-exclamation-triangle text-amber-500 mt-0.5" />
|
||||
<span><strong>Uso informal</strong> — Meta pode restringir/banir o número</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-exclamation-triangle text-amber-500 mt-0.5" />
|
||||
<span>Depende do <strong>celular ligado e com internet</strong></span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<i class="pi pi-info-circle text-amber-500 mt-0.5" />
|
||||
<span>Sem SLA, sem garantia de uptime</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="mt-auto pt-2 border-t border-[var(--surface-border)] flex items-center justify-between">
|
||||
<span class="text-[0.7rem] text-[var(--text-color-secondary)]">
|
||||
Ideal pra <strong>uso pessoal</strong> e baixo volume
|
||||
</span>
|
||||
<span class="text-[0.72rem] font-bold text-indigo-500 flex items-center gap-1">
|
||||
{{ activeProvider === 'evolution' ? 'Ativo' : 'Ativar' }} <i class="pi pi-arrow-right text-[0.6rem]" />
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Info geral -->
|
||||
<div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5" />
|
||||
<div>
|
||||
<strong>Só um canal ativo por vez.</strong>
|
||||
Trocar de canal desativa o outro — você vai precisar reconfigurar (conectar QR novamente no Pessoal, ou ativar o número no Oficial).
|
||||
Histórico de conversas é <strong>preservado</strong> em ambos os casos.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -16,15 +16,24 @@
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const tenantStore = useTenantStore();
|
||||
|
||||
// Detecta area (admin clinica vs therapist) pra direcionar corretamente
|
||||
function goConversas() {
|
||||
const role = tenantStore.activeRole || tenantStore.role || '';
|
||||
const isTherapistArea = role === 'therapist';
|
||||
router.push(isTherapistArea ? '/therapist/conversas' : '/admin/conversas');
|
||||
}
|
||||
|
||||
// ── Contexto ──────────────────────────────────────────────────
|
||||
const userId = ref(null);
|
||||
const tenantId = ref(null); // tenant_id real (da tabela tenants)
|
||||
@@ -46,6 +55,7 @@ async function loadUser() {
|
||||
|
||||
const credentials = ref({ api_url: '', api_key: '', instance_name: '' });
|
||||
const hasCredentials = ref(false);
|
||||
const channelRecord = ref(null); // row de notification_channels pra sincronizar connection_status
|
||||
const connectionStatus = ref(null); // 'open' | 'close' | 'connecting' | null
|
||||
const connectionLoading = ref(false);
|
||||
|
||||
@@ -95,6 +105,7 @@ async function loadCredentials() {
|
||||
instance_name: data.credentials.instance_name || ''
|
||||
};
|
||||
hasCredentials.value = true;
|
||||
channelRecord.value = data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,8 +119,26 @@ async function checkConnectionStatus() {
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const instances = await res.json();
|
||||
const inst = Array.isArray(instances) ? instances.find((i) => i.instance?.instanceName === credentials.value.instance_name) : null;
|
||||
connectionStatus.value = inst?.instance?.status || 'close';
|
||||
// Evolution v1 retorna [{ instance: { instanceName, status } }], v2 retorna [{ instanceName, connectionStatus/state }]
|
||||
const arr = Array.isArray(instances) ? instances : [];
|
||||
const inst = arr.find((i) => {
|
||||
const name = i?.instance?.instanceName ?? i?.instanceName ?? i?.name;
|
||||
return name === credentials.value.instance_name;
|
||||
});
|
||||
const rawState = inst?.instance?.status ?? inst?.instance?.state ?? inst?.connectionStatus ?? inst?.state ?? inst?.status;
|
||||
connectionStatus.value = rawState || 'close';
|
||||
|
||||
// Persiste no DB pra SaaS admin ver status atualizado na listagem
|
||||
if (channelRecord.value?.id) {
|
||||
const dbStatus = rawState === 'open' ? 'connected' : rawState === 'connecting' ? 'connecting' : 'disconnected';
|
||||
if (channelRecord.value.connection_status !== dbStatus) {
|
||||
await supabase
|
||||
.from('notification_channels')
|
||||
.update({ connection_status: dbStatus, last_health_check: new Date().toISOString() })
|
||||
.eq('id', channelRecord.value.id);
|
||||
channelRecord.value.connection_status = dbStatus;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
connectionStatus.value = 'close';
|
||||
toast.add({
|
||||
@@ -133,16 +162,29 @@ async function fetchQrCode() {
|
||||
const res = await fetch(`${credentials.value.api_url}/instance/connect/${credentials.value.instance_name}`, { headers: { apikey: credentials.value.api_key } });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
const base64 = data?.base64;
|
||||
// Evolution v1: data.qrcode.base64 · v2: data.base64 · variantes: data.code/qr/qrCode
|
||||
const base64 =
|
||||
data?.base64 ||
|
||||
data?.qrcode?.base64 ||
|
||||
data?.qrCode?.base64 ||
|
||||
data?.qr?.base64 ||
|
||||
data?.qr ||
|
||||
data?.code ||
|
||||
null;
|
||||
if (!base64) {
|
||||
// Instância pode já estar conectada
|
||||
if (data?.instance?.status === 'open') {
|
||||
const openState =
|
||||
data?.instance?.status === 'open' ||
|
||||
data?.instance?.state === 'open' ||
|
||||
data?.state === 'open' ||
|
||||
data?.status === 'open';
|
||||
if (openState) {
|
||||
connectionStatus.value = 'open';
|
||||
toast.add({ severity: 'success', summary: 'WhatsApp já está conectado!', life: 3000 });
|
||||
qrDialog.value = false;
|
||||
return;
|
||||
}
|
||||
throw new Error('QR Code não retornado pela API.');
|
||||
console.error('[QR] Resposta inesperada da Evolution:', data);
|
||||
throw new Error('QR Code não retornado pela API. Veja o console (F12) pra debug.');
|
||||
}
|
||||
qrCodeBase64.value = base64.startsWith('data:') ? base64 : `data:image/png;base64,${base64}`;
|
||||
startQrCountdown();
|
||||
@@ -177,6 +219,58 @@ function openQrDialog() {
|
||||
fetchQrCode();
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// Inbox (Fase 5a) — configurar webhook MESSAGES_UPSERT na Evolution
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
const inboxProvisioning = ref(false);
|
||||
const inboxWebhookUrl = ref('');
|
||||
|
||||
// Resolve URL pública do Supabase pra Evolution conseguir alcançar a edge function.
|
||||
// Em dev local, localhost de dentro do container Evolution não funciona — precisa host.docker.internal.
|
||||
function resolveSupabasePublicUrl() {
|
||||
const envUrl = import.meta.env.VITE_SUPABASE_URL || '';
|
||||
try {
|
||||
const u = new URL(envUrl);
|
||||
if (u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
|
||||
u.hostname = 'host.docker.internal';
|
||||
return u.toString().replace(/\/+$/, '');
|
||||
}
|
||||
} catch {}
|
||||
return envUrl.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
async function provisionInbox() {
|
||||
if (!tenantId.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Tenant inválido', life: 3000 });
|
||||
return;
|
||||
}
|
||||
if (!credentials.value?.api_url || !credentials.value?.api_key || !credentials.value?.instance_name) {
|
||||
toast.add({ severity: 'warn', summary: 'Salve as credenciais antes', detail: 'URL, API key e nome da instância são obrigatórios.', life: 4000 });
|
||||
return;
|
||||
}
|
||||
inboxProvisioning.value = true;
|
||||
try {
|
||||
const publicUrl = resolveSupabasePublicUrl();
|
||||
const { data, error } = await supabase.functions.invoke('evolution-webhook-provision', {
|
||||
body: {
|
||||
tenant_id: tenantId.value,
|
||||
api_url: credentials.value.api_url,
|
||||
api_key: credentials.value.api_key,
|
||||
instance_name: credentials.value.instance_name,
|
||||
public_url: publicUrl
|
||||
}
|
||||
});
|
||||
if (error) throw error;
|
||||
if (!data?.ok) throw new Error(data?.error || 'Falha no provisionamento');
|
||||
inboxWebhookUrl.value = data.webhook_url;
|
||||
toast.add({ severity: 'success', summary: 'Inbox conectada!', detail: 'Mensagens recebidas agora vão aparecer em /admin/conversas.', life: 5000 });
|
||||
} catch (err) {
|
||||
toast.add({ severity: 'error', summary: 'Falha ao configurar inbox', detail: err?.message || String(err), life: 6000 });
|
||||
} finally {
|
||||
inboxProvisioning.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function closeQrDialog() {
|
||||
qrDialog.value = false;
|
||||
clearQrTimer();
|
||||
@@ -509,6 +603,12 @@ onBeforeUnmount(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<router-link to="/configuracoes/whatsapp">
|
||||
<Button label="Trocar canal" icon="pi pi-arrow-left" severity="secondary" outlined size="small" class="rounded-full" />
|
||||
</router-link>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Abas -->
|
||||
<Tabs :value="activeTab" @update:value="activeTab = $event">
|
||||
@@ -563,6 +663,28 @@ onBeforeUnmount(() => {
|
||||
e escaneie o QR Code que aparecerá na tela.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Inbox / CRM de conversas (Fase 5a) -->
|
||||
<div v-if="connectionStatus === 'open'" class="flex flex-col gap-3 px-4 py-3 rounded-lg border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="grid place-items-center w-10 h-10 rounded-full bg-blue-100 text-blue-600">
|
||||
<i class="pi pi-inbox text-lg" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold text-sm">Inbox de conversas</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Receba respostas dos pacientes direto no sistema.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Button label="Conectar inbox" icon="pi pi-link" size="small" :loading="inboxProvisioning" @click="provisionInbox" />
|
||||
<Button icon="pi pi-external-link" severity="secondary" outlined size="small" v-tooltip.bottom="'Abrir Conversas'" @click="goConversas" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="inboxWebhookUrl" class="text-[0.7rem] text-[var(--text-color-secondary)] bg-[var(--surface-card)] border border-[var(--surface-border)] rounded px-2 py-1.5 font-mono break-all">
|
||||
Webhook configurado: {{ inboxWebhookUrl }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</TabPanel>
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/layout/configuracoes/ConfiguracoesWhatsappTemplatesPage.vue
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, onMounted, nextTick } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const tenantStore = useTenantStore();
|
||||
const drawerStore = useConversationDrawerStore();
|
||||
|
||||
const userId = ref(null);
|
||||
const tenantId = ref(null);
|
||||
|
||||
const templates = ref([]);
|
||||
const loading = ref(true);
|
||||
const saving = ref({});
|
||||
const reverting = ref({});
|
||||
|
||||
const EVENT_TYPE_LABELS = {
|
||||
lembrete_sessao: 'Lembrete de sessão',
|
||||
confirmacao_sessao: 'Confirmação de sessão',
|
||||
cancelamento_sessao: 'Cancelamento de sessão',
|
||||
reagendamento: 'Reagendamento',
|
||||
cobranca_pendente: 'Cobrança pendente',
|
||||
boas_vindas_paciente: 'Boas-vindas ao paciente',
|
||||
intake_recebido: 'Triagem recebida',
|
||||
intake_aprovado: 'Triagem aprovada',
|
||||
intake_rejeitado: 'Triagem rejeitada'
|
||||
};
|
||||
const EVENT_SEVERITY = {
|
||||
lembrete_sessao: 'info',
|
||||
confirmacao_sessao: 'success',
|
||||
cancelamento_sessao: 'danger',
|
||||
reagendamento: 'warn',
|
||||
cobranca_pendente: 'warn',
|
||||
boas_vindas_paciente: 'success',
|
||||
intake_recebido: 'info',
|
||||
intake_aprovado: 'success',
|
||||
intake_rejeitado: 'danger'
|
||||
};
|
||||
const DOMAIN_LABEL = { session: 'Sessão', intake: 'Triagem', billing: 'Financeiro', system: 'Sistema' };
|
||||
|
||||
const textareaRefs = ref({});
|
||||
function setTextareaRef(key, el) {
|
||||
if (el) textareaRefs.value[key] = el;
|
||||
}
|
||||
|
||||
async function loadUser() {
|
||||
const {
|
||||
data: { user }
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return;
|
||||
userId.value = user.id;
|
||||
tenantId.value = tenantStore.activeTenantId || user.id;
|
||||
}
|
||||
|
||||
async function loadTemplates() {
|
||||
if (!tenantId.value) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data: globals, error: gErr } = await supabase
|
||||
.from('notification_templates')
|
||||
.select('*')
|
||||
.is('tenant_id', null)
|
||||
.eq('channel', 'whatsapp')
|
||||
.eq('is_default', true)
|
||||
.eq('is_active', true)
|
||||
.is('deleted_at', null)
|
||||
.order('domain')
|
||||
.order('event_type');
|
||||
if (gErr) throw gErr;
|
||||
|
||||
const { data: customs, error: cErr } = await supabase
|
||||
.from('notification_templates')
|
||||
.select('*')
|
||||
.eq('tenant_id', tenantId.value)
|
||||
.eq('channel', 'whatsapp')
|
||||
.is('deleted_at', null);
|
||||
if (cErr) throw cErr;
|
||||
|
||||
const customMap = {};
|
||||
for (const c of customs || []) customMap[c.key] = c;
|
||||
|
||||
templates.value = (globals || []).map((g) => {
|
||||
const custom = customMap[g.key];
|
||||
const current = custom?.body_text ?? g.body_text;
|
||||
return {
|
||||
key: g.key,
|
||||
domain: g.domain,
|
||||
event_type: g.event_type,
|
||||
label: EVENT_TYPE_LABELS[g.event_type] || g.event_type,
|
||||
type_severity: EVENT_SEVERITY[g.event_type] || 'secondary',
|
||||
domain_label: DOMAIN_LABEL[g.domain] || g.domain,
|
||||
variables: Array.isArray(g.variables) ? g.variables : [],
|
||||
default_body: g.body_text,
|
||||
id: custom?.id || null,
|
||||
body_text: current,
|
||||
saved_body: current,
|
||||
is_custom: !!custom
|
||||
};
|
||||
});
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro ao carregar templates', detail: e.message, life: 4000 });
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function insertVariable(key, variable) {
|
||||
const snippet = `{{${variable}}}`;
|
||||
const tpl = templates.value.find((t) => t.key === key);
|
||||
if (!tpl) return;
|
||||
|
||||
const taWrapper = textareaRefs.value[key];
|
||||
const ta = taWrapper?.$el?.querySelector('textarea') ?? taWrapper;
|
||||
if (ta?.setSelectionRange) {
|
||||
const start = ta.selectionStart ?? ta.value.length;
|
||||
const end = ta.selectionEnd ?? start;
|
||||
tpl.body_text = (tpl.body_text || '').slice(0, start) + snippet + (tpl.body_text || '').slice(end);
|
||||
nextTick(() => {
|
||||
const pos = start + snippet.length;
|
||||
ta.focus();
|
||||
ta.setSelectionRange(pos, pos);
|
||||
});
|
||||
} else {
|
||||
tpl.body_text = (tpl.body_text || '') + snippet;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveTemplate(tpl) {
|
||||
if (!tenantId.value || saving.value[tpl.key]) return;
|
||||
const body = (tpl.body_text || '').trim();
|
||||
if (!body) {
|
||||
toast.add({ severity: 'warn', summary: 'Mensagem não pode ficar vazia', life: 3000 });
|
||||
return;
|
||||
}
|
||||
if (body.length > 4096) {
|
||||
toast.add({ severity: 'warn', summary: 'Mensagem muito longa (máx. 4096 caracteres)', life: 3000 });
|
||||
return;
|
||||
}
|
||||
|
||||
saving.value[tpl.key] = true;
|
||||
try {
|
||||
if (tpl.id) {
|
||||
const { error } = await supabase.from('notification_templates').update({ body_text: body }).eq('id', tpl.id);
|
||||
if (error) throw error;
|
||||
} else {
|
||||
const { data: existing } = await supabase.from('notification_templates').select('id').eq('tenant_id', tenantId.value).eq('key', tpl.key).is('deleted_at', null).maybeSingle();
|
||||
|
||||
if (existing?.id) {
|
||||
const { error } = await supabase.from('notification_templates').update({ body_text: body, is_active: true }).eq('id', existing.id);
|
||||
if (error) throw error;
|
||||
tpl.id = existing.id;
|
||||
} else {
|
||||
const { data, error } = await supabase
|
||||
.from('notification_templates')
|
||||
.insert({
|
||||
owner_id: userId.value,
|
||||
tenant_id: tenantId.value,
|
||||
channel: 'whatsapp',
|
||||
key: tpl.key,
|
||||
domain: tpl.domain,
|
||||
event_type: tpl.event_type,
|
||||
body_text: body,
|
||||
variables: tpl.variables,
|
||||
is_active: true,
|
||||
is_default: false
|
||||
})
|
||||
.select('id')
|
||||
.single();
|
||||
if (error) throw error;
|
||||
tpl.id = data.id;
|
||||
}
|
||||
tpl.is_custom = true;
|
||||
}
|
||||
tpl.saved_body = body;
|
||||
tpl.body_text = body;
|
||||
drawerStore.invalidateTemplates();
|
||||
toast.add({ severity: 'success', summary: 'Template salvo', life: 3000 });
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e.message, life: 5000 });
|
||||
} finally {
|
||||
saving.value[tpl.key] = false;
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRevert(tpl) {
|
||||
if (!tpl.is_custom || !tpl.id) return;
|
||||
confirm.require({
|
||||
group: 'headless',
|
||||
message: `Reverter "${tpl.label}" para o texto padrão? Sua personalização será removida.`,
|
||||
header: 'Reverter ao padrão',
|
||||
icon: 'pi-undo',
|
||||
color: '#f59e0b',
|
||||
accept: async () => {
|
||||
if (reverting.value[tpl.key]) return;
|
||||
reverting.value[tpl.key] = true;
|
||||
try {
|
||||
const { error } = await supabase.from('notification_templates').update({ deleted_at: new Date().toISOString() }).eq('id', tpl.id);
|
||||
if (error) throw error;
|
||||
tpl.id = null;
|
||||
tpl.is_custom = false;
|
||||
tpl.body_text = tpl.default_body;
|
||||
tpl.saved_body = tpl.default_body;
|
||||
drawerStore.invalidateTemplates();
|
||||
toast.add({ severity: 'success', summary: 'Revertido ao padrão', life: 3000 });
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro ao reverter', detail: e.message, life: 5000 });
|
||||
} finally {
|
||||
reverting.value[tpl.key] = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isDirty(tpl) {
|
||||
return (tpl.body_text || '') !== (tpl.saved_body || '');
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadUser();
|
||||
await loadTemplates();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<ConfirmDialog group="headless">
|
||||
<template #container="{ message, acceptCallback, rejectCallback }">
|
||||
<div class="flex flex-col items-center p-8 bg-surface-0 dark:bg-surface-900 rounded-xl shadow-xl">
|
||||
<div class="rounded-full inline-flex justify-center items-center h-24 w-24 -mt-20" :style="{ background: message.color || 'var(--p-primary-color)', color: '#fff' }">
|
||||
<i :class="`pi ${message.icon || 'pi-question'} !text-4xl`"></i>
|
||||
</div>
|
||||
<span class="font-bold text-2xl block mb-2 mt-6">{{ message.header }}</span>
|
||||
<p class="mb-0 text-center text-[var(--text-color-secondary)]">{{ message.message }}</p>
|
||||
<div class="flex items-center gap-2 mt-6">
|
||||
<Button label="Confirmar" class="rounded-full" :style="{ background: message.color || 'var(--p-primary-color)', borderColor: message.color || 'var(--p-primary-color)' }" @click="acceptCallback" />
|
||||
<Button label="Cancelar" variant="outlined" class="rounded-full" @click="rejectCallback" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</ConfirmDialog>
|
||||
|
||||
<Message severity="info" :closable="false">
|
||||
Os textos padrão já funcionam — edite apenas se quiser personalizar. A qualquer momento você pode <strong>reverter ao padrão</strong> definido pelo administrador.
|
||||
</Message>
|
||||
|
||||
<template v-if="loading">
|
||||
<div v-for="n in 4" :key="n" class="rounded-[6px] border border-[var(--surface-border)] bg-[var(--surface-card)] p-4">
|
||||
<div class="flex items-center gap-3 mb-3">
|
||||
<Skeleton width="2.5rem" height="2.5rem" borderRadius="6px" />
|
||||
<div class="flex-1 flex flex-col gap-2">
|
||||
<Skeleton width="10rem" height="1rem" />
|
||||
<Skeleton width="6rem" height="0.75rem" />
|
||||
</div>
|
||||
<Skeleton width="5rem" height="1.4rem" borderRadius="999px" />
|
||||
</div>
|
||||
<Skeleton width="100%" height="5rem" class="mb-2" />
|
||||
<div class="flex gap-1">
|
||||
<Skeleton v-for="i in 3" :key="i" width="6rem" height="1.6rem" borderRadius="999px" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div
|
||||
v-if="!templates.length"
|
||||
class="rounded-[6px] border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 text-center text-[var(--text-color-secondary)]"
|
||||
>
|
||||
<i class="pi pi-whatsapp text-3xl opacity-30 block mb-2" />
|
||||
Nenhum template WhatsApp disponível no momento.
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="tpl in templates"
|
||||
:key="tpl.key"
|
||||
class="rounded-[6px] border bg-[var(--surface-card)] p-4 flex flex-col gap-3 overflow-hidden"
|
||||
:class="tpl.is_custom ? 'border-green-300' : 'border-[var(--surface-border)]'"
|
||||
>
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<div
|
||||
class="w-10 h-10 rounded-[6px] flex items-center justify-center shrink-0"
|
||||
:class="tpl.is_custom ? 'bg-green-100 text-green-700' : 'bg-[var(--surface-ground)] text-[var(--text-color-secondary)]'"
|
||||
>
|
||||
<i class="pi pi-whatsapp text-lg" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="font-semibold text-[var(--text-color)]">{{ tpl.label }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] flex items-center gap-1.5 mt-0.5">
|
||||
<Tag :value="tpl.domain_label" :severity="tpl.type_severity" class="text-[0.6rem]" />
|
||||
<code class="font-mono opacity-70">{{ tpl.key }}</code>
|
||||
</div>
|
||||
</div>
|
||||
<Tag v-if="tpl.is_custom" value="Personalizado" severity="success" class="text-[0.65rem]" />
|
||||
<Tag v-else value="Padrão" severity="secondary" class="text-[0.65rem]" />
|
||||
</div>
|
||||
|
||||
<Textarea
|
||||
:ref="(el) => setTextareaRef(tpl.key, el)"
|
||||
v-model="tpl.body_text"
|
||||
rows="4"
|
||||
auto-resize
|
||||
class="w-full text-sm"
|
||||
:maxlength="4096"
|
||||
placeholder="Digite o texto do template..."
|
||||
/>
|
||||
|
||||
<div class="flex items-center justify-between flex-wrap gap-2">
|
||||
<span class="text-[0.68rem] text-[var(--text-color-secondary)]">{{ (tpl.body_text || '').length }} / 4096 caracteres</span>
|
||||
<span v-if="isDirty(tpl)" class="text-[0.68rem] text-amber-600 font-medium flex items-center gap-1">
|
||||
<i class="pi pi-circle-fill text-[0.4rem]" />
|
||||
Alterações não salvas
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="tpl.variables.length" class="flex flex-col gap-1.5">
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">Inserir variável:</span>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<Button
|
||||
v-for="v in tpl.variables"
|
||||
:key="v"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="font-mono !text-[0.68rem] !py-1 !px-2"
|
||||
@click="insertVariable(tpl.key, v)"
|
||||
>
|
||||
<span v-text="'{{' + v + '}}'"></span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 justify-end flex-wrap">
|
||||
<Button
|
||||
v-if="tpl.is_custom"
|
||||
label="Reverter ao padrão"
|
||||
icon="pi pi-undo"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="reverting[tpl.key]"
|
||||
:disabled="reverting[tpl.key]"
|
||||
@click="confirmRevert(tpl)"
|
||||
/>
|
||||
<Button
|
||||
label="Salvar"
|
||||
icon="pi pi-check"
|
||||
size="small"
|
||||
:loading="saving[tpl.key]"
|
||||
:disabled="saving[tpl.key] || !isDirty(tpl)"
|
||||
@click="saveTemplate(tpl)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user