import type { TableInfo } from "../../domain/models/table.js"; import type { TableRepository } from "../../domain/repositories/table-repository.js"; import type { TelegramNotifier } from "../../infrastructure/telegram/telegram-notifier.js"; import type { AstraCallsClient } from "../../infrastructure/astracalls/astracalls-client.js"; import { TableAlertFormatter } from "../../domain/services/table-alert-formatter.js"; export class NotificationService { constructor( private tableRepo: TableRepository, private telegram: TelegramNotifier | null, private astracalls: AstraCallsClient | null, private formatter: TableAlertFormatter, private whatsappTargets: string[] = [], private telegramChatId?: string, ) {} async notifyExpiringTables(alerts: { table: TableInfo; daysUntil: number; severity: "warning" | "critical" | "expired" }[]): Promise<{ telegramSent: number; whatsappSent: number; errors: string[]; }> { const errors: string[] = []; let telegramSent = 0; let whatsappSent = 0; // Agrupa alertas por severidade para montar mensagem única const critical = alerts.filter(a => a.severity === "expired" || a.severity === "critical"); const warnings = alerts.filter(a => a.severity === "warning"); // 1. Telegram - um resumo + alertas individuais críticos const isTelegramDisabled = !this.telegramChatId || ["disabled", "none", "off", "0"].includes(this.telegramChatId.toLowerCase().trim()); if (this.telegram && this.telegramChatId && !isTelegramDisabled) { if (critical.length > 0) { for (const alert of critical) { const msg = this.formatter.formatExpiryAlert({ table_id: alert.table.id, table_title: alert.table.title, operadora: alert.table.operadora, administradora: alert.table.administradora, revision_date: alert.table.revision_date || "", days_until_expiry: alert.daysUntil, severity: alert.severity, alert_sent_at: null, channels: [], }); const ok = await this.telegram.sendMessage(msg, this.telegramChatId); if (ok) { telegramSent++; console.log(`[Telegram] Alerta enviado: ${alert.table.title}`); } else { errors.push(`Falha Telegram: ${alert.table.title}`); } } } if (warnings.length > 0) { const summaryMsg = this.formatWarningSummary(warnings); const ok = await this.telegram.sendMessage(summaryMsg, this.telegramChatId); if (ok) { telegramSent++; console.log(`[Telegram] Resumo de avisos enviado`); } else { errors.push("Falha Telegram: resumo de avisos"); } } } // 2. WhatsApp via AstraCalls if (this.astracalls && this.whatsappTargets.length > 0) { for (const alert of critical) { const msg = this.formatWhatsAppCritical(alert); for (const target of this.whatsappTargets) { const ok = await this.astracalls.sendText(target, msg); if (ok.success) { whatsappSent++; console.log(`[WhatsApp] Alerta enviado para ${target}: ${alert.table.title}`); } else { errors.push(`Falha WhatsApp ${target}: ${alert.table.title} (${ok.error})`); console.error(`[WhatsApp] Falha ao enviar para ${target} (${alert.table.title}): ${ok.error}`); } } } } return { telegramSent, whatsappSent, errors }; } private formatWarningSummary(alerts: { table: TableInfo; daysUntil: number; severity: string }[]): string { const lines = [ "⚠️ Tabelas próximas do vencimento (RMS)", "", ]; for (const a of alerts) { const editUrl = `https://cms.rmscorretora.com.br/admin/tabelas/${a.table.id}/editar`; lines.push( `📋 ${this.escapeHtml(a.table.title)}`, ` Operadora: ${a.table.operadora} • Vencimento: ${a.table.revision_date || "?"} • ${a.daysUntil} dia(s)`, ` 🔗 ${editUrl}`, "" ); } lines.push("💡 Clique nos links acima para editar as tabelas no CMS RMS."); return lines.join("\n"); } private formatWhatsAppCritical(alert: { table: TableInfo; daysUntil: number; severity: string }): string { const daysText = alert.daysUntil < 0 ? `Venceu há ${Math.abs(alert.daysUntil)} dia(s)` : alert.daysUntil === 0 ? "Vence HOJE" : `Vence em ${alert.daysUntil} dia(s)`; const editUrl = `https://cms.rmscorretora.com.br/admin/tabelas/${alert.table.id}/editar`; return [ `🚨 *TABELA ${alert.severity.toUpperCase()}*`, `🏢 ${alert.table.operadora}`, `📋 ${this.escapeHtml(alert.table.title)}`, `🆔 ${alert.table.id}`, `📅 ${alert.table.revision_date || "Sem data"}`, `⏰ ${daysText}`, `🔗 ${editUrl}`, "", "Clique no link para editar no CMS RMS.", ].join("\n"); } private escapeHtml(str?: string | null): string { if (!str) return ""; return str.replace(/&/g, "&").replace(//g, ">"); } }