2644e60bb6
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>
522 lines
22 KiB
Vue
522 lines
22 KiB
Vue
<!--
|
|
|--------------------------------------------------------------------------
|
|
| Agência PSI
|
|
|--------------------------------------------------------------------------
|
|
| Criado e desenvolvido por Leonardo Nohama
|
|
|
|
|
| Tecnologia aplicada à escuta.
|
|
| Estrutura para o cuidado.
|
|
|
|
|
| Arquivo: src/views/pages/saas/SaasDocumentTemplatesPage.vue
|
|
| Data: 2026
|
|
| Local: São Carlos/SP — Brasil
|
|
|--------------------------------------------------------------------------
|
|
| © 2026 — Todos os direitos reservados
|
|
|--------------------------------------------------------------------------
|
|
| Gestao de templates globais de documentos pelo SaaS admin.
|
|
| Templates globais (is_global = true) ficam disponiveis para todos os tenants.
|
|
|--------------------------------------------------------------------------
|
|
-->
|
|
<script setup>
|
|
import { ref, computed, onMounted } from 'vue'
|
|
import { supabase } from '@/lib/supabase/client'
|
|
import { useToast } from 'primevue/usetoast'
|
|
import { useConfirm } from 'primevue/useconfirm'
|
|
import { extractVariablesFromHtml, TEMPLATE_VARIABLES } from '@/services/DocumentTemplates.service'
|
|
import JoditEmailEditor from '@/components/ui/JoditEmailEditor.vue'
|
|
|
|
const toast = useToast()
|
|
const confirm = useConfirm()
|
|
|
|
// ── State ───────────────────────────────────────────────────
|
|
|
|
const loading = ref(false)
|
|
const rows = ref([])
|
|
const q = ref('')
|
|
|
|
const showDlg = ref(false)
|
|
const saving = ref(false)
|
|
const isEdit = ref(false)
|
|
const activeTab = ref('editor')
|
|
|
|
const TIPOS = [
|
|
{ value: 'declaracao_comparecimento', label: 'Declaração de comparecimento' },
|
|
{ value: 'atestado_psicologico', label: 'Atestado psicológico' },
|
|
{ value: 'relatorio_acompanhamento', label: 'Relatório de acompanhamento' },
|
|
{ value: 'recibo_pagamento', label: 'Recibo de pagamento' },
|
|
{ value: 'termo_consentimento', label: 'Termo de consentimento (TCLE)' },
|
|
{ value: 'encaminhamento', label: 'Encaminhamento' },
|
|
{ value: 'contrato_servicos', label: 'Contrato de prestação de serviços' },
|
|
{ value: 'tcle', label: 'TCLE' },
|
|
{ value: 'autorizacao_menor', label: 'Autorização para menor' },
|
|
{ value: 'laudo_psicologico', label: 'Laudo psicológico' },
|
|
{ value: 'parecer_psicologico', label: 'Parecer psicológico' },
|
|
{ value: 'termo_sigilo', label: 'Termo de sigilo' },
|
|
{ value: 'declaracao_inicio_tratamento', label: 'Declaração de início de tratamento' },
|
|
{ value: 'termo_alta', label: 'Termo de alta terapêutica' },
|
|
{ value: 'tcle_online', label: 'Consentimento atendimento online' },
|
|
{ value: 'outro', label: 'Outro' }
|
|
]
|
|
|
|
const form = ref(resetForm())
|
|
|
|
function resetForm() {
|
|
return {
|
|
id: null,
|
|
nome_template: '',
|
|
tipo: 'outro',
|
|
descricao: '',
|
|
corpo_html: '',
|
|
cabecalho_html: '',
|
|
rodape_html: '',
|
|
variaveis: [],
|
|
logo_url: '',
|
|
ativo: true
|
|
}
|
|
}
|
|
|
|
// ── Filtro ───────────────────────────────────────────────────
|
|
|
|
const filteredRows = computed(() => {
|
|
const term = String(q.value || '').trim().toLowerCase()
|
|
if (!term) return rows.value
|
|
return rows.value.filter(r =>
|
|
[r.nome_template, r.tipo, r.descricao].some(s =>
|
|
String(s || '').toLowerCase().includes(term)
|
|
)
|
|
)
|
|
})
|
|
|
|
// ── Fetch ───────────────────────────────────────────────────
|
|
|
|
async function fetchAll() {
|
|
loading.value = true
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from('document_templates')
|
|
.select('*')
|
|
.eq('is_global', true)
|
|
.order('nome_template', { ascending: true })
|
|
|
|
if (error) throw error
|
|
rows.value = data || []
|
|
} catch (e) {
|
|
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
onMounted(fetchAll)
|
|
|
|
// ── Dialog ──────────────────────────────────────────────────
|
|
|
|
function openCreate() {
|
|
form.value = resetForm()
|
|
isEdit.value = false
|
|
activeTab.value = 'editor'
|
|
showDlg.value = true
|
|
}
|
|
|
|
function openEdit(row) {
|
|
form.value = {
|
|
id: row.id,
|
|
nome_template: row.nome_template || '',
|
|
tipo: row.tipo || 'outro',
|
|
descricao: row.descricao || '',
|
|
corpo_html: row.corpo_html || '',
|
|
cabecalho_html: row.cabecalho_html || '',
|
|
rodape_html: row.rodape_html || '',
|
|
variaveis: row.variaveis || [],
|
|
logo_url: row.logo_url || '',
|
|
ativo: row.ativo ?? true
|
|
}
|
|
isEdit.value = true
|
|
activeTab.value = 'editor'
|
|
showDlg.value = true
|
|
}
|
|
|
|
// ── Save ────────────────────────────────────────────────────
|
|
|
|
async function save() {
|
|
const nome = String(form.value.nome_template || '').trim()
|
|
if (!nome) {
|
|
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Nome do template é obrigatório.' })
|
|
return
|
|
}
|
|
|
|
saving.value = true
|
|
try {
|
|
// Auto-extrair variaveis do HTML
|
|
const allHtml = (form.value.corpo_html || '') + (form.value.cabecalho_html || '') + (form.value.rodape_html || '')
|
|
const vars = extractVariablesFromHtml(allHtml)
|
|
|
|
const payload = {
|
|
nome_template: nome,
|
|
tipo: form.value.tipo || 'outro',
|
|
descricao: form.value.descricao || null,
|
|
corpo_html: form.value.corpo_html || '',
|
|
cabecalho_html: form.value.cabecalho_html || null,
|
|
rodape_html: form.value.rodape_html || null,
|
|
variaveis: vars,
|
|
logo_url: form.value.logo_url || null,
|
|
is_global: true,
|
|
ativo: form.value.ativo,
|
|
tenant_id: null,
|
|
owner_id: null
|
|
}
|
|
|
|
if (isEdit.value) {
|
|
const { error } = await supabase
|
|
.from('document_templates')
|
|
.update(payload)
|
|
.eq('id', form.value.id)
|
|
|
|
if (error) throw error
|
|
toast.add({ severity: 'success', summary: 'Salvo', detail: nome, life: 2000 })
|
|
} else {
|
|
const { error } = await supabase
|
|
.from('document_templates')
|
|
.insert(payload)
|
|
|
|
if (error) throw error
|
|
toast.add({ severity: 'success', summary: 'Criado', detail: nome, life: 2000 })
|
|
}
|
|
|
|
showDlg.value = false
|
|
fetchAll()
|
|
} catch (e) {
|
|
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
|
|
} finally {
|
|
saving.value = false
|
|
}
|
|
}
|
|
|
|
// ── Toggle ativo ────────────────────────────────────────────
|
|
|
|
async function toggleAtivo(row) {
|
|
try {
|
|
const { error } = await supabase
|
|
.from('document_templates')
|
|
.update({ ativo: !row.ativo })
|
|
.eq('id', row.id)
|
|
|
|
if (error) throw error
|
|
row.ativo = !row.ativo
|
|
toast.add({ severity: 'info', summary: row.ativo ? 'Ativado' : 'Desativado', detail: row.nome_template, life: 2000 })
|
|
} catch (e) {
|
|
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
|
|
}
|
|
}
|
|
|
|
// ── Delete ──────────────────────────────────────────────────
|
|
|
|
function onDelete(row) {
|
|
confirm.require({
|
|
message: `Excluir permanentemente "${row.nome_template}"? Essa ação não pode ser desfeita.`,
|
|
header: 'Excluir template global',
|
|
icon: 'pi pi-exclamation-triangle',
|
|
acceptClass: 'p-button-danger',
|
|
accept: async () => {
|
|
try {
|
|
const { error } = await supabase
|
|
.from('document_templates')
|
|
.delete()
|
|
.eq('id', row.id)
|
|
|
|
if (error) throw error
|
|
rows.value = rows.value.filter(r => r.id !== row.id)
|
|
toast.add({ severity: 'success', summary: 'Excluído', life: 2000 })
|
|
} catch (e) {
|
|
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
// ── Helpers ─────────────────────────────────────────────────
|
|
|
|
function tipoLabel(tipo) {
|
|
return TIPOS.find(t => t.value === tipo)?.label || tipo
|
|
}
|
|
|
|
// ── Preview com dados ficticios ─────────────────────────────
|
|
|
|
const SAMPLE = {
|
|
paciente_nome: 'Maria Silva Santos',
|
|
paciente_cpf: '123.456.789-00',
|
|
paciente_data_nascimento: '15/03/1990',
|
|
data_sessao: '28/03/2026',
|
|
hora_inicio: '14:00',
|
|
hora_fim: '14:50',
|
|
terapeuta_nome: 'Dr. João Oliveira',
|
|
terapeuta_crp: '06/12345',
|
|
clinica_nome: 'Clínica Exemplo',
|
|
clinica_endereco: 'Av. São Carlos, 500, Centro, São Carlos/SP',
|
|
clinica_telefone: '(16) 3333-1111',
|
|
clinica_cnpj: '12.345.678/0001-00',
|
|
valor: 'R$ 200,00',
|
|
valor_extenso: 'duzentos reais',
|
|
forma_pagamento: 'PIX',
|
|
data_atual: new Date().toLocaleDateString('pt-BR'),
|
|
data_atual_extenso: '29 de março de 2026',
|
|
cidade_estado: 'São Carlos/SP'
|
|
}
|
|
|
|
function previewReplace(html) {
|
|
return String(html || '').replace(/\{\{(\w+)\}\}/g, (m, k) =>
|
|
SAMPLE[k] !== undefined
|
|
? `<span style="background:#fef3c7;padding:1px 4px;border-radius:3px;">${SAMPLE[k]}</span>`
|
|
: `<span style="background:#fee2e2;padding:1px 4px;border-radius:3px;">${m}</span>`
|
|
)
|
|
}
|
|
|
|
// ── Variaveis agrupadas ─────────────────────────────────────
|
|
|
|
const variablesGrouped = computed(() => {
|
|
const groups = {}
|
|
for (const v of TEMPLATE_VARIABLES) {
|
|
if (!groups[v.grupo]) groups[v.grupo] = []
|
|
groups[v.grupo].push(v)
|
|
}
|
|
return groups
|
|
})
|
|
|
|
const cursorField = ref('corpo_html')
|
|
const editorCabecalho = ref(null)
|
|
const editorCorpo = ref(null)
|
|
const editorRodape = ref(null)
|
|
|
|
function insertVariable(key) {
|
|
const tag = `{{${key}}}`
|
|
const editorMap = {
|
|
cabecalho_html: editorCabecalho,
|
|
corpo_html: editorCorpo,
|
|
rodape_html: editorRodape
|
|
}
|
|
const editorRef = editorMap[cursorField.value]
|
|
if (editorRef?.value?.insertHTML) {
|
|
editorRef.value.insertHTML(tag)
|
|
} else {
|
|
form.value[cursorField.value] = (form.value[cursorField.value] || '') + tag
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<template>
|
|
<div class="flex flex-col gap-4 p-4">
|
|
<!-- Header -->
|
|
<div class="cfg-subheader">
|
|
<div class="cfg-subheader__icon"><i class="pi pi-file-edit" /></div>
|
|
<div class="min-w-0 flex-1">
|
|
<div class="cfg-subheader__title">Templates de Documentos</div>
|
|
<div class="cfg-subheader__sub">Templates globais disponíveis para todos os tenants (is_global = true).</div>
|
|
</div>
|
|
<div class="flex items-center gap-2 shrink-0">
|
|
<Button label="Novo template" icon="pi pi-plus" size="small" @click="openCreate" />
|
|
<Button icon="pi pi-refresh" severity="secondary" text :loading="loading" v-tooltip.bottom="'Recarregar'" @click="fetchAll" />
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Busca -->
|
|
<div class="mb-4">
|
|
<IconField>
|
|
<InputIcon class="pi pi-search" />
|
|
<InputText v-model="q" placeholder="Buscar template..." class="!w-[300px]" size="small" />
|
|
</IconField>
|
|
</div>
|
|
|
|
<!-- Loading -->
|
|
<div v-if="loading" class="flex items-center justify-center py-16">
|
|
<i class="pi pi-spinner pi-spin text-2xl text-[var(--text-color-secondary)]" />
|
|
</div>
|
|
|
|
<!-- Table -->
|
|
<DataTable
|
|
v-else
|
|
:value="filteredRows"
|
|
stripedRows
|
|
responsiveLayout="scroll"
|
|
class="text-sm"
|
|
:rowClass="(r) => !r.ativo ? 'opacity-50' : ''"
|
|
>
|
|
<template #empty>
|
|
<div class="text-center py-8 text-[var(--text-color-secondary)]">Nenhum template global cadastrado.</div>
|
|
</template>
|
|
|
|
<Column field="nome_template" header="Nome" sortable style="min-width: 200px">
|
|
<template #body="{ data }">
|
|
<div class="flex items-center gap-2">
|
|
<i class="pi pi-file text-primary" />
|
|
<span class="font-medium">{{ data.nome_template }}</span>
|
|
</div>
|
|
</template>
|
|
</Column>
|
|
|
|
<Column field="tipo" header="Tipo" sortable style="min-width: 180px">
|
|
<template #body="{ data }">
|
|
<Tag :value="tipoLabel(data.tipo)" severity="info" class="text-xs" />
|
|
</template>
|
|
</Column>
|
|
|
|
<Column field="variaveis" header="Variáveis" style="min-width: 100px">
|
|
<template #body="{ data }">
|
|
<span class="text-xs text-[var(--text-color-secondary)]">{{ data.variaveis?.length || 0 }}</span>
|
|
</template>
|
|
</Column>
|
|
|
|
<Column field="ativo" header="Status" style="width: 100px" bodyClass="text-center">
|
|
<template #body="{ data }">
|
|
<Tag
|
|
:value="data.ativo ? 'Ativo' : 'Inativo'"
|
|
:severity="data.ativo ? 'success' : 'danger'"
|
|
class="text-xs cursor-pointer"
|
|
@click="toggleAtivo(data)"
|
|
/>
|
|
</template>
|
|
</Column>
|
|
|
|
<Column header="Ações" style="width: 120px" bodyClass="text-center">
|
|
<template #body="{ data }">
|
|
<div class="flex items-center justify-center gap-1">
|
|
<Button icon="pi pi-pencil" text rounded size="small" @click="openEdit(data)" v-tooltip.top="'Editar'" />
|
|
<Button icon="pi pi-trash" text rounded size="small" severity="danger" @click="onDelete(data)" v-tooltip.top="'Excluir'" />
|
|
</div>
|
|
</template>
|
|
</Column>
|
|
</DataTable>
|
|
|
|
<!-- Dialog Create/Edit -->
|
|
<Dialog
|
|
v-model:visible="showDlg"
|
|
modal
|
|
maximizable
|
|
:draggable="false"
|
|
:closable="!saving"
|
|
:dismissableMask="!saving"
|
|
class="w-[65rem]"
|
|
:breakpoints="{ '1199px': '95vw', '768px': '98vw' }"
|
|
:pt="{
|
|
header: { class: '!p-4 !rounded-t-xl border-b border-[var(--surface-border)]' },
|
|
content: { class: '!p-4' },
|
|
footer: { class: '!p-3 !rounded-b-xl border-t border-[var(--surface-border)]' }
|
|
}"
|
|
pt:mask:class="backdrop-blur-xs"
|
|
>
|
|
<template #header>
|
|
<div class="flex items-center gap-3">
|
|
<span class="flex items-center justify-center w-8 h-8 rounded-lg bg-primary/10">
|
|
<i class="pi pi-file-edit text-primary" />
|
|
</span>
|
|
<div>
|
|
<div class="text-base font-semibold">{{ isEdit ? 'Editar' : 'Novo' }} template global</div>
|
|
<div class="text-xs text-[var(--text-color-secondary)]">Visível para todos os tenants</div>
|
|
</div>
|
|
</div>
|
|
</template>
|
|
|
|
<div class="flex flex-col gap-4">
|
|
<!-- Nome e tipo -->
|
|
<div class="grid grid-cols-1 sm:grid-cols-[1fr_200px] gap-3">
|
|
<div class="flex flex-col gap-1">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Nome do template</label>
|
|
<InputText v-model="form.nome_template" placeholder="Ex: Declaração de comparecimento" class="w-full" />
|
|
</div>
|
|
<div class="flex flex-col gap-1">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Tipo</label>
|
|
<Select v-model="form.tipo" :options="TIPOS" optionLabel="label" optionValue="value" class="w-full" />
|
|
</div>
|
|
</div>
|
|
|
|
<div class="grid grid-cols-1 sm:grid-cols-[1fr_100px] gap-3">
|
|
<div class="flex flex-col gap-1">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Descrição</label>
|
|
<InputText v-model="form.descricao" placeholder="Breve descrição" class="w-full" />
|
|
</div>
|
|
<div class="flex flex-col gap-1">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Status</label>
|
|
<Select v-model="form.ativo" :options="[{ value: true, label: 'Ativo' }, { value: false, label: 'Inativo' }]" optionLabel="label" optionValue="value" class="w-full" />
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Tabs -->
|
|
<div class="flex items-center gap-1 border-b border-[var(--surface-border)]">
|
|
<button
|
|
class="px-3 py-2 text-sm font-medium border-b-2 transition-colors"
|
|
:class="activeTab === 'editor' ? 'border-primary text-primary' : 'border-transparent text-[var(--text-color-secondary)]'"
|
|
@click="activeTab = 'editor'"
|
|
>Editor</button>
|
|
<button
|
|
class="px-3 py-2 text-sm font-medium border-b-2 transition-colors"
|
|
:class="activeTab === 'preview' ? 'border-primary text-primary' : 'border-transparent text-[var(--text-color-secondary)]'"
|
|
@click="activeTab = 'preview'"
|
|
>Preview</button>
|
|
</div>
|
|
|
|
<!-- Editor -->
|
|
<div v-show="activeTab === 'editor'" class="flex flex-col lg:flex-row gap-4">
|
|
<div class="flex-1 flex flex-col gap-3">
|
|
<div class="flex flex-col gap-1" @focusin="cursorField = 'cabecalho_html'">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Cabeçalho</label>
|
|
<JoditEmailEditor ref="editorCabecalho" v-model="form.cabecalho_html" :minHeight="120" layoutButtons :logoUrl="form.logo_url" />
|
|
</div>
|
|
<div class="flex flex-col gap-1" @focusin="cursorField = 'corpo_html'">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Corpo do documento</label>
|
|
<JoditEmailEditor ref="editorCorpo" v-model="form.corpo_html" :minHeight="350" />
|
|
</div>
|
|
<div class="flex flex-col gap-1" @focusin="cursorField = 'rodape_html'">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">Rodapé</label>
|
|
<JoditEmailEditor ref="editorRodape" v-model="form.rodape_html" :minHeight="120" layoutButtons :logoUrl="form.logo_url" />
|
|
</div>
|
|
<div class="flex flex-col gap-1">
|
|
<label class="text-xs font-medium text-[var(--text-color-secondary)]">URL do logo (opcional)</label>
|
|
<InputText v-model="form.logo_url" placeholder="https://..." class="w-full" />
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Painel de variaveis -->
|
|
<div class="w-full lg:w-[200px] flex-shrink-0">
|
|
<div class="sticky top-0">
|
|
<div class="text-xs font-semibold uppercase tracking-wider text-[var(--text-color-secondary)] mb-1">Variáveis</div>
|
|
<div class="text-[0.6rem] text-[var(--text-color-secondary)] mb-2">Clique para inserir</div>
|
|
<div class="flex flex-col gap-2.5 max-h-[500px] overflow-y-auto pr-1">
|
|
<div v-for="(vars, grupo) in variablesGrouped" :key="grupo">
|
|
<div class="text-[0.6rem] font-semibold uppercase tracking-wider text-[var(--text-color-secondary)] mb-0.5">{{ grupo }}</div>
|
|
<div class="flex flex-col">
|
|
<button
|
|
v-for="v in vars"
|
|
:key="v.key"
|
|
class="text-left text-xs px-1.5 py-0.5 rounded hover:bg-primary/10 hover:text-primary transition-colors truncate"
|
|
@click="insertVariable(v.key)"
|
|
>
|
|
{{ v.label }}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Preview -->
|
|
<div v-show="activeTab === 'preview'" class="border border-[var(--surface-border)] rounded-lg bg-white overflow-hidden">
|
|
<div class="p-6 text-black" style="font-family: 'Segoe UI', Arial, sans-serif; font-size: 12pt; line-height: 1.6;">
|
|
<div v-if="form.cabecalho_html" class="text-center mb-4 pb-3 border-b border-gray-300" v-html="previewReplace(form.cabecalho_html)" />
|
|
<div class="min-h-[300px]" v-html="previewReplace(form.corpo_html)" />
|
|
<div v-if="form.rodape_html" class="mt-8 pt-3 border-t border-gray-300 text-center text-[10pt] text-gray-500" v-html="previewReplace(form.rodape_html)" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<template #footer>
|
|
<div class="flex items-center justify-end gap-2">
|
|
<Button label="Cancelar" text @click="showDlg = false" :disabled="saving" />
|
|
<Button :label="isEdit ? 'Salvar' : 'Criar'" icon="pi pi-check" :loading="saving" @click="save" />
|
|
</div>
|
|
</template>
|
|
</Dialog>
|
|
|
|
<ConfirmDialog />
|
|
</div>
|
|
</template>
|