import { createApp } from "./api/app.js"; import { config } from "./core/config.js"; import { SqliteTableRepository, SqliteAlertRepository, SqliteCheckResultRepository, SqliteSettingsRepository } from "./infrastructure/sqlite/repositories.js"; const tableRepo = new SqliteTableRepository(config.SQLITE_PATH); const alertRepo = new SqliteAlertRepository(config.SQLITE_PATH); const checkResultRepo = new SqliteCheckResultRepository(config.SQLITE_PATH); const settingsRepo = new SqliteSettingsRepository(config.SQLITE_PATH); const app = createApp({ tableRepo, alertRepo, checkResultRepo, settingsRepo }); // Scheduler de verificação periódica let checkInterval: ReturnType | null = null; function startScheduler() { if (checkInterval) return; checkInterval = setInterval(async () => { console.log("[Scheduler] Verificação periódica iniciada..."); try { const { TableService } = await import("./application/services/table-service.js"); const { NotificationService } = await import("./application/services/notification-service.js"); const { TelegramNotifier } = await import("./infrastructure/telegram/telegram-notifier.js"); const { AstraCallsClient } = await import("./infrastructure/astracalls/astracalls-client.js"); const { TableAlertFormatter } = await import("./domain/services/table-alert-formatter.js"); const tableService = new TableService(tableRepo, alertRepo, checkResultRepo); const result = await tableService.checkAllTables(); console.log(`[Scheduler] Check completo: ${result.total_tables} tabelas, ${result.alerts_generated.length} alertas`); if (result.alerts_generated.length > 0) { const telegram = config.TELEGRAM_BOT_TOKEN && config.TELEGRAM_CHAT_ID ? new TelegramNotifier({ botToken: config.TELEGRAM_BOT_TOKEN, chatId: config.TELEGRAM_CHAT_ID }) : null; const astracalls = config.ASTRACALLS_MCP_URL ? new AstraCallsClient({ mcpUrl: config.ASTRACALLS_MCP_URL, bearerToken: config.ASTRACALLS_BEARER_TOKEN }) : null; const whatsappTargets = config.WHATSAPP_ALERT_TARGETS ? config.WHATSAPP_ALERT_TARGETS.split(",").map((s: string) => s.trim()).filter(Boolean) : []; const notificationService = new NotificationService( tableRepo, telegram, astracalls, new TableAlertFormatter(), whatsappTargets, config.TELEGRAM_CHAT_ID ); const criticalTables = await tableService.getTablesByStatus("prestes_a_vencer"); const expiredTables = await tableService.getTablesByStatus("vencida"); const alerts = [ ...criticalTables.map(t => ({ table: t, daysUntil: calculateDaysUntil(t.revision_date), severity: "critical" as const })), ...expiredTables.map(t => ({ table: t, daysUntil: calculateDaysUntil(t.revision_date), severity: "expired" as const })), ]; await notificationService.notifyExpiringTables(alerts); } } catch (err) { console.error("[Scheduler] Erro:", err); } }, config.POLL_INTERVAL_MS); console.log(`[Scheduler] Iniciado com intervalo de ${config.POLL_INTERVAL_MS}ms`); } function stopScheduler() { if (checkInterval) { clearInterval(checkInterval); checkInterval = null; console.log("[Scheduler] Parado"); } } function calculateDaysUntil(revisionDate: string | null): number { if (!revisionDate) return 0; const months = ["janeiro", "fevereiro", "marco", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"]; const match = revisionDate.match(/^([A-Za-zçãõ]+)\/(\d{4})$/i); if (!match) return 0; const monthIdx = months.findIndex(m => m.startsWith(match[1].toLowerCase().slice(0, 3))); const year = parseInt(match[2], 10); if (monthIdx < 0) return 0; const expiry = new Date(year, monthIdx + 1, 0); return Math.ceil((expiry.getTime() - Date.now()) / (1000 * 60 * 60 * 24)); } // Graceful shutdown process.on("SIGINT", () => { stopScheduler(); process.exit(0); }); process.on("SIGTERM", () => { stopScheduler(); process.exit(0); }); // Inicia servidor const server = Bun.serve({ port: config.API_PORT, fetch: app.fetch, hostname: "0.0.0.0", }); console.log(`🚀 Table Expiration Watcher rodando em http://localhost:${config.API_PORT}`); console.log(` Health: http://localhost:${config.API_PORT}/health`); console.log(` Config UI: http://localhost:${config.API_PORT}/configs`); console.log(` API: http://localhost:${config.API_PORT}/api/status`); startScheduler(); // Verificação inicial ao iniciar (opcional) setTimeout(async () => { console.log("[Init] Verificação inicial..."); try { const { TableService } = await import("./application/services/table-service.js"); const tableService = new TableService(tableRepo, alertRepo, checkResultRepo); await tableService.syncTablesFromCMS(); await tableService.checkAllTables(); console.log("[Init] Verificação inicial concluída"); } catch (err) { console.error("[Init] Erro:", err); } }, 2000);