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,243 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/utils/addonExtratoExport.js
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { htmlToPdfDownload } from '@/services/pdf.service';
|
||||
|
||||
// ─── labels ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOVEMENT_LABELS = {
|
||||
purchase: 'Compra',
|
||||
consumption: 'Consumo',
|
||||
adjustment: 'Ajuste',
|
||||
refund: 'Reembolso',
|
||||
bonus: 'Bônus',
|
||||
expiration: 'Expiração'
|
||||
};
|
||||
|
||||
const ADDON_LABELS = {
|
||||
sms: 'SMS',
|
||||
email: 'E-mail',
|
||||
server: 'Servidor',
|
||||
domain: 'Domínio'
|
||||
};
|
||||
|
||||
// ─── formatadores ───────────────────────────────────────────────────────────
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
try {
|
||||
return new Date(iso).toLocaleString('pt-BR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function fmtAmount(row) {
|
||||
const amt = Number(row.amount) || 0;
|
||||
if (row.type === 'purchase' || row.type === 'bonus' || row.type === 'refund') {
|
||||
return `+${amt}`;
|
||||
}
|
||||
if (row.type === 'consumption') {
|
||||
return `-${Math.abs(amt)}`;
|
||||
}
|
||||
return amt >= 0 ? `+${amt}` : `${amt}`;
|
||||
}
|
||||
|
||||
function fmtBRL(cents) {
|
||||
if (!cents) return '';
|
||||
return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
|
||||
}
|
||||
|
||||
function addonLabel(type) {
|
||||
return ADDON_LABELS[type] || type || '';
|
||||
}
|
||||
|
||||
function movementLabel(type) {
|
||||
return MOVEMENT_LABELS[type] || type || '';
|
||||
}
|
||||
|
||||
// ─── sanitização para CSV ───────────────────────────────────────────────────
|
||||
|
||||
function csvCell(value) {
|
||||
if (value === null || value === undefined) return '';
|
||||
const s = String(value)
|
||||
.replace(/[\r\n]+/g, ' ')
|
||||
.replace(/"/g, '""')
|
||||
.trim();
|
||||
// Previne CSV injection: prefixa com espaço se começar com =, +, -, @
|
||||
const safe = /^[=+\-@]/.test(s) ? ' ' + s : s;
|
||||
return `"${safe}"`;
|
||||
}
|
||||
|
||||
function csvLine(cells) {
|
||||
return cells.map(csvCell).join(';');
|
||||
}
|
||||
|
||||
// ─── export CSV ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function buildExtratoCSV(rows, summary, periodLabel) {
|
||||
const header = ['Data', 'Addon', 'Tipo', 'Quantidade', 'Saldo após', 'Descrição', 'Valor (R$)', 'Método', 'Referência'];
|
||||
|
||||
const lines = [csvLine(header)];
|
||||
for (const r of rows) {
|
||||
lines.push(
|
||||
csvLine([
|
||||
fmtDate(r.created_at),
|
||||
addonLabel(r.addon_type),
|
||||
movementLabel(r.type),
|
||||
fmtAmount(r),
|
||||
r.balance_after ?? '',
|
||||
r.description ?? '',
|
||||
r.price_cents ? fmtBRL(r.price_cents) : '',
|
||||
r.payment_method ?? '',
|
||||
r.payment_reference ?? ''
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
// Rodapé com resumo
|
||||
lines.push('');
|
||||
lines.push(csvLine(['Período', periodLabel, '', '', '', '', '', '', '']));
|
||||
lines.push(csvLine(['Registros', summary.totalRows, '', '', '', '', '', '', '']));
|
||||
lines.push(csvLine(['Total comprado (créditos)', summary.purchasedCredits, '', '', '', '', '', '', '']));
|
||||
lines.push(csvLine(['Total comprado (R$)', fmtBRL(summary.purchasedCents), '', '', '', '', '', '', '']));
|
||||
lines.push(csvLine(['Total consumido (créditos)', summary.consumedCredits, '', '', '', '', '', '', '']));
|
||||
|
||||
return '\uFEFF' + lines.join('\r\n');
|
||||
}
|
||||
|
||||
export function downloadExtratoCSV(rows, summary, periodLabel, filename) {
|
||||
const csv = buildExtratoCSV(rows, summary, periodLabel);
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename || `extrato-addons-${Date.now()}.csv`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
// ─── export PDF ─────────────────────────────────────────────────────────────
|
||||
|
||||
function htmlEscape(s) {
|
||||
if (s === null || s === undefined) return '';
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function buildExtratoHTML(rows, summary, periodLabel, tenantName) {
|
||||
const tbody = rows
|
||||
.map(
|
||||
(r) => `
|
||||
<tr>
|
||||
<td>${htmlEscape(fmtDate(r.created_at))}</td>
|
||||
<td>${htmlEscape(addonLabel(r.addon_type))}</td>
|
||||
<td>${htmlEscape(movementLabel(r.type))}</td>
|
||||
<td class="num">${htmlEscape(fmtAmount(r))}</td>
|
||||
<td class="num">${htmlEscape(r.balance_after ?? '')}</td>
|
||||
<td>${htmlEscape(r.description ?? '')}</td>
|
||||
<td class="num">${htmlEscape(r.price_cents ? fmtBRL(r.price_cents) : '')}</td>
|
||||
<td>${htmlEscape(r.payment_reference ?? '')}</td>
|
||||
</tr>
|
||||
`
|
||||
)
|
||||
.join('');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Extrato de Recursos Extras</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: 'Segoe UI', Arial, sans-serif; color: #1a1a1a; margin: 0; padding: 24px; font-size: 11px; }
|
||||
h1 { font-size: 18px; margin: 0 0 4px 0; color: #2e3440; }
|
||||
.subtitle { color: #6b7280; font-size: 11px; margin-bottom: 16px; }
|
||||
.summary { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
|
||||
.card { flex: 1 1 150px; border: 1px solid #e5e7eb; border-radius: 6px; padding: 8px 12px; background: #f9fafb; }
|
||||
.card .label { font-size: 9px; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
|
||||
.card .value { font-size: 14px; font-weight: 600; color: #111827; margin-top: 2px; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 10px; }
|
||||
th { background: #374151; color: #fff; padding: 6px 8px; text-align: left; font-weight: 600; }
|
||||
td { padding: 5px 8px; border-bottom: 1px solid #e5e7eb; }
|
||||
td.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
tr:nth-child(even) td { background: #f9fafb; }
|
||||
.footer { margin-top: 16px; font-size: 9px; color: #9ca3af; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Extrato de Recursos Extras</h1>
|
||||
<div class="subtitle">
|
||||
${htmlEscape(tenantName || '')} · Período: <strong>${htmlEscape(periodLabel)}</strong> ·
|
||||
Gerado em ${htmlEscape(fmtDate(new Date().toISOString()))}
|
||||
</div>
|
||||
|
||||
<div class="summary">
|
||||
<div class="card"><div class="label">Registros</div><div class="value">${summary.totalRows}</div></div>
|
||||
<div class="card"><div class="label">Comprado (créditos)</div><div class="value">${summary.purchasedCredits}</div></div>
|
||||
<div class="card"><div class="label">Comprado (R$)</div><div class="value">${htmlEscape(fmtBRL(summary.purchasedCents) || 'R$ 0,00')}</div></div>
|
||||
<div class="card"><div class="label">Consumido (créditos)</div><div class="value">${summary.consumedCredits}</div></div>
|
||||
</div>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Data</th>
|
||||
<th>Addon</th>
|
||||
<th>Tipo</th>
|
||||
<th class="num">Qtd.</th>
|
||||
<th class="num">Saldo após</th>
|
||||
<th>Descrição</th>
|
||||
<th class="num">Valor</th>
|
||||
<th>Referência</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${tbody || '<tr><td colspan="8" style="text-align:center;color:#9ca3af;padding:16px;">Sem transações no período</td></tr>'}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="footer">AgênciaPSI · Extrato de débitos e créditos de recursos extras</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export async function downloadExtratoPDF(rows, summary, periodLabel, tenantName, filename) {
|
||||
const html = buildExtratoHTML(rows, summary, periodLabel, tenantName);
|
||||
await htmlToPdfDownload(html, filename || `extrato-addons-${Date.now()}.pdf`);
|
||||
}
|
||||
|
||||
// ─── util exposto pra página ────────────────────────────────────────────────
|
||||
|
||||
export const formatters = {
|
||||
fmtDate,
|
||||
fmtAmount,
|
||||
fmtBRL,
|
||||
addonLabel,
|
||||
movementLabel
|
||||
};
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/utils/auditoriaExport.js
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { htmlToPdfDownload } from '@/services/pdf.service';
|
||||
|
||||
const SOURCE_LABELS = {
|
||||
audit_logs: 'Auditoria',
|
||||
document_access_logs: 'Acesso a documento',
|
||||
patient_status_history: 'Status paciente',
|
||||
notification_logs: 'Notificação',
|
||||
addon_transactions: 'Recurso extra'
|
||||
};
|
||||
|
||||
const ENTITY_LABELS = {
|
||||
patients: 'Paciente',
|
||||
agenda_eventos: 'Evento de agenda',
|
||||
financial_records: 'Registro financeiro',
|
||||
documents: 'Documento',
|
||||
tenant_members: 'Membro do tenant',
|
||||
document: 'Documento',
|
||||
notification: 'Notificação',
|
||||
patient_status: 'Status do paciente',
|
||||
addon_transaction: 'Transação de recurso'
|
||||
};
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
try {
|
||||
return new Date(iso).toLocaleString('pt-BR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
});
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function sourceLabel(src) {
|
||||
return SOURCE_LABELS[src] || src || '';
|
||||
}
|
||||
|
||||
export function entityLabel(ent) {
|
||||
return ENTITY_LABELS[ent] || ent || '';
|
||||
}
|
||||
|
||||
// ─── sanitização CSV (anti-injection) ────────────────────────────────────────
|
||||
|
||||
function csvCell(value) {
|
||||
if (value === null || value === undefined) return '';
|
||||
const s = String(value)
|
||||
.replace(/[\r\n]+/g, ' ')
|
||||
.replace(/"/g, '""')
|
||||
.trim();
|
||||
const safe = /^[=+\-@]/.test(s) ? ' ' + s : s;
|
||||
return `"${safe}"`;
|
||||
}
|
||||
|
||||
function csvLine(cells) {
|
||||
return cells.map(csvCell).join(';');
|
||||
}
|
||||
|
||||
export function buildAuditCSV(rows, summary, periodLabel, userDisplay) {
|
||||
const header = ['Data/Hora', 'Origem', 'Entidade', 'ID entidade', 'Ação', 'Descrição', 'Usuário'];
|
||||
const lines = [csvLine(header)];
|
||||
|
||||
for (const r of rows) {
|
||||
lines.push(
|
||||
csvLine([
|
||||
fmtDate(r.occurred_at),
|
||||
sourceLabel(r.source),
|
||||
entityLabel(r.entity_type),
|
||||
r.entity_id ?? '',
|
||||
r.action ?? '',
|
||||
r.description ?? '',
|
||||
userDisplay(r.user_id)
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
lines.push(csvLine(['Período', periodLabel]));
|
||||
lines.push(csvLine(['Total de registros', summary.totalRows]));
|
||||
lines.push(csvLine(['Usuários distintos', summary.distinctUsers]));
|
||||
|
||||
return '\uFEFF' + lines.join('\r\n');
|
||||
}
|
||||
|
||||
export function downloadAuditCSV(rows, summary, periodLabel, userDisplay, filename) {
|
||||
const csv = buildAuditCSV(rows, summary, periodLabel, userDisplay);
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename || `auditoria-${Date.now()}.csv`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
// ─── PDF ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function htmlEscape(s) {
|
||||
if (s === null || s === undefined) return '';
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function buildAuditHTML(rows, summary, periodLabel, tenantName, userDisplay) {
|
||||
const tbody = rows
|
||||
.map(
|
||||
(r) => `
|
||||
<tr>
|
||||
<td>${htmlEscape(fmtDate(r.occurred_at))}</td>
|
||||
<td>${htmlEscape(sourceLabel(r.source))}</td>
|
||||
<td>${htmlEscape(entityLabel(r.entity_type))}</td>
|
||||
<td>${htmlEscape(r.description ?? '')}</td>
|
||||
<td>${htmlEscape(userDisplay(r.user_id))}</td>
|
||||
</tr>`
|
||||
)
|
||||
.join('');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Relatório de Auditoria</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: 'Segoe UI', Arial, sans-serif; color: #1a1a1a; margin: 0; padding: 24px; font-size: 10px; }
|
||||
h1 { font-size: 18px; margin: 0 0 4px 0; color: #2e3440; }
|
||||
.subtitle { color: #6b7280; font-size: 10px; margin-bottom: 16px; }
|
||||
.summary { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 14px; }
|
||||
.card { flex: 1 1 120px; border: 1px solid #e5e7eb; border-radius: 6px; padding: 6px 10px; background: #f9fafb; }
|
||||
.card .label { font-size: 8px; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
|
||||
.card .value { font-size: 13px; font-weight: 600; color: #111827; margin-top: 2px; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 9px; }
|
||||
th { background: #374151; color: #fff; padding: 5px 7px; text-align: left; font-weight: 600; }
|
||||
td { padding: 4px 7px; border-bottom: 1px solid #e5e7eb; vertical-align: top; }
|
||||
tr:nth-child(even) td { background: #f9fafb; }
|
||||
.footer { margin-top: 14px; font-size: 8px; color: #9ca3af; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Relatório de Auditoria</h1>
|
||||
<div class="subtitle">
|
||||
${htmlEscape(tenantName || '')} · Período: <strong>${htmlEscape(periodLabel)}</strong>
|
||||
· Gerado em ${htmlEscape(fmtDate(new Date().toISOString()))}
|
||||
</div>
|
||||
|
||||
<div class="summary">
|
||||
<div class="card"><div class="label">Registros</div><div class="value">${summary.totalRows}</div></div>
|
||||
<div class="card"><div class="label">Usuários distintos</div><div class="value">${summary.distinctUsers}</div></div>
|
||||
</div>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Data/Hora</th>
|
||||
<th>Origem</th>
|
||||
<th>Entidade</th>
|
||||
<th>Descrição</th>
|
||||
<th>Usuário</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${tbody || '<tr><td colspan="5" style="text-align:center;color:#9ca3af;padding:16px;">Nenhum evento no período</td></tr>'}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="footer">AgênciaPSI · Registro imutável de operações de tratamento (LGPD Art. 37)</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export async function downloadAuditPDF(rows, summary, periodLabel, tenantName, userDisplay, filename) {
|
||||
const html = buildAuditHTML(rows, summary, periodLabel, tenantName, userDisplay);
|
||||
await htmlToPdfDownload(html, filename || `auditoria-${Date.now()}.pdf`);
|
||||
}
|
||||
|
||||
export const auditFormatters = {
|
||||
fmtDate,
|
||||
sourceLabel,
|
||||
entityLabel
|
||||
};
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/utils/excelExport.js
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import ExcelJS from 'exceljs';
|
||||
|
||||
/**
|
||||
* Tipos de coluna suportados:
|
||||
* text — string (default)
|
||||
* money — cents (divide por 100 + formata BRL)
|
||||
* date — ISO/Date (formata dd/mm/yyyy hh:mm)
|
||||
* number — inteiro/decimal
|
||||
*/
|
||||
|
||||
function fmtDateCell(value) {
|
||||
if (!value) return null;
|
||||
const d = value instanceof Date ? value : new Date(value);
|
||||
if (isNaN(d.getTime())) return String(value);
|
||||
return d;
|
||||
}
|
||||
|
||||
function sanitizeText(value) {
|
||||
if (value === null || value === undefined) return '';
|
||||
const s = String(value).replace(/[\r\n]+/g, ' ').trim();
|
||||
// Previne fórmula Excel: prefixa com espaço se começar com =, +, -, @
|
||||
return /^[=+\-@]/.test(s) ? ' ' + s : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gera workbook Excel a partir de headers e rows.
|
||||
* headers: [{ key, label, type: 'text'|'money'|'date'|'number', width?: number }]
|
||||
* rows: array de objetos
|
||||
*/
|
||||
export async function buildExcelBlob({ sheetName = 'Dados', headers, rows, footerRows = [] }) {
|
||||
const wb = new ExcelJS.Workbook();
|
||||
wb.creator = 'AgenciaPSI';
|
||||
wb.created = new Date();
|
||||
|
||||
const ws = wb.addWorksheet(sheetName, {
|
||||
views: [{ state: 'frozen', ySplit: 1 }]
|
||||
});
|
||||
|
||||
// ── Cabeçalho ──────────────────────────────────────────────
|
||||
ws.columns = headers.map((h) => ({
|
||||
header: h.label,
|
||||
key: h.key,
|
||||
width: h.width || 18
|
||||
}));
|
||||
|
||||
const headerRow = ws.getRow(1);
|
||||
headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' } };
|
||||
headerRow.fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FF374151' }
|
||||
};
|
||||
headerRow.alignment = { vertical: 'middle', horizontal: 'left' };
|
||||
headerRow.height = 20;
|
||||
|
||||
// ── Rows ───────────────────────────────────────────────────
|
||||
for (const row of rows) {
|
||||
const cells = {};
|
||||
for (const h of headers) {
|
||||
const raw = row[h.key];
|
||||
switch (h.type) {
|
||||
case 'money': {
|
||||
const cents = Number(raw) || 0;
|
||||
cells[h.key] = cents / 100;
|
||||
break;
|
||||
}
|
||||
case 'date':
|
||||
cells[h.key] = fmtDateCell(raw);
|
||||
break;
|
||||
case 'number':
|
||||
cells[h.key] = Number(raw) || 0;
|
||||
break;
|
||||
default:
|
||||
cells[h.key] = sanitizeText(raw);
|
||||
}
|
||||
}
|
||||
const r = ws.addRow(cells);
|
||||
|
||||
// Formatação por tipo
|
||||
headers.forEach((h, idx) => {
|
||||
const cell = r.getCell(idx + 1);
|
||||
if (h.type === 'money') {
|
||||
cell.numFmt = '"R$" #,##0.00;[Red]-"R$" #,##0.00';
|
||||
} else if (h.type === 'date') {
|
||||
cell.numFmt = 'dd/mm/yyyy hh:mm';
|
||||
} else if (h.type === 'number') {
|
||||
cell.numFmt = '#,##0';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Zebra (linhas pares) ───────────────────────────────────
|
||||
for (let i = 2; i <= ws.rowCount; i++) {
|
||||
if (i % 2 === 0) {
|
||||
ws.getRow(i).fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FFF9FAFB' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ── Footer com resumo ──────────────────────────────────────
|
||||
if (footerRows.length) {
|
||||
ws.addRow([]);
|
||||
for (const fr of footerRows) {
|
||||
const r = ws.addRow(fr);
|
||||
r.font = { bold: true };
|
||||
}
|
||||
}
|
||||
|
||||
// ── Borders ────────────────────────────────────────────────
|
||||
const borderStyle = { style: 'thin', color: { argb: 'FFE5E7EB' } };
|
||||
ws.eachRow((row) => {
|
||||
row.eachCell((cell) => {
|
||||
cell.border = { top: borderStyle, left: borderStyle, bottom: borderStyle, right: borderStyle };
|
||||
});
|
||||
});
|
||||
|
||||
const buf = await wb.xlsx.writeBuffer();
|
||||
return new Blob([buf], {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
});
|
||||
}
|
||||
|
||||
export async function downloadExcel({ filename, ...opts }) {
|
||||
const blob = await buildExcelBlob(opts);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename || `export-${Date.now()}.xlsx`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/utils/lgpdExportFormats.js
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { htmlToPdfDownload } from '@/services/pdf.service';
|
||||
|
||||
function htmlEscape(s) {
|
||||
if (s === null || s === undefined) return '';
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
try {
|
||||
return new Date(iso).toLocaleString('pt-BR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
} catch {
|
||||
return String(iso);
|
||||
}
|
||||
}
|
||||
|
||||
function fmtBRL(cents) {
|
||||
if (cents === null || cents === undefined) return '';
|
||||
const n = typeof cents === 'number' ? cents / 100 : Number(cents) / 100;
|
||||
if (!isFinite(n)) return '';
|
||||
return n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
|
||||
}
|
||||
|
||||
function renderKV(label, value) {
|
||||
if (value === null || value === undefined || value === '') return '';
|
||||
return `<div class="kv"><span class="k">${htmlEscape(label)}:</span> <span class="v">${htmlEscape(value)}</span></div>`;
|
||||
}
|
||||
|
||||
function renderSectionHeader(title, count) {
|
||||
const badge = count != null ? `<span class="count">${count}</span>` : '';
|
||||
return `<h2>${htmlEscape(title)} ${badge}</h2>`;
|
||||
}
|
||||
|
||||
function renderTable(headers, rows) {
|
||||
if (!rows || !rows.length) {
|
||||
return '<p class="empty">Sem registros.</p>';
|
||||
}
|
||||
const th = headers.map((h) => `<th>${htmlEscape(h.label)}</th>`).join('');
|
||||
const body = rows
|
||||
.map(
|
||||
(r) =>
|
||||
'<tr>' +
|
||||
headers
|
||||
.map((h) => {
|
||||
const raw = h.get ? h.get(r) : r[h.key];
|
||||
return `<td>${htmlEscape(raw ?? '')}</td>`;
|
||||
})
|
||||
.join('') +
|
||||
'</tr>'
|
||||
)
|
||||
.join('');
|
||||
return `<table><thead><tr>${th}</tr></thead><tbody>${body}</tbody></table>`;
|
||||
}
|
||||
|
||||
export function buildLgpdHTML(payload, tenantName) {
|
||||
if (!payload) return '';
|
||||
|
||||
const meta = payload.export_metadata || {};
|
||||
const p = payload.paciente || {};
|
||||
|
||||
const sections = [];
|
||||
|
||||
// ── Cabeçalho LGPD ─────────────────────────────────────────────────────
|
||||
sections.push(`
|
||||
<div class="cover">
|
||||
<h1>Relatório de Dados Pessoais</h1>
|
||||
<p class="lead">
|
||||
Documento gerado em atendimento ao <strong>art. 18, II da LGPD</strong>
|
||||
(portabilidade de dados do titular).
|
||||
</p>
|
||||
<div class="meta">
|
||||
${renderKV('Controlador', tenantName || 'AgênciaPSI')}
|
||||
${renderKV('Gerado em', fmtDate(meta.generated_at))}
|
||||
${renderKV('Fundamento', meta.lgpd_basis)}
|
||||
${renderKV('Versão do formato', meta.format_version)}
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
// ── Dados pessoais ─────────────────────────────────────────────────────
|
||||
sections.push(renderSectionHeader('1. Dados pessoais do titular'));
|
||||
sections.push(`
|
||||
<div class="grid">
|
||||
${renderKV('Nome completo', p.nome_completo)}
|
||||
${renderKV('Nome social', p.nome_social)}
|
||||
${renderKV('Apelido', p.apelido)}
|
||||
${renderKV('CPF', p.cpf)}
|
||||
${renderKV('RG', p.rg)}
|
||||
${renderKV('Data de nascimento', p.data_nascimento)}
|
||||
${renderKV('Gênero', p.genero)}
|
||||
${renderKV('Estado civil', p.estado_civil)}
|
||||
${renderKV('Profissão', p.profissao)}
|
||||
${renderKV('Escolaridade', p.escolaridade)}
|
||||
${renderKV('Telefone', p.telefone)}
|
||||
${renderKV('E-mail', p.email)}
|
||||
${renderKV('Endereço', [p.endereco_logradouro, p.endereco_numero, p.endereco_bairro, p.endereco_cidade, p.endereco_uf, p.endereco_cep].filter(Boolean).join(', '))}
|
||||
${renderKV('Status atual', p.status)}
|
||||
${renderKV('Data de criação do cadastro', fmtDate(p.created_at))}
|
||||
</div>
|
||||
`);
|
||||
|
||||
// ── Contatos ───────────────────────────────────────────────────────────
|
||||
const contatos = payload.contatos || [];
|
||||
sections.push(renderSectionHeader('2. Contatos', contatos.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Nome', key: 'nome' },
|
||||
{ label: 'Tipo', key: 'tipo' },
|
||||
{ label: 'Relação', key: 'relacao' },
|
||||
{ label: 'Telefone', key: 'telefone' },
|
||||
{ label: 'E-mail', key: 'email' }
|
||||
],
|
||||
contatos
|
||||
)
|
||||
);
|
||||
|
||||
// ── Contatos de apoio ──────────────────────────────────────────────────
|
||||
const apoio = payload.contatos_apoio || [];
|
||||
sections.push(renderSectionHeader('3. Contatos de apoio', apoio.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Nome', key: 'nome' },
|
||||
{ label: 'Vínculo', key: 'vinculo' },
|
||||
{ label: 'Telefone', key: 'telefone' }
|
||||
],
|
||||
apoio
|
||||
)
|
||||
);
|
||||
|
||||
// ── Histórico de status ────────────────────────────────────────────────
|
||||
const status = payload.historico_status || [];
|
||||
sections.push(renderSectionHeader('4. Histórico de status', status.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Data', key: 'alterado_em', get: (r) => fmtDate(r.alterado_em) },
|
||||
{ label: 'Anterior', key: 'status_anterior' },
|
||||
{ label: 'Novo', key: 'status_novo' },
|
||||
{ label: 'Motivo', key: 'motivo' }
|
||||
],
|
||||
status
|
||||
)
|
||||
);
|
||||
|
||||
// ── Eventos de agenda ──────────────────────────────────────────────────
|
||||
const agenda = payload.eventos_agenda || [];
|
||||
sections.push(renderSectionHeader('5. Eventos de agenda', agenda.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Início', key: 'inicio_em', get: (r) => fmtDate(r.inicio_em) },
|
||||
{ label: 'Tipo', key: 'tipo' },
|
||||
{ label: 'Status', key: 'status' },
|
||||
{ label: 'Observações', key: 'observacoes' }
|
||||
],
|
||||
agenda
|
||||
)
|
||||
);
|
||||
|
||||
// ── Registros financeiros ──────────────────────────────────────────────
|
||||
const financeiro = payload.registros_financeiros || [];
|
||||
sections.push(renderSectionHeader('6. Registros financeiros', financeiro.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Criado em', key: 'created_at', get: (r) => fmtDate(r.created_at) },
|
||||
{ label: 'Vencimento', key: 'due_date' },
|
||||
{ label: 'Valor', key: 'amount', get: (r) => fmtBRL(r.amount) },
|
||||
{ label: 'Valor final', key: 'final_amount', get: (r) => fmtBRL(r.final_amount) },
|
||||
{ label: 'Status', key: 'status' },
|
||||
{ label: 'Método', key: 'payment_method' }
|
||||
],
|
||||
financeiro
|
||||
)
|
||||
);
|
||||
|
||||
// ── Documentos ─────────────────────────────────────────────────────────
|
||||
const docs = payload.documentos || [];
|
||||
sections.push(renderSectionHeader('7. Documentos', docs.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Nome', key: 'nome_original' },
|
||||
{ label: 'Tipo', key: 'tipo_documento' },
|
||||
{ label: 'Categoria', key: 'categoria' },
|
||||
{ label: 'Tamanho (bytes)', key: 'tamanho_bytes' },
|
||||
{ label: 'Upload em', key: 'uploaded_at', get: (r) => fmtDate(r.uploaded_at) }
|
||||
],
|
||||
docs
|
||||
)
|
||||
);
|
||||
|
||||
// ── Notificações ───────────────────────────────────────────────────────
|
||||
const notifs = payload.notificacoes_enviadas || [];
|
||||
sections.push(renderSectionHeader('8. Notificações enviadas', notifs.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Data', key: 'created_at', get: (r) => fmtDate(r.created_at) },
|
||||
{ label: 'Canal', key: 'channel' },
|
||||
{ label: 'Destinatário', key: 'recipient_address' },
|
||||
{ label: 'Status', key: 'status' }
|
||||
],
|
||||
notifs
|
||||
)
|
||||
);
|
||||
|
||||
// ── Audit trail ────────────────────────────────────────────────────────
|
||||
const audit = payload.audit_trail || [];
|
||||
sections.push(renderSectionHeader('9. Auditoria de alterações', audit.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Data', key: 'created_at', get: (r) => fmtDate(r.created_at) },
|
||||
{ label: 'Ação', key: 'action' },
|
||||
{ label: 'Campos alterados', key: 'changed_fields', get: (r) => (r.changed_fields || []).join(', ') }
|
||||
],
|
||||
audit
|
||||
)
|
||||
);
|
||||
|
||||
// ── Acessos a documentos ───────────────────────────────────────────────
|
||||
const acessos = payload.acessos_a_documentos || [];
|
||||
sections.push(renderSectionHeader('10. Acessos a documentos', acessos.length));
|
||||
sections.push(
|
||||
renderTable(
|
||||
[
|
||||
{ label: 'Data', key: 'acessado_em', get: (r) => fmtDate(r.acessado_em) },
|
||||
{ label: 'Ação', key: 'acao' }
|
||||
],
|
||||
acessos
|
||||
)
|
||||
);
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Relatório LGPD - ${htmlEscape(p.nome_completo || 'paciente')}</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: 'Segoe UI', Arial, sans-serif; color: #1a1a1a; margin: 0; padding: 20px; font-size: 10px; }
|
||||
h1 { font-size: 20px; margin: 0 0 8px; color: #1e3a8a; }
|
||||
h2 { font-size: 13px; margin: 18px 0 6px; color: #1f2937; border-bottom: 1px solid #e5e7eb; padding-bottom: 3px; }
|
||||
h2 .count { display: inline-block; background: #3b82f6; color: #fff; border-radius: 999px; padding: 0 6px; font-size: 9px; margin-left: 6px; vertical-align: middle; }
|
||||
.cover { margin-bottom: 16px; padding: 12px; background: #f3f4f6; border-left: 4px solid #1e3a8a; border-radius: 4px; }
|
||||
.lead { font-size: 10px; color: #4b5563; margin: 0 0 8px; }
|
||||
.meta .kv, .grid .kv { font-size: 9px; }
|
||||
.kv .k { font-weight: 600; color: #6b7280; }
|
||||
.kv .v { color: #111827; }
|
||||
.grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 2px 12px; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 9px; margin-top: 4px; }
|
||||
th { background: #374151; color: #fff; padding: 4px 6px; text-align: left; font-weight: 600; }
|
||||
td { padding: 3px 6px; border-bottom: 1px solid #e5e7eb; }
|
||||
tr:nth-child(even) td { background: #f9fafb; }
|
||||
.empty { font-style: italic; color: #9ca3af; font-size: 9px; margin: 4px 0 8px; }
|
||||
.footer { margin-top: 24px; font-size: 8px; color: #9ca3af; text-align: center; border-top: 1px solid #e5e7eb; padding-top: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${sections.join('\n')}
|
||||
<div class="footer">
|
||||
AgênciaPSI · Relatório LGPD · Gerado em ${htmlEscape(fmtDate(meta.generated_at))}
|
||||
· O titular tem direito a requerer a correção de dados incompletos, inexatos ou desatualizados (Art. 18, III).
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export async function downloadLgpdPDF(payload, tenantName, filename) {
|
||||
const html = buildLgpdHTML(payload, tenantName);
|
||||
await htmlToPdfDownload(html, filename || `lgpd-export-${Date.now()}.pdf`);
|
||||
}
|
||||
Reference in New Issue
Block a user