Files
TableExpirationWatcher/src/index.ts
T

130 lines
5.7 KiB
TypeScript

import { createApp } from "./api/app.js";
import { config } from "./core/config.js";
import { SqliteTableRepository, SqliteAlertRepository, SqliteCheckResultRepository, SqliteSettingsRepository } from "./infrastructure/sqlite/repositories.js";
import { DynamicConfigService } from "./infrastructure/config/dynamic-config-service.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 dynamicConfig = new DynamicConfigService(settingsRepo);
const app = createApp({ tableRepo, alertRepo, checkResultRepo, settingsRepo, dynamicConfig });
// Scheduler de verificação periódica
let checkInterval: ReturnType<typeof setInterval> | null = null;
function startScheduler() {
if (checkInterval) return;
const pollInterval = dynamicConfig.getNumber("POLL_INTERVAL_MS", config.POLL_INTERVAL_MS);
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, dynamicConfig);
await tableService.syncTablesFromCMS();
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 botToken = dynamicConfig.get("TELEGRAM_BOT_TOKEN", config.TELEGRAM_BOT_TOKEN);
const chatId = dynamicConfig.get("TELEGRAM_CHAT_ID", config.TELEGRAM_CHAT_ID);
const isTelegramDisabled = !chatId || ["disabled", "none", "off", "0"].includes(chatId.toLowerCase().trim());
const telegram = botToken && chatId && !isTelegramDisabled
? new TelegramNotifier({ botToken, chatId })
: null;
const mcpUrl = dynamicConfig.get("ASTRACALLS_MCP_URL", config.ASTRACALLS_MCP_URL);
const bearerToken = dynamicConfig.get("ASTRACALLS_BEARER_TOKEN", config.ASTRACALLS_BEARER_TOKEN);
const astracalls = mcpUrl
? new AstraCallsClient({ mcpUrl, bearerToken })
: null;
const rawTargets = dynamicConfig.get("WHATSAPP_ALERT_TARGETS", config.WHATSAPP_ALERT_TARGETS);
const whatsappTargets = rawTargets
? rawTargets.split(",").map((s: string) => s.trim()).filter(Boolean)
: [];
const notificationService = new NotificationService(
tableRepo, telegram, astracalls, new TableAlertFormatter(),
whatsappTargets, chatId
);
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);
}
}, pollInterval);
console.log(`[Scheduler] Iniciado com intervalo de ${pollInterval}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 port = dynamicConfig.getNumber("API_PORT", config.API_PORT);
const server = Bun.serve({
port,
fetch: app.fetch,
hostname: "0.0.0.0",
});
console.log(`🚀 Table Expiration Watcher rodando em http://localhost:${port}`);
console.log(` Health: http://localhost:${port}/health`);
console.log(` Config UI: http://localhost:${port}/configs`);
console.log(` API: http://localhost:${port}/api/status`);
startScheduler();
// Verificação inicial ao iniciar
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, dynamicConfig);
await tableService.syncTablesFromCMS();
await tableService.checkAllTables();
console.log("[Init] Verificação inicial concluída");
} catch (err) {
console.error("[Init] Erro:", err);
}
}, 2000);