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:
@@ -275,6 +275,212 @@ async function loadTransactions() {
|
||||
if (data) transactions.value = data;
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// ABA 4 — WhatsApp: Pacotes (CRUD whatsapp_credit_packages)
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
const waPackages = ref([]);
|
||||
const waPackagesLoading = ref(false);
|
||||
const waPkgDialog = ref(false);
|
||||
const waEditingPkgId = ref(null);
|
||||
|
||||
const emptyWaPkg = () => ({
|
||||
name: '',
|
||||
description: '',
|
||||
credits: 100,
|
||||
price_brl: 0,
|
||||
is_active: true,
|
||||
is_featured: false,
|
||||
position: 100
|
||||
});
|
||||
|
||||
const waPkgForm = ref(emptyWaPkg());
|
||||
|
||||
async function loadWaPackages() {
|
||||
waPackagesLoading.value = true;
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('whatsapp_credit_packages')
|
||||
.select('*')
|
||||
.order('position', { ascending: true })
|
||||
.order('price_brl', { ascending: true });
|
||||
if (error) throw error;
|
||||
waPackages.value = data || [];
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message, life: 4000 });
|
||||
} finally {
|
||||
waPackagesLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openNewWaPkg() {
|
||||
waEditingPkgId.value = null;
|
||||
waPkgForm.value = emptyWaPkg();
|
||||
waPkgDialog.value = true;
|
||||
}
|
||||
|
||||
function openEditWaPkg(row) {
|
||||
waEditingPkgId.value = row.id;
|
||||
waPkgForm.value = {
|
||||
name: row.name || '',
|
||||
description: row.description || '',
|
||||
credits: row.credits,
|
||||
price_brl: Number(row.price_brl) || 0,
|
||||
is_active: row.is_active,
|
||||
is_featured: row.is_featured,
|
||||
position: row.position ?? 100
|
||||
};
|
||||
waPkgDialog.value = true;
|
||||
}
|
||||
|
||||
function sanitizeWaPkg(f) {
|
||||
return {
|
||||
name: String(f.name || '').trim().slice(0, 100),
|
||||
description: f.description ? String(f.description).trim().slice(0, 500) : null,
|
||||
credits: Math.max(1, Math.round(Number(f.credits) || 0)),
|
||||
price_brl: Math.max(0.01, Number(f.price_brl) || 0),
|
||||
is_active: !!f.is_active,
|
||||
is_featured: !!f.is_featured,
|
||||
position: Math.max(0, Math.round(Number(f.position) || 100))
|
||||
};
|
||||
}
|
||||
|
||||
async function saveWaPkg() {
|
||||
const clean = sanitizeWaPkg(waPkgForm.value);
|
||||
if (!clean.name) { toast.add({ severity: 'warn', summary: 'Nome é obrigatório', life: 2500 }); return; }
|
||||
if (clean.credits < 1) { toast.add({ severity: 'warn', summary: 'Créditos deve ser > 0', life: 2500 }); return; }
|
||||
if (clean.price_brl <= 0) { toast.add({ severity: 'warn', summary: 'Preço deve ser > 0', life: 2500 }); return; }
|
||||
try {
|
||||
if (waEditingPkgId.value) {
|
||||
const { error } = await supabase.from('whatsapp_credit_packages').update(clean).eq('id', waEditingPkgId.value);
|
||||
if (error) throw error;
|
||||
toast.add({ severity: 'success', summary: 'Pacote atualizado', life: 2000 });
|
||||
} else {
|
||||
const { error } = await supabase.from('whatsapp_credit_packages').insert(clean);
|
||||
if (error) throw error;
|
||||
toast.add({ severity: 'success', summary: 'Pacote criado', life: 2000 });
|
||||
}
|
||||
waPkgDialog.value = false;
|
||||
await loadWaPackages();
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message, life: 4000 });
|
||||
}
|
||||
}
|
||||
|
||||
function deleteWaPkg(row) {
|
||||
confirm.require({
|
||||
group: 'headless',
|
||||
header: 'Remover pacote',
|
||||
message: `Remover "${row.name}"? Compras existentes continuam válidas (FK SET NULL).`,
|
||||
icon: 'pi-trash',
|
||||
color: '#ef4444',
|
||||
accept: async () => {
|
||||
try {
|
||||
const { error } = await supabase.from('whatsapp_credit_packages').delete().eq('id', row.id);
|
||||
if (error) throw error;
|
||||
toast.add({ severity: 'success', summary: 'Pacote removido', life: 2000 });
|
||||
await loadWaPackages();
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message, life: 4000 });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function toggleWaPkgActive(row) {
|
||||
try {
|
||||
const { error } = await supabase.from('whatsapp_credit_packages').update({ is_active: !row.is_active }).eq('id', row.id);
|
||||
if (error) throw error;
|
||||
row.is_active = !row.is_active;
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message, life: 4000 });
|
||||
}
|
||||
}
|
||||
|
||||
function formatBrl(v) {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(Number(v) || 0);
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// ABA 5 — WhatsApp: Topup manual (add_whatsapp_credits RPC)
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
const waTopup = ref({
|
||||
tenantId: null,
|
||||
amount: 100,
|
||||
kind: 'topup_manual',
|
||||
note: ''
|
||||
});
|
||||
|
||||
const waTopupKinds = [
|
||||
{ label: 'Topup manual (cortesia)', value: 'topup_manual' },
|
||||
{ label: 'Ajuste', value: 'adjustment' },
|
||||
{ label: 'Estorno / Refund', value: 'refund' }
|
||||
];
|
||||
|
||||
const waTenantBalance = ref(null);
|
||||
const waRecentTopups = ref([]);
|
||||
const waTopupSaving = ref(false);
|
||||
|
||||
async function loadWaBalance(tenantId) {
|
||||
if (!tenantId) { waTenantBalance.value = null; waRecentTopups.value = []; return; }
|
||||
const [{ data: bal }, { data: txs }] = await Promise.all([
|
||||
supabase
|
||||
.from('whatsapp_credits_balance')
|
||||
.select('balance, lifetime_purchased, lifetime_used, low_balance_threshold')
|
||||
.eq('tenant_id', tenantId)
|
||||
.maybeSingle(),
|
||||
supabase
|
||||
.from('whatsapp_credits_transactions')
|
||||
.select('id, kind, amount, balance_after, note, created_at, admin_id')
|
||||
.eq('tenant_id', tenantId)
|
||||
.in('kind', ['topup_manual', 'adjustment', 'refund'])
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(20)
|
||||
]);
|
||||
waTenantBalance.value = bal || { balance: 0, lifetime_purchased: 0, lifetime_used: 0, low_balance_threshold: 20 };
|
||||
waRecentTopups.value = txs || [];
|
||||
}
|
||||
|
||||
async function onWaTenantChange() {
|
||||
await loadWaBalance(waTopup.value.tenantId);
|
||||
}
|
||||
|
||||
async function submitWaTopup() {
|
||||
const t = waTopup.value;
|
||||
if (!t.tenantId) { toast.add({ severity: 'warn', summary: 'Selecione o tenant', life: 2500 }); return; }
|
||||
const amt = Math.round(Number(t.amount) || 0);
|
||||
if (amt < 1) { toast.add({ severity: 'warn', summary: 'Créditos deve ser >= 1', life: 2500 }); return; }
|
||||
const note = String(t.note || '').trim().slice(0, 500) || null;
|
||||
|
||||
waTopupSaving.value = true;
|
||||
try {
|
||||
const { data: authData } = await supabase.auth.getUser();
|
||||
const adminId = authData?.user?.id || null;
|
||||
const { error } = await supabase.rpc('add_whatsapp_credits', {
|
||||
p_tenant_id: t.tenantId,
|
||||
p_amount: amt,
|
||||
p_kind: t.kind,
|
||||
p_purchase_id: null,
|
||||
p_admin_id: adminId,
|
||||
p_note: note
|
||||
});
|
||||
if (error) throw error;
|
||||
toast.add({ severity: 'success', summary: `+${amt} créditos`, detail: tenantName(t.tenantId), life: 3000 });
|
||||
waTopup.value.note = '';
|
||||
waTopup.value.amount = 100;
|
||||
await loadWaBalance(t.tenantId);
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message, life: 4000 });
|
||||
} finally {
|
||||
waTopupSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const waKindBadge = {
|
||||
topup_manual: { label: 'Topup', cls: 'bg-sky-500/10 text-sky-600' },
|
||||
adjustment: { label: 'Ajuste', cls: 'bg-slate-500/10 text-slate-600' },
|
||||
refund: { label: 'Refund', cls: 'bg-orange-500/10 text-orange-600' }
|
||||
};
|
||||
|
||||
function txTypeLabel(type) {
|
||||
const map = { purchase: 'Compra', consume: 'Consumo', adjustment: 'Ajuste', refund: 'Reembolso', expiration: 'Expiração' };
|
||||
return map[type] || type;
|
||||
@@ -298,11 +504,12 @@ onMounted(() => {
|
||||
loadProducts();
|
||||
loadCredits();
|
||||
loadTransactions();
|
||||
loadWaPackages();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-4 p-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">
|
||||
@@ -319,43 +526,46 @@ onMounted(() => {
|
||||
</template>
|
||||
</ConfirmDialog>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-2xl font-bold m-0">Recursos Extras (Add-ons)</h2>
|
||||
<!-- Header -->
|
||||
<div class="cfg-subheader">
|
||||
<div class="cfg-subheader__icon"><i class="pi pi-box" /></div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="cfg-subheader__title">Recursos Extras (Add-ons)</div>
|
||||
<div class="cfg-subheader__sub">Produtos, créditos WhatsApp/SMS e transações consumidas por tenants.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Próximos passos -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<Card class="border-l-4" style="border-left-color: var(--p-yellow-500)">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<i class="pi pi-bell text-2xl" style="color: var(--p-yellow-500)" />
|
||||
<div>
|
||||
<h4 class="font-semibold m-0 mb-1">Alerta de saldo baixo</h4>
|
||||
<p class="text-sm text-surface-500 m-0">
|
||||
Próximo passo: Notificar tenants automaticamente quando o saldo de créditos estiver abaixo do limite configurado. O campo <code>low_balance_threshold</code> já existe no banco — falta a Edge Function de verificação
|
||||
periódica.
|
||||
</p>
|
||||
<Tag value="Planejado" severity="warn" class="mt-2" />
|
||||
</div>
|
||||
<div class="rounded-[6px] border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 border-l-4" style="border-left-color: var(--p-yellow-500)">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-[6px] flex items-center justify-center shrink-0 bg-yellow-100 text-yellow-700">
|
||||
<i class="pi pi-bell text-lg" />
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="font-semibold text-[var(--text-color)] mb-1">Alerta de saldo baixo</div>
|
||||
<p class="text-sm text-[var(--text-color-secondary)] m-0">
|
||||
Próximo passo: notificar tenants automaticamente quando o saldo de créditos estiver abaixo do limite configurado. O campo <code class="font-mono text-xs">low_balance_threshold</code> já existe no banco — falta a Edge Function de verificação periódica.
|
||||
</p>
|
||||
<Tag value="Planejado" severity="warn" class="mt-2 text-[0.65rem]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card class="border-l-4" style="border-left-color: var(--p-blue-500)">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<i class="pi pi-credit-card text-2xl" style="color: var(--p-blue-500)" />
|
||||
<div>
|
||||
<h4 class="font-semibold m-0 mb-1">Compra online (Gateway)</h4>
|
||||
<p class="text-sm text-surface-500 m-0">
|
||||
Próximo passo: Integrar gateway de pagamento (PIX, cartão) para que tenants comprem créditos diretamente pela plataforma. Os campos <code>payment_method</code> e <code>payment_reference</code> já estão prontos no
|
||||
banco.
|
||||
</p>
|
||||
<Tag value="Planejado" severity="info" class="mt-2" />
|
||||
</div>
|
||||
<div class="rounded-[6px] border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 border-l-4" style="border-left-color: var(--p-blue-500)">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-[6px] flex items-center justify-center shrink-0 bg-blue-100 text-blue-700">
|
||||
<i class="pi pi-credit-card text-lg" />
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="font-semibold text-[var(--text-color)] mb-1">Compra online (Gateway)</div>
|
||||
<p class="text-sm text-[var(--text-color-secondary)] m-0">
|
||||
Próximo passo: integrar gateway de pagamento (PIX, cartão) para que tenants comprem créditos diretamente pela plataforma. Os campos <code class="font-mono text-xs">payment_method</code> e <code class="font-mono text-xs">payment_reference</code> já estão prontos no banco.
|
||||
</p>
|
||||
<Tag value="Planejado" severity="info" class="mt-2 text-[0.65rem]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs v-model:value="activeTab">
|
||||
@@ -363,6 +573,8 @@ onMounted(() => {
|
||||
<Tab :value="0">Produtos</Tab>
|
||||
<Tab :value="1">Recursos Extras por Tenant</Tab>
|
||||
<Tab :value="2">Transações</Tab>
|
||||
<Tab :value="3"><i class="pi pi-whatsapp mr-1 text-emerald-500" />Pacotes WhatsApp</Tab>
|
||||
<Tab :value="4"><i class="pi pi-whatsapp mr-1 text-emerald-500" />Topup WhatsApp</Tab>
|
||||
</TabList>
|
||||
|
||||
<TabPanels>
|
||||
@@ -580,6 +792,139 @@ onMounted(() => {
|
||||
</Column>
|
||||
</DataTable>
|
||||
</TabPanel>
|
||||
|
||||
<!-- ── ABA 4: Pacotes WhatsApp (loja Twilio/Asaas) ────── -->
|
||||
<TabPanel :value="3">
|
||||
<div class="flex items-start justify-between gap-3 mb-3 flex-wrap">
|
||||
<div class="text-xs text-[var(--text-color-secondary)] max-w-[660px]">
|
||||
Pacotes que os tenants veem em <code>/configuracoes/creditos-whatsapp</code>. Consumidos só no canal
|
||||
<strong>AgenciaPSI Oficial (Twilio)</strong> — WhatsApp Pessoal (Evolution) é gratuito.
|
||||
<strong>Destaque</strong> aparece com estrela; <strong>posição</strong> ordena (menor primeiro).
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Button icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="waPackagesLoading" @click="loadWaPackages" />
|
||||
<Button label="Novo pacote" icon="pi pi-plus" size="small" @click="openNewWaPkg" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable :value="waPackages" :loading="waPackagesLoading" size="small" stripedRows
|
||||
emptyMessage="Nenhum pacote cadastrado.">
|
||||
<Column field="position" header="#" style="width: 60px" />
|
||||
<Column header="Nome">
|
||||
<template #body="{ data }">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="font-semibold">{{ data.name }}</span>
|
||||
<i v-if="data.is_featured" class="pi pi-star-fill text-amber-500 text-xs" v-tooltip.top="'Destaque'" />
|
||||
</div>
|
||||
<div v-if="data.description" class="text-xs text-[var(--text-color-secondary)] truncate max-w-[360px]">
|
||||
{{ data.description }}
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
<Column field="credits" header="Créditos" style="width: 100px" />
|
||||
<Column header="Preço" style="width: 130px">
|
||||
<template #body="{ data }">
|
||||
<span class="font-mono">{{ formatBrl(data.price_brl) }}</span>
|
||||
<div class="text-[0.68rem] text-[var(--text-color-secondary)]">{{ formatBrl(data.price_brl / data.credits) }} / msg</div>
|
||||
</template>
|
||||
</Column>
|
||||
<Column header="Ativo" style="width: 80px">
|
||||
<template #body="{ data }">
|
||||
<ToggleSwitch :modelValue="data.is_active" @update:modelValue="() => toggleWaPkgActive(data)" />
|
||||
</template>
|
||||
</Column>
|
||||
<Column header="Ações" style="width: 100px">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-1">
|
||||
<Button icon="pi pi-pencil" text rounded size="small" @click="openEditWaPkg(data)" />
|
||||
<Button icon="pi pi-trash" text rounded size="small" severity="danger" @click="deleteWaPkg(data)" />
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
</TabPanel>
|
||||
|
||||
<!-- ── ABA 5: Topup manual WhatsApp ───────────────────── -->
|
||||
<TabPanel :value="4">
|
||||
<div class="grid grid-cols-1 md:grid-cols-[1fr_1fr] gap-4">
|
||||
<!-- Form -->
|
||||
<div class="flex flex-col gap-3 rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-plus-circle text-sky-500" />
|
||||
<h3 class="text-sm font-bold uppercase tracking-wide m-0">Adicionar créditos WhatsApp a um tenant</h3>
|
||||
</div>
|
||||
<p class="text-xs text-[var(--text-color-secondary)] m-0">
|
||||
Ações: cortesia onboarding, reembolso fora do Asaas, correção de falha técnica. Fica no extrato do tenant
|
||||
com <code>admin_id = você</code> pra auditoria.
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">Tenant</label>
|
||||
<Select v-model="waTopup.tenantId" :options="tenants" optionLabel="label" optionValue="value"
|
||||
filter placeholder="Selecionar tenant" class="w-full"
|
||||
:loading="loadingTenants"
|
||||
@update:modelValue="onWaTenantChange" />
|
||||
</div>
|
||||
|
||||
<div v-if="waTenantBalance" class="grid grid-cols-3 gap-2 rounded-md bg-[var(--surface-ground)] p-2 text-xs">
|
||||
<div><span class="text-[var(--text-color-secondary)]">Saldo:</span> <strong>{{ waTenantBalance.balance }}</strong></div>
|
||||
<div><span class="text-[var(--text-color-secondary)]">Comprados:</span> <strong>{{ waTenantBalance.lifetime_purchased }}</strong></div>
|
||||
<div><span class="text-[var(--text-color-secondary)]">Usados:</span> <strong>{{ waTenantBalance.lifetime_used }}</strong></div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-col gap-1 flex-1">
|
||||
<label class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">Quantidade</label>
|
||||
<InputNumber v-model="waTopup.amount" :min="1" :max="100000" class="w-full" fluid />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1 flex-1">
|
||||
<label class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">Tipo</label>
|
||||
<Select v-model="waTopup.kind" :options="waTopupKinds" optionLabel="label" optionValue="value" class="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">Nota / motivo</label>
|
||||
<Textarea v-model="waTopup.note" rows="2" autoResize
|
||||
placeholder="Ex: Cortesia onboarding, ressarcimento #T123…"
|
||||
maxlength="500" />
|
||||
<small class="text-[var(--text-color-secondary)]">Visível pro tenant no extrato. Max 500 chars.</small>
|
||||
</div>
|
||||
|
||||
<Button label="Adicionar créditos" icon="pi pi-check"
|
||||
class="rounded-full self-start"
|
||||
:loading="waTopupSaving"
|
||||
:disabled="!waTopup.tenantId || !waTopup.amount"
|
||||
@click="submitWaTopup" />
|
||||
</div>
|
||||
|
||||
<!-- Histórico -->
|
||||
<div class="flex flex-col gap-2 rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-history text-[var(--primary-color)]" />
|
||||
<h3 class="text-sm font-bold uppercase tracking-wide m-0">Topups / ajustes recentes</h3>
|
||||
</div>
|
||||
<div v-if="!waTopup.tenantId" class="text-xs text-[var(--text-color-secondary)] italic py-4 text-center">
|
||||
Selecione um tenant pra ver o histórico.
|
||||
</div>
|
||||
<div v-else-if="!waRecentTopups.length" class="text-xs text-[var(--text-color-secondary)] italic py-4 text-center">
|
||||
Nenhum topup/ajuste ainda pra esse tenant.
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-1 max-h-[340px] overflow-y-auto text-xs">
|
||||
<div v-for="tx in waRecentTopups" :key="tx.id"
|
||||
class="grid grid-cols-[auto_1fr_auto_auto] items-center gap-2 p-2 rounded hover:bg-[var(--surface-hover)]">
|
||||
<span class="inline-flex items-center px-1.5 py-px rounded text-[0.62rem] font-bold uppercase"
|
||||
:class="waKindBadge[tx.kind]?.cls">{{ waKindBadge[tx.kind]?.label || tx.kind }}</span>
|
||||
<span class="truncate">{{ tx.note || '—' }}</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)]">{{ formatDate(tx.created_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabPanel>
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
|
||||
@@ -741,5 +1086,72 @@ onMounted(() => {
|
||||
</div>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<!-- Dialog: Novo/Editar pacote WhatsApp -->
|
||||
<Dialog
|
||||
v-model:visible="waPkgDialog"
|
||||
modal
|
||||
:draggable="false"
|
||||
:closable="true"
|
||||
:dismissableMask="true"
|
||||
class="dc-dialog w-[32rem]"
|
||||
:breakpoints="{ '1199px': '90vw', '768px': '94vw' }"
|
||||
:pt="{
|
||||
header: { class: '!p-3 !rounded-t-[12px] border-b border-[var(--surface-border)] shadow-[0_1px_0_0_rgba(255,255,255,0.06)] bg-gray-100' },
|
||||
content: { class: '!p-3' },
|
||||
footer: { class: '!p-0 !rounded-b-[12px] border-t border-[var(--surface-border)] shadow-[0_1px_0_0_rgba(255,255,255,0.06)] bg-gray-100' }
|
||||
}"
|
||||
pt:mask:class="backdrop-blur-xs"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex w-full items-center gap-3 px-1">
|
||||
<i class="pi pi-whatsapp text-emerald-500 text-xl" />
|
||||
<div class="min-w-0">
|
||||
<div class="text-base font-semibold truncate">{{ waEditingPkgId ? 'Editar pacote' : 'Novo pacote WhatsApp' }}</div>
|
||||
<div class="text-xs opacity-50">Créditos consumidos no canal AgenciaPSI Oficial (Twilio)</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="font-medium text-sm">Nome *</label>
|
||||
<InputText v-model="waPkgForm.name" maxlength="100" placeholder="Ex: Pacote Mensal 500" class="w-full" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="font-medium text-sm">Descrição</label>
|
||||
<InputText v-model="waPkgForm.description" maxlength="500" placeholder="Ex: Ideal pra clínicas pequenas" class="w-full" />
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="font-medium text-sm">Créditos *</label>
|
||||
<InputNumber v-model="waPkgForm.credits" :min="1" :max="100000" fluid />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="font-medium text-sm">Preço *</label>
|
||||
<InputNumber v-model="waPkgForm.price_brl" mode="currency" currency="BRL" locale="pt-BR" :min="0.01" :maxFractionDigits="2" fluid />
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-3 items-end">
|
||||
<div class="flex items-center gap-2">
|
||||
<ToggleSwitch v-model="waPkgForm.is_active" />
|
||||
<label class="text-sm">Ativo</label>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<ToggleSwitch v-model="waPkgForm.is_featured" />
|
||||
<label class="text-sm">Destaque</label>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-xs font-medium">Posição</label>
|
||||
<InputNumber v-model="waPkgForm.position" :min="0" :max="9999" fluid />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="flex items-center justify-end gap-2 px-3 py-3">
|
||||
<Button label="Cancelar" severity="secondary" text class="rounded-full hover:!text-red-500" @click="waPkgDialog = false" />
|
||||
<Button :label="waEditingPkgId ? 'Salvar' : 'Criar'" icon="pi pi-check" class="rounded-full" @click="saveWaPkg" />
|
||||
</div>
|
||||
</template>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
Reference in New Issue
Block a user