fix: sincronização de parâmetros na função de envio para garantir dados corretos nas automações

This commit is contained in:
Sidney 2026-05-08 10:26:31 -03:00
parent 00655694ca
commit 214629adce
3 changed files with 16 additions and 5 deletions

View File

@ -55,4 +55,5 @@
26. **SQL-First Architecture Pattern**: New features or module refactors SHOULD prioritize 100% SQL persistence (using `notas_boletim` as a template). The legacy JSON `school_data` should be treated as secondary or deprecated for these modules, ensuring real-time consistency between Manager and Portal.
27. **Safe Rendering Principle (Portal)**: All property accesses on dynamic objects (like `data` or `student`) MUST use optional chaining (`?.`). Avoid using undeclared variables copied from other modules; always perform a `tsc` check in the portal before committing to prevent "White Screen of Death" crashes.
28. **Frequency Parity Rule**: The Portal MUST mirror the Manager's attendance matching logic exactly, including time windows (30m before) and end-of-day fallbacks (23:59), to ensure data consistency between Admin and Student views.
29. **Hybrid Identity Lookup**: Automated messaging services MUST implement a hybrid lookup for students: first check the legacy `school_data` JSON, then fallback to the PostgreSQL `alunos` table. This ensures support for both migrated and newly created students.
30. **Financial Data Integrity**: Automation routines MUST prioritize `school_data.payments` (JSON) as the trigger source while using `alunos_cobrancas` (SQL) for tracking notification counters (spam control), ensuring 100% parity with the management UI.

View File

@ -106,6 +106,12 @@
- **Estado Atual:** Pipeline 100% estabilizado no GitHub Actions usando `self-hosted` runner (Oracle ARM64 nativo).
- **Melhoria:** O build agora ocorre diretamente na arquitetura de destino, sem emulação QEMU, garantindo velocidade e estabilidade total.
### 📅 08/05/2026 - Estabilização Crítica de Automação e Sincronia Financeira
- **Fonte de Disparos:** A rotina de cobranças agora utiliza o `school_data.payments` (JSON) como fonte primária para garantir 100% de paridade com o painel financeiro, eliminando falhas de "tabela vazia".
- **Sincronização Financeira:** Implementado o espelhamento automático de `data.payments` (JSON) para a tabela `alunos_cobrancas` (SQL) com trava de unicidade no `asaas_payment_id`.
- **Busca Híbrida de Alunos:** O envio de WhatsApp agora busca o aluno primeiro no JSON e, caso não encontre, faz o fallback para a tabela SQL `alunos`.
- **Resiliência de Telefone:** Implementada lógica de "Melhor Esforço" para seleção de telefone (Responsável vs Aluno) e proteção contra erro de `NaN` na formatação de valores.
### 📢 Automação de Mensagens
- [x] **Estabilização de Lembretes (V2):** Resolvido bug de deslocamento de fuso horário (-1 dia) nas datas de vencimento. Implementadas ferramentas de debug (ignorar trava diária e reset de contadores) e **controle manual de delay para disparos em massa** para facilitar testes e garantir segurança contra banimento.

View File

@ -459,7 +459,7 @@ function formatCobrancaDate(dateStr) {
// Integração WhatsApp Evolution API
// (Mesma lógica, trocando supabase por database.js)
// ============================================================
async function sendEvolutionMessage(asaasPaymentId, eventType, paymentPayload = null) {
async function sendEvolutionMessage(asaasPaymentId, eventType, fallbackValorArg = null, fallbackVencimentoArg = null) {
try {
let cob = null;
for (let i = 0; i < 3; i++) {
@ -470,9 +470,9 @@ async function sendEvolutionMessage(asaasPaymentId, eventType, paymentPayload =
if (!cob) return console.log(`[Evolution] Cobrança não encontrada: ${asaasPaymentId}`);
let fallbackValor = cob.valor;
let fallbackVencimento = cob.vencimento;
let fallbackDescricao = paymentPayload?.description || 'serviços educacionais';
let fallbackValor = fallbackValorArg || cob.valor;
let fallbackVencimento = fallbackVencimentoArg || cob.vencimento;
let fallbackDescricao = 'serviços educacionais';
const appData = await getSchoolData();
if (!appData) return console.log('[WhatsApp] school_data não encontrado');
@ -1154,8 +1154,12 @@ async function executarRotinaCobrancas(tipo = 'ambos') {
const rules = appData?.messageTemplates?.automationRules || {};
const sendDaysBefore = parseInt(rules.sendDaysBefore) || 3;
const maxPreWarnings = parseInt(rules.maxPreWarnings) || 1;
const sendDaysAfter = parseInt(rules.sendDaysAfter) || 1;
const repeatEveryDays = parseInt(rules.repeatEveryDays) || 3;
let enviadasAtraso = 0;
let enviadasAviso = 0;
const allPayments = appData.payments || [];
const hoje = getLocalSafeDate(new Date());