diff --git a/CLAUDE.md b/CLAUDE.md index 3d645bf..5dde122 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -126,4 +126,7 @@ Env vars críticas no Coolify: `CMS_API_KEY`, `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CH - `produtos_json` pode ser null → trata como `sem_data`. - AstraCalls MCP usa JSON-RPC 2.0 (`tools/call` + `send_text`). - UI `/configs` é servida como HTML string (sem build step). Modifique `settings-page.ts` para mudanças visuais. -- SQLite path default `./data/tables.db` — volume persistente no Docker. \ No newline at end of file +- SQLite path default `./data/tables.db` — volume persistente no Docker. + +## Get tabelas .env. CMS_API_KEY +curl -s -H "Authorization: Bearer $CMS_API_KEY" "https://cms.rmscorretora.com.br/api/v3/plano?per_page=200" | bun -e 'const input = JSON.parse(await Bun.stdin.text()); const statuses = {}; for (const p of input.data) statuses[p.status] = (statuses[p.status] || 0) + 1; console.log("Statuses:", statuses); console.log("Total:", input.data.length);' \ No newline at end of file diff --git a/src/api/app.ts b/src/api/app.ts index 47717f8..40ea926 100644 --- a/src/api/app.ts +++ b/src/api/app.ts @@ -9,16 +9,19 @@ import { AstraCallsClient } from "../infrastructure/astracalls/astracalls-client import { TableAlertFormatter } from "../domain/services/table-alert-formatter.js"; import { renderSettingsHtml } from "./views/settings-page.js"; import { SqliteSettingsRepository } from "../infrastructure/sqlite/repositories.js"; +import { DynamicConfigService } from "../infrastructure/config/dynamic-config-service.js"; export interface AppDependencies { tableRepo: TableRepository; alertRepo: AlertRepository; checkResultRepo: CheckResultRepository; settingsRepo: SettingsRepository; + dynamicConfig?: DynamicConfigService; } export function createApp(deps: AppDependencies) { const app = new Hono(); + const dynamicConfig = deps.dynamicConfig || new DynamicConfigService(deps.settingsRepo); // CORS para UI app.use("*", cors({ @@ -29,39 +32,51 @@ export function createApp(deps: AppDependencies) { })); // Serviços - const tableService = new TableService(deps.tableRepo, deps.alertRepo, deps.checkResultRepo); + const tableService = new TableService(deps.tableRepo, deps.alertRepo, deps.checkResultRepo, dynamicConfig); - const telegram = config.TELEGRAM_BOT_TOKEN && config.TELEGRAM_CHAT_ID - ? new TelegramNotifier({ botToken: config.TELEGRAM_BOT_TOKEN, chatId: config.TELEGRAM_CHAT_ID }) - : null; + function getNotificationService() { + const botToken = dynamicConfig.get("TELEGRAM_BOT_TOKEN"); + const chatId = dynamicConfig.get("TELEGRAM_CHAT_ID"); + const telegram = botToken && chatId + ? new TelegramNotifier({ botToken, chatId }) + : null; - const astracalls = config.ASTRACALLS_MCP_URL - ? new AstraCallsClient({ - mcpUrl: config.ASTRACALLS_MCP_URL, - bearerToken: config.ASTRACALLS_BEARER_TOKEN, - }) - : null; + const mcpUrl = dynamicConfig.get("ASTRACALLS_MCP_URL"); + const bearerToken = dynamicConfig.get("ASTRACALLS_BEARER_TOKEN"); + const astracalls = mcpUrl + ? new AstraCallsClient({ mcpUrl, bearerToken }) + : null; - const whatsappTargets = config.WHATSAPP_ALERT_TARGETS - ? config.WHATSAPP_ALERT_TARGETS.split(",").map((s: string) => s.trim()).filter(Boolean) - : []; + const rawTargets = dynamicConfig.get("WHATSAPP_ALERT_TARGETS"); + const whatsappTargets = rawTargets + ? rawTargets.split(",").map((s: string) => s.trim()).filter(Boolean) + : []; - const notificationService = new NotificationService( - deps.tableRepo, - telegram, - astracalls, - new TableAlertFormatter(), - whatsappTargets, - config.TELEGRAM_CHAT_ID, - ); + return new NotificationService( + deps.tableRepo, + telegram, + astracalls, + new TableAlertFormatter(), + whatsappTargets, + chatId, + ); + } + + // Auth state (cookie simples) + const AUTH_COOKIE = "tw_auth"; + const AUTH_VALUE = "ok"; // Auth middleware const requireAuth = async (c: any, next: any) => { const apiKey = c.req.header("x-api-key"); const authHeader = c.req.header("authorization"); const bearer = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null; + const cookie = c.req.header("Cookie") || ""; + const hasAuthCookie = cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`); - if (apiKey === config.API_SECRET_KEY || bearer === config.API_SECRET_KEY) { + const secretKey = dynamicConfig.get("API_SECRET_KEY", config.API_SECRET_KEY); + + if (apiKey === secretKey || bearer === secretKey || hasAuthCookie) { return next(); } return c.json({ error: "Unauthorized", message: "API key inválida" }, 401); @@ -81,28 +96,18 @@ export function createApp(deps: AppDependencies) { return c.html(renderSettingsHtml()); }); - // Auth state (cookie simples) - const AUTH_COOKIE = "tw_auth"; - const AUTH_VALUE = "ok"; - // Login app.post("/api/v1/configs/auth", async (c) => { const raw = await c.req.text(); - console.log("[DEBUG] Raw body:", JSON.stringify(raw)); let body: any = {}; try { body = JSON.parse(raw); - } catch (e) { - console.log("[DEBUG] JSON parse error:", e); - } - console.log("[DEBUG] Parsed body:", JSON.stringify(body)); + } catch {} const key = body?.secretKey?.trim(); - console.log("[DEBUG] Key:", key); - console.log("[DEBUG] Config API_SECRET_KEY:", config.API_SECRET_KEY); - console.log("[DEBUG] Match:", key === config.API_SECRET_KEY); - if (key && key === config.API_SECRET_KEY) { + const currentSecretKey = dynamicConfig.get("API_SECRET_KEY", config.API_SECRET_KEY); + + if (key && (key === currentSecretKey || key === config.API_SECRET_KEY)) { const cookieValue = `${AUTH_COOKIE}=${AUTH_VALUE}; HttpOnly; Path=/; SameSite=Lax; Max-Age=86400`; - console.log("[DEBUG] Setting cookie:", cookieValue); c.header("Set-Cookie", cookieValue); return c.json({ authenticated: true }); } @@ -122,36 +127,24 @@ export function createApp(deps: AppDependencies) { return c.json({ ok: true }); }); - // API de configs para a UI (protegida por cookie) + // API de configs para a UI (protegida por cookie ou secret key) app.get("/api/v1/configs", async (c) => { const cookie = c.req.header("Cookie") || ""; - if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`)) { + const apiKey = c.req.header("x-api-key"); + const currentSecretKey = dynamicConfig.get("API_SECRET_KEY", config.API_SECRET_KEY); + if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`) && apiKey !== currentSecretKey) { return c.json({ authenticated: false }, 401); } - // Retorna configs do banco (SQLite) — prioridade UI > .env > default - const allSettings = deps.settingsRepo.getAll(); - const defs = SqliteSettingsRepository.getDefinitions(); - - const settings = defs.map(def => { - const stored = allSettings.find(s => s.key === def.key); - const value = stored ? stored.value : def.defaultValue; - return { - key: def.key, - value: def.isSecret && value ? "*****" : value, - category: def.category, - label: def.label, - type: def.type, - isSecret: def.isSecret, - description: def.description, - }; - }); + const settings = dynamicConfig.getEffectiveSettings(true); return c.json({ settings }); }); // PUT /api/v1/configs - Atualizar múltiplas configs app.put("/api/v1/configs", async (c) => { const cookie = c.req.header("Cookie") || ""; - if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`)) { + const apiKey = c.req.header("x-api-key"); + const currentSecretKey = dynamicConfig.get("API_SECRET_KEY", config.API_SECRET_KEY); + if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`) && apiKey !== currentSecretKey) { return c.json({ authenticated: false }, 401); } const body = await c.req.json(); @@ -162,22 +155,43 @@ export function createApp(deps: AppDependencies) { const results: Record = {}; for (const [key, value] of Object.entries(settings)) { try { - deps.settingsRepo.set(key, String(value)); + dynamicConfig.set(key, String(value)); results[key] = true; } catch (err) { results[key] = false; } } - return c.json({ results }); + return c.json({ ok: true, results }); }); // === ROTAS PROTEGIDAS === app.use("/api/*", requireAuth); - // Dashboard de status + // Dashboard de status & saúde app.get("/api/status", async (c) => { const summary = await tableService.getExpirySummary(); - return c.json(summary); + const cmsUrl = dynamicConfig.get("CMS_API_URL", config.CMS_API_URL); + let cmsReachable = false; + try { + const res = await fetch(`${cmsUrl}/v3/plano?per_page=1`, { + signal: AbortSignal.timeout(3000), + }); + cmsReachable = res.ok; + } catch { + cmsReachable = false; + } + + const notifierReady = Boolean( + dynamicConfig.get("TELEGRAM_BOT_TOKEN") || + dynamicConfig.get("ASTRACALLS_MCP_URL") + ); + + return c.json({ + ...summary, + cmsReachable, + schedulerRunning: true, + notifierReady, + }); }); // Forçar verificação completa @@ -213,7 +227,6 @@ export function createApp(deps: AppDependencies) { const summary = await tableService.getExpirySummary(); const alerts = summary.criticalTables.map(table => { const expiryDate = table.revision_date; - // calcula dias aproximados const months = ["janeiro", "fevereiro", "marco", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"]; let daysUntil = 0; @@ -232,6 +245,7 @@ export function createApp(deps: AppDependencies) { return { table, daysUntil, severity }; }); + const notificationService = getNotificationService(); const result = await notificationService.notifyExpiringTables(alerts); return c.json(result); }); diff --git a/src/api/views/settings-page.ts b/src/api/views/settings-page.ts index e4dca83..79290ac 100644 --- a/src/api/views/settings-page.ts +++ b/src/api/views/settings-page.ts @@ -337,13 +337,14 @@ export function renderSettingsHtml(): string { const row = document.createElement('div'); row.className = 'setting-row'; const isBool = item.type === 'boolean' || item.value === 'true' || item.value === 'false'; + const currentVal = dirtyValues[item.key] !== undefined ? dirtyValues[item.key] : item.value; let controlHtml = ''; if (isBool) { - const checked = item.value === 'true' || item.value === '1'; + const checked = currentVal === 'true' || currentVal === '1'; controlHtml = ''; } else { const isSecret = item.isSecret; - controlHtml = ''; + controlHtml = ''; } row.innerHTML = '
' + item.label + '
' + (item.description || item.key) + '
' + controlHtml + '
'; card.appendChild(row); @@ -353,18 +354,28 @@ export function renderSettingsHtml(): string { } function onSwitchChange(checkbox) { dirtyValues[checkbox.getAttribute('data-key')] = checkbox.checked ? 'true' : 'false'; } - function onInputChange(input) { dirtyValues[input.getAttribute('data-key')] = input.value.trim(); } + function onInputChange(input) { + const key = input.getAttribute('data-key'); + const val = input.value; + if (val === '••••••••' || val === '*****') return; + dirtyValues[key] = val; + } // 4. Salvar document.getElementById('save-all-btn').addEventListener('click', async () => { - const keys = Object.keys(dirtyValues); + const payload = {}; + for (const [k, v] of Object.entries(dirtyValues)) { + if (v === '••••••••' || v === '*****') continue; + payload[k] = v; + } + const keys = Object.keys(payload); if (keys.length === 0) { showToast('Nenhuma alteração pendente'); return; } try { const res = await fetch('/api/v1/configs', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ settings: dirtyValues }) + body: JSON.stringify({ settings: payload }) }); - if (res.ok) { showToast('Configurações salvas!'); dirtyValues = {}; loadSettings(); } + if (res.ok) { showToast('Configurações salvas!'); dirtyValues = {}; await loadSettings(); } else { showToast('Erro ao salvar'); } } catch (err) { showToast('Falha na conexão'); } }); diff --git a/src/application/services/table-service.ts b/src/application/services/table-service.ts index 0330cd0..211aedf 100644 --- a/src/application/services/table-service.ts +++ b/src/application/services/table-service.ts @@ -1,6 +1,7 @@ import { config } from "../../core/config.js"; import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../../domain/models/table.js"; import type { TableRepository, AlertRepository, CheckResultRepository } from "../../domain/repositories/table-repository.js"; +import type { DynamicConfigService } from "../../infrastructure/config/dynamic-config-service.js"; import { parseISO, format, differenceInDays, isValid } from "date-fns"; import { ptBR } from "date-fns/locale"; @@ -11,40 +12,68 @@ const MONTH_MAP: Record = { function parseRevisionDate(revisionDate: string | null): Date | null { if (!revisionDate) return null; - const match = revisionDate.match(/^([A-Za-zçãõ]+)\/(\d{4})$/i); + const cleaned = revisionDate.trim(); + if (cleaned === "" || cleaned === "*") return null; + const match = cleaned.match(/^([A-Za-zçãõ]+)\/(\d{4})$/i); if (!match) return null; const monthName = match[1].toLowerCase(); const year = parseInt(match[2], 10); const month = MONTH_MAP[monthName]; // 1-12 if (!month) return null; - // Considera o último dia do mês como data de expiração - // JS Date: month é 0-indexed, então month (1-12) vira month (0-11) - // new Date(year, month, 0) → último dia do mês anterior - // Para último dia do mês atual: new Date(year, month, 0) onde month já é 1-indexed + // Considera o último dia do mês como data de expiração (new Date(year, month, 0)) const date = new Date(year, month, 0); return date; } -function calculateTableStatus(table: TableInfo): TableStatus { +function calculateTableStatus( + table: TableInfo, + warningDays: number = Number(process.env.TABLE_EXPIRY_WARNING_DAYS || config.TABLE_EXPIRY_WARNING_DAYS || 30), + criticalDays: number = Number(process.env.TABLE_EXPIRY_CRITICAL_DAYS || config.TABLE_EXPIRY_CRITICAL_DAYS || 7) +): TableStatus { + // 1. Vesting status ou is_stale explícito de vencimento if (table.is_stale || table.vesting_status === "vencido") { return "vencida"; } - const expiryDate = parseRevisionDate(table.revision_date); - if (!expiryDate) return "sem_data"; + // 2. Avaliação de revision_date + const rawRev = (table.revision_date || "").trim(); + if (!rawRev || rawRev === "*") { + return "sem_data"; + } + + const expiryDate = parseRevisionDate(rawRev); + if (!expiryDate) { + return "sem_data"; + } const now = new Date(); const diffDays = differenceInDays(expiryDate, now); - if (diffDays < 0) return "vencida"; - if (diffDays <= config.TABLE_EXPIRY_CRITICAL_DAYS) return "prestes_a_vencer"; - if (diffDays <= config.TABLE_EXPIRY_WARNING_DAYS) return "prestes_a_vencer"; + if (diffDays < 0) { + return "vencida"; + } + + // 3. Vesting status "a_vencer" ou dentro da janela configurada + if (table.vesting_status === "a_vencer") { + return "prestes_a_vencer"; + } + + if (diffDays <= criticalDays) { + return "prestes_a_vencer"; + } + if (diffDays <= warningDays) { + return "prestes_a_vencer"; + } + return "vigente"; } -function calculateSeverity(daysUntilExpiry: number): "warning" | "critical" | "expired" { +function calculateSeverity( + daysUntilExpiry: number, + criticalDays: number = Number(process.env.TABLE_EXPIRY_CRITICAL_DAYS || config.TABLE_EXPIRY_CRITICAL_DAYS || 7) +): "warning" | "critical" | "expired" { if (daysUntilExpiry < 0) return "expired"; - if (daysUntilExpiry <= config.TABLE_EXPIRY_CRITICAL_DAYS) return "critical"; + if (daysUntilExpiry <= criticalDays) return "critical"; return "warning"; } @@ -52,19 +81,50 @@ export class TableService { constructor( private tableRepo: TableRepository, private alertRepo: AlertRepository, - private checkResultRepo: CheckResultRepository + private checkResultRepo: CheckResultRepository, + private dynamicConfig?: DynamicConfigService ) {} + private getWarningDays(): number { + return this.dynamicConfig + ? this.dynamicConfig.getNumber("TABLE_EXPIRY_WARNING_DAYS", 30) + : Number(process.env.TABLE_EXPIRY_WARNING_DAYS || config.TABLE_EXPIRY_WARNING_DAYS || 30); + } + + private getCriticalDays(): number { + return this.dynamicConfig + ? this.dynamicConfig.getNumber("TABLE_EXPIRY_CRITICAL_DAYS", 7) + : Number(process.env.TABLE_EXPIRY_CRITICAL_DAYS || config.TABLE_EXPIRY_CRITICAL_DAYS || 7); + } + + private getCmsApiUrl(): string { + return this.dynamicConfig + ? this.dynamicConfig.get("CMS_API_URL", config.CMS_API_URL) + : config.CMS_API_URL; + } + + private getCmsApiKey(): string { + return this.dynamicConfig + ? this.dynamicConfig.get("CMS_API_KEY", config.CMS_API_KEY) + : config.CMS_API_KEY; + } + + calculateStatus(table: TableInfo): TableStatus { + return calculateTableStatus(table, this.getWarningDays(), this.getCriticalDays()); + } + async checkAllTables(): Promise { const tables = await this.tableRepo.getAll(); const now = new Date().toISOString(); + const warningDays = this.getWarningDays(); + const criticalDays = this.getCriticalDays(); let vigente = 0, prestes_a_vencer = 0, vencidas = 0, sem_data = 0, errors = 0; const alertsGenerated: ExpiryAlert[] = []; for (const table of tables) { try { - const status = calculateTableStatus(table); + const status = calculateTableStatus(table, warningDays, criticalDays); await this.tableRepo.updateStatus(table.id, status); switch (status) { @@ -77,7 +137,7 @@ export class TableService { if (status === "prestes_a_vencer" || status === "vencida") { const expiryDate = parseRevisionDate(table.revision_date); const daysUntil = expiryDate ? differenceInDays(expiryDate, now) : 0; - const severity = calculateSeverity(daysUntil); + const severity = calculateSeverity(daysUntil, criticalDays); const alert: ExpiryAlert = { table_id: table.id, @@ -116,12 +176,14 @@ export class TableService { } async fetchTablesFromCMS(): Promise { - const url = `${config.CMS_API_URL}/v3/plano?per_page=200`; + const cmsApiUrl = this.getCmsApiUrl(); + const cmsApiKey = this.getCmsApiKey(); + const url = `${cmsApiUrl}/v3/plano?per_page=200`; const headers: Record = { "Content-Type": "application/json", }; - if (config.CMS_API_KEY) { - headers["Authorization"] = `Bearer ${config.CMS_API_KEY}`; + if (cmsApiKey) { + headers["Authorization"] = `Bearer ${cmsApiKey}`; } const response = await fetch(url, { headers }); @@ -131,10 +193,12 @@ export class TableService { const data = await response.json(); const now = new Date().toISOString(); + const cmsBaseUrl = cmsApiUrl.replace("/api", ""); - const cmsBaseUrl = config.CMS_API_URL.replace("/api", ""); + // Filtra estritamente apenas status "publish" (ignora desativadas, rascunhos, lixeira) + const activeItems = (data.data || []).filter((item: any) => item.status === "publish"); - return (data.data || []).map((item: any) => { + return activeItems.map((item: any) => { const produtosJson = item.produtos_json; const extractedAt = produtosJson?._meta?.extracted_at || null; @@ -153,6 +217,7 @@ export class TableService { edit_url: `${cmsBaseUrl}/admin/tabelas/${item.id}/editar`, is_stale: Boolean(item.is_stale), vesting_status: item.vesting_status || null, + modified_gmt: item.modified_gmt || null, }; return table; }); @@ -160,10 +225,17 @@ export class TableService { async syncTablesFromCMS(): Promise { const tables = await this.fetchTablesFromCMS(); + const activeIds = tables.map(t => t.id); + + // Remove do SQLite quaisquer tabelas que não estejam mais publicadas/ativas no CMS + this.tableRepo.deleteNotIn(activeIds); + let saved = 0; + const warningDays = this.getWarningDays(); + const criticalDays = this.getCriticalDays(); for (const table of tables) { - const status = calculateTableStatus(table); + const status = calculateTableStatus(table, warningDays, criticalDays); const tableWithStatus = { ...table, status }; await this.tableRepo.save(tableWithStatus); saved++; diff --git a/src/domain/models/setting.ts b/src/domain/models/setting.ts index 4208fe9..e56ec78 100644 --- a/src/domain/models/setting.ts +++ b/src/domain/models/setting.ts @@ -13,3 +13,26 @@ export interface SettingValue { value: string; updated_at: string; } + +export const DEFAULT_SETTING_DEFINITIONS: SettingDefinition[] = [ + // Sincronização & CMS + { key: "POLL_INTERVAL_MS", label: "Intervalo de Verificação (ms)", description: "Frequência de sincronização e verificação automática", category: "sync", type: "number", defaultValue: "3600000" }, + { key: "TABLE_EXPIRY_WARNING_DAYS", label: "Aviso Antecipado (dias)", description: "Dias antes do vencimento para emitir aviso (warning)", category: "sync", type: "number", defaultValue: "30" }, + { key: "TABLE_EXPIRY_CRITICAL_DAYS", label: "Aviso Crítico (dias)", description: "Dias antes do vencimento para emitir aviso crítico", category: "sync", type: "number", defaultValue: "7" }, + { key: "CMS_API_URL", label: "URL da API CMS", description: "Endpoint base da API CMS RMS (ex: https://cms.rmscorretora.com.br/api)", category: "sync", type: "string", defaultValue: "https://cms.rmscorretora.com.br/api" }, + { key: "CMS_API_KEY", label: "Chave de API CMS", description: "Bearer token ou Secret Key para autenticação na API CMS", category: "sync", type: "string", isSecret: true, defaultValue: "" }, + + // Notificações + { key: "TELEGRAM_BOT_TOKEN", label: "Token Bot Telegram", description: "Token do bot Telegram para envio de alertas", category: "notifications", type: "string", isSecret: true, defaultValue: "" }, + { key: "TELEGRAM_CHAT_ID", label: "Chat ID Telegram", description: "Chat ID ou ID de grupo/canal onde enviar alertas", category: "notifications", type: "string", defaultValue: "" }, + { key: "ASTRACALLS_MCP_URL", label: "URL do AstraCalls MCP", description: "Endpoint do servidor MCP do AstraCalls para WhatsApp", category: "notifications", type: "string", defaultValue: "https://astra.rdsnexus.vix.br/mcp" }, + { key: "ASTRACALLS_BEARER_TOKEN", label: "Token Bearer AstraCalls", description: "Bearer token para autenticação no MCP AstraCalls", category: "notifications", type: "string", isSecret: true, defaultValue: "" }, + { key: "ASTRACALLS_SESSION_PHONE", label: "Telefone da Sessão AstraCalls", description: "Número de telefone conectado da sessão WhatsApp", category: "notifications", type: "string", defaultValue: "5527997509094" }, + { key: "WHATSAPP_ALERT_TARGETS", label: "Destinos WhatsApp", description: "Telefones/grupos separados por vírgula para alertas (ex: 5527...,12036...@g.us)", category: "notifications", type: "string", defaultValue: "5527988037765" }, + + // Sistema + { key: "API_PORT", label: "Porta da API", description: "Porta onde o servidor HTTP escuta", category: "general", type: "number", defaultValue: "3002" }, + { key: "API_SECRET_KEY", label: "Chave Secreta da API", description: "Senha mestra para login no painel /configs e autenticação da API", category: "general", type: "string", isSecret: true, defaultValue: "dev-secret-change-me" }, + { key: "SQLITE_PATH", label: "Caminho do SQLite", description: "Arquivo de banco de dados local", category: "general", type: "string", defaultValue: "./data/tables.db" }, + { key: "LOG_LEVEL", label: "Nível de Log", description: "Nível de verbosidade do log (info, debug, warn, error)", category: "general", type: "string", defaultValue: "info" }, +]; diff --git a/src/domain/models/table.ts b/src/domain/models/table.ts index 9de7f4b..ac146fb 100644 --- a/src/domain/models/table.ts +++ b/src/domain/models/table.ts @@ -15,6 +15,7 @@ export interface TableInfo { edit_url?: string | null; // URL de edição no CMS is_stale?: boolean; vesting_status?: string | null; + modified_gmt?: string | null; } export interface TableProdutosJson { @@ -70,6 +71,7 @@ export const TableInfoSchema = z.object({ last_checked: z.string().datetime(), is_stale: z.boolean().optional(), vesting_status: z.string().nullable().optional(), + modified_gmt: z.string().nullable().optional(), }); export interface ExpiryAlert { diff --git a/src/domain/repositories/table-repository.ts b/src/domain/repositories/table-repository.ts index 3cbde87..d2a5b5c 100644 --- a/src/domain/repositories/table-repository.ts +++ b/src/domain/repositories/table-repository.ts @@ -10,6 +10,8 @@ export interface TableRepository { updateStatus(id: string, status: TableStatus): void; markAlertSent(tableId: string, channel: "telegram" | "whatsapp"): void; getAlertHistory(tableId: string): ExpiryAlert[]; + deleteNotIn(activeIds: string[]): number; + deleteById(id: string): void; } export interface AlertRepository { diff --git a/src/index.ts b/src/index.ts index dc937e2..aed4c01 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,23 @@ 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 }); +const app = createApp({ tableRepo, alertRepo, checkResultRepo, settingsRepo, dynamicConfig }); // Scheduler de verificação periódica let checkInterval: ReturnType | 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 { @@ -23,27 +27,33 @@ function startScheduler() { 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 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 telegram = config.TELEGRAM_BOT_TOKEN && config.TELEGRAM_CHAT_ID - ? new TelegramNotifier({ botToken: config.TELEGRAM_BOT_TOKEN, chatId: config.TELEGRAM_CHAT_ID }) + const botToken = dynamicConfig.get("TELEGRAM_BOT_TOKEN", config.TELEGRAM_BOT_TOKEN); + const chatId = dynamicConfig.get("TELEGRAM_CHAT_ID", config.TELEGRAM_CHAT_ID); + const telegram = botToken && chatId + ? new TelegramNotifier({ botToken, chatId }) : null; - const astracalls = config.ASTRACALLS_MCP_URL - ? new AstraCallsClient({ mcpUrl: config.ASTRACALLS_MCP_URL, bearerToken: config.ASTRACALLS_BEARER_TOKEN }) + 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 whatsappTargets = config.WHATSAPP_ALERT_TARGETS - ? config.WHATSAPP_ALERT_TARGETS.split(",").map((s: string) => s.trim()).filter(Boolean) + 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, config.TELEGRAM_CHAT_ID + whatsappTargets, chatId ); const criticalTables = await tableService.getTablesByStatus("prestes_a_vencer"); @@ -59,9 +69,9 @@ function startScheduler() { } catch (err) { console.error("[Scheduler] Erro:", err); } - }, config.POLL_INTERVAL_MS); + }, pollInterval); - console.log(`[Scheduler] Iniciado com intervalo de ${config.POLL_INTERVAL_MS}ms`); + console.log(`[Scheduler] Iniciado com intervalo de ${pollInterval}ms`); } function stopScheduler() { @@ -90,25 +100,26 @@ 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: config.API_PORT, + 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`); +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 (opcional) +// 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); + const tableService = new TableService(tableRepo, alertRepo, checkResultRepo, dynamicConfig); await tableService.syncTablesFromCMS(); await tableService.checkAllTables(); console.log("[Init] Verificação inicial concluída"); diff --git a/src/infrastructure/config/dynamic-config-service.ts b/src/infrastructure/config/dynamic-config-service.ts new file mode 100644 index 0000000..a1a9603 --- /dev/null +++ b/src/infrastructure/config/dynamic-config-service.ts @@ -0,0 +1,71 @@ +import type { SettingsRepository } from "../../domain/repositories/settings-repository.js"; +import { DEFAULT_SETTING_DEFINITIONS, type SettingDefinition } from "../../domain/models/setting.js"; + +export class DynamicConfigService { + constructor(private settingsRepo: SettingsRepository) {} + + get(key: string, fallback?: string): string { + // 1. SQLite (se definido e não vazio) + const stored = this.settingsRepo.get(key); + if (stored && stored.value !== undefined && stored.value.trim() !== "") { + return stored.value.trim(); + } + + // 2. process.env + const envVal = process.env[key]; + if (envVal !== undefined && envVal.trim() !== "") { + return envVal.trim(); + } + + // 3. Fallback explícito + if (fallback !== undefined) { + return fallback; + } + + // 4. Default definition + const def = DEFAULT_SETTING_DEFINITIONS.find((d) => d.key === key); + return def ? def.defaultValue : ""; + } + + getNumber(key: string, fallback?: number): number { + const raw = this.get(key); + const parsed = Number(raw); + if (Number.isFinite(parsed)) return parsed; + return fallback ?? 0; + } + + getBoolean(key: string, fallback?: boolean): boolean { + const raw = this.get(key).toLowerCase().trim(); + if (raw === "true" || raw === "1" || raw === "yes" || raw === "sim") return true; + if (raw === "false" || raw === "0" || raw === "no" || raw === "nao" || raw === "não") return false; + return fallback ?? false; + } + + set(key: string, value: string): void { + const trimmed = (value ?? "").trim(); + const def = DEFAULT_SETTING_DEFINITIONS.find((d) => d.key === key); + if (def?.isSecret) { + // Ignora máscaras comuns de senha para evitar sobrescrever a chave real + if (trimmed === "••••••••" || trimmed === "*****" || trimmed === "") { + return; + } + } + this.settingsRepo.set(key, trimmed); + } + + getEffectiveSettings(maskSecrets = true) { + return DEFAULT_SETTING_DEFINITIONS.map((def) => { + const effectiveValue = this.get(def.key); + const isSecret = def.isSecret === true; + return { + key: def.key, + value: isSecret && maskSecrets && effectiveValue.length > 0 ? "••••••••" : effectiveValue, + category: def.category, + label: def.label, + type: def.type, + isSecret, + description: def.description, + }; + }); + } +} diff --git a/src/infrastructure/sqlite/repositories.ts b/src/infrastructure/sqlite/repositories.ts index 2191855..c31ee59 100644 --- a/src/infrastructure/sqlite/repositories.ts +++ b/src/infrastructure/sqlite/repositories.ts @@ -1,6 +1,6 @@ import type { TableRepository, AlertRepository, CheckResultRepository, SettingsRepository } from "../../domain/repositories/table-repository.js"; import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../../domain/models/table.js"; -import type { SettingValue, SettingDefinition } from "../../domain/models/setting.js"; +import { DEFAULT_SETTING_DEFINITIONS, type SettingValue, type SettingDefinition } from "../../domain/models/setting.js"; import { Database } from "bun:sqlite"; import path from "path"; @@ -35,6 +35,7 @@ export class SqliteTableRepository implements TableRepository { last_checked TEXT NOT NULL, is_stale INTEGER NOT NULL DEFAULT 0, vesting_status TEXT, + modified_gmt TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); @@ -50,6 +51,9 @@ export class SqliteTableRepository implements TableRepository { try { this.db.exec("ALTER TABLE tables ADD COLUMN vesting_status TEXT;"); } catch {} + try { + this.db.exec("ALTER TABLE tables ADD COLUMN modified_gmt TEXT;"); + } catch {} this.db.exec(` CREATE TABLE IF NOT EXISTS alerts ( @@ -90,8 +94,8 @@ export class SqliteTableRepository implements TableRepository { const stmt = this.db.prepare(` INSERT OR REPLACE INTO tables ( id, title, operadora, administradora, revision_date, download_pdf, - vigencia, produtos_json, status, extracted_at, last_checked, is_stale, vesting_status, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now')) + vigencia, produtos_json, status, extracted_at, last_checked, is_stale, vesting_status, modified_gmt, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now')) `); stmt.run( table.id, @@ -106,7 +110,8 @@ export class SqliteTableRepository implements TableRepository { table.extracted_at, table.last_checked, table.is_stale ? 1 : 0, - table.vesting_status || null + table.vesting_status || null, + table.modified_gmt || null ); } @@ -170,9 +175,27 @@ export class SqliteTableRepository implements TableRepository { last_checked: row.last_checked, is_stale: Boolean(row.is_stale), vesting_status: row.vesting_status || null, + modified_gmt: row.modified_gmt || null, }; } + deleteNotIn(activeIds: string[]): number { + if (activeIds.length === 0) { + this.db.exec("DELETE FROM alerts"); + const res = this.db.prepare("DELETE FROM tables").run(); + return res.changes; + } + const placeholders = activeIds.map(() => "?").join(","); + this.db.prepare(`DELETE FROM alerts WHERE table_id NOT IN (${placeholders})`).run(...activeIds); + const res = this.db.prepare(`DELETE FROM tables WHERE id NOT IN (${placeholders})`).run(...activeIds); + return res.changes; + } + + deleteById(id: string): void { + this.db.prepare("DELETE FROM alerts WHERE table_id = ?").run(id); + this.db.prepare("DELETE FROM tables WHERE id = ?").run(id); + } + private mapAlertRow(row: any): ExpiryAlert { return { table_id: row.table_id, @@ -249,27 +272,15 @@ export class SqliteAlertRepository implements AlertRepository { } } -const DEFAULT_SETTING_DEFINITIONS: SettingDefinition[] = [ - // Sync & CMS - { key: "POLL_INTERVAL_MS", label: "Intervalo de Verificação (ms)", description: "Frequência de sincronização e verificação automática", category: "sync", type: "number", defaultValue: "3600000" }, - { key: "TABLE_EXPIRY_WARNING_DAYS", label: "Aviso Antecipado (dias)", description: "Dias antes do vencimento para emitir aviso (warning)", category: "sync", type: "number", defaultValue: "30" }, - { key: "TABLE_EXPIRY_CRITICAL_DAYS", label: "Aviso Crítico (dias)", description: "Dias antes do vencimento para emitir aviso crítico", category: "sync", type: "number", defaultValue: "7" }, - { key: "CMS_API_URL", label: "URL da API CMS", description: "Endpoint base da API CMS RMS", category: "sync", type: "string", defaultValue: "https://cms.rmscorretora.com.br/api" }, - - // Notificações - { key: "TELEGRAM_BOT_TOKEN", label: "Token Bot Telegram", description: "Token do bot Telegram para alertas", category: "notifications", type: "string", isSecret: true, defaultValue: "" }, - { key: "TELEGRAM_CHAT_ID", label: "Chat ID Telegram", description: "Chat/grupo onde enviar alertas", category: "notifications", type: "string", defaultValue: "" }, - { key: "WHATSAPP_ALERT_TARGETS", label: "Destinos WhatsApp", description: "Telefones/grupos separados por vírgula para alertas WhatsApp", category: "notifications", type: "string", defaultValue: "5527988037765" }, - - // Sistema - { key: "API_PORT", label: "Porta da API", description: "Porta onde o servidor HTTP escuta", category: "general", type: "number", defaultValue: "3002" }, - { key: "SQLITE_PATH", label: "Caminho do SQLite", description: "Arquivo de banco de dados local", category: "general", type: "string", defaultValue: "./data/tables.db" }, -]; - export class SqliteSettingsRepository implements SettingsRepository { private db: Database; constructor(dbPath: string = "./data/tables.db") { + const dir = path.dirname(dbPath); + const fs = require("fs"); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } this.db = new Database(dbPath); this.initSchema(); } @@ -283,11 +294,13 @@ export class SqliteSettingsRepository implements SettingsRepository { ); `); - // Insere defaults se não existirem + // Não insere defaults vazios para não bloquear fallback ao process.env for (const def of DEFAULT_SETTING_DEFINITIONS) { - const exists = this.db.prepare("SELECT 1 FROM settings WHERE key = ?").get(def.key); - if (!exists) { - this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?)").run(def.key, def.defaultValue); + if (def.defaultValue && def.defaultValue.trim() !== "") { + const exists = this.db.prepare("SELECT 1 FROM settings WHERE key = ?").get(def.key); + if (!exists) { + this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?)").run(def.key, def.defaultValue); + } } } } diff --git a/tests/integration/sqlite-repos.test.ts b/tests/integration/sqlite-repos.test.ts index ce0392b..303fa2a 100644 --- a/tests/integration/sqlite-repos.test.ts +++ b/tests/integration/sqlite-repos.test.ts @@ -158,4 +158,21 @@ describe("SQLite Repositories", () => { // Mais recente primeiro expect(new Date(history[0].checked_at).getTime()).toBeGreaterThanOrEqual(new Date(history[1].checked_at).getTime()); }); + + test("TableRepository: deleteNotIn remove tabelas desativadas/removidas", () => { + const t1: TableInfo = { id: "active-1", title: "Ativo 1", operadora: "Op", administradora: null, revision_date: "Out/2027", download_pdf: null, vigencia: null, produtos_json: null, status: "vigente", extracted_at: null, last_checked: "2026-01-01" }; + const t2: TableInfo = { id: "deactivated-2", title: "Desativado 2", operadora: "Op", administradora: null, revision_date: "Out/2026", download_pdf: null, vigencia: null, produtos_json: null, status: "vencida", extracted_at: null, last_checked: "2026-01-01" }; + tableRepo.save(t1); + tableRepo.save(t2); + + expect(tableRepo.getAll().length).toBe(2); + + // Sync do CMS traz apenas active-1 + const deletedCount = tableRepo.deleteNotIn(["active-1"]); + expect(deletedCount).toBe(1); + + const remaining = tableRepo.getAll(); + expect(remaining.length).toBe(1); + expect(remaining[0].id).toBe("active-1"); + }); }); \ No newline at end of file diff --git a/tests/unit/astracalls-client.test.ts b/tests/unit/astracalls-client.test.ts index 7f85ead..e0bd2fd 100644 --- a/tests/unit/astracalls-client.test.ts +++ b/tests/unit/astracalls-client.test.ts @@ -15,7 +15,7 @@ describe("AstraCallsClient", () => { const c = new AstraCallsClient({ mcpUrl: "https://astra.test/mcp", bearerToken: "my-secret-token", - }, mockFetch); + }, mockFetch as any); await c.sendText("5527999998888", "teste"); expect(capturedHeaders?.Authorization).toBe("Bearer my-secret-token"); @@ -30,7 +30,7 @@ describe("AstraCallsClient", () => { }), { status: 200, headers: { "content-type": "application/json" } }); }; - const c = new AstraCallsClient({ mcpUrl: "https://astra.test/mcp" }, mockFetch); + const c = new AstraCallsClient({ mcpUrl: "https://astra.test/mcp" }, mockFetch as any); await c.sendText("5527999998888", "teste"); }); }); diff --git a/tests/unit/dynamic-config.test.ts b/tests/unit/dynamic-config.test.ts new file mode 100644 index 0000000..bc4c86e --- /dev/null +++ b/tests/unit/dynamic-config.test.ts @@ -0,0 +1,70 @@ +import { test, expect, describe, beforeEach } from "bun:test"; +import { DynamicConfigService } from "../../src/infrastructure/config/dynamic-config-service.js"; +import type { SettingsRepository } from "../../src/domain/repositories/settings-repository.js"; +import type { SettingValue } from "../../src/domain/models/setting.js"; + +class InMemorySettingsRepo implements SettingsRepository { + private map = new Map(); + + get(key: string): SettingValue | null { + const val = this.map.get(key); + return val !== undefined ? { key, value: val, updated_at: "now" } : null; + } + getAll(): SettingValue[] { + return Array.from(this.map.entries()).map(([key, value]) => ({ key, value, updated_at: "now" })); + } + set(key: string, value: string): void { + this.map.set(key, value); + } +} + +describe("DynamicConfigService", () => { + let repo: InMemorySettingsRepo; + let dynamicConfig: DynamicConfigService; + + beforeEach(() => { + repo = new InMemorySettingsRepo(); + dynamicConfig = new DynamicConfigService(repo); + delete process.env.TEST_DYNAMIC_KEY; + }); + + test("Prioridade: SQLite > process.env > default", () => { + process.env.CMS_API_URL = "https://env.example.com"; + expect(dynamicConfig.get("CMS_API_URL")).toBe("https://env.example.com"); + + repo.set("CMS_API_URL", "https://sqlite.example.com"); + expect(dynamicConfig.get("CMS_API_URL")).toBe("https://sqlite.example.com"); + }); + + test("Não sobrescreve segredo se valor for máscara", () => { + repo.set("CMS_API_KEY", "real-super-secret"); + dynamicConfig.set("CMS_API_KEY", "••••••••"); + expect(dynamicConfig.get("CMS_API_KEY")).toBe("real-super-secret"); + + dynamicConfig.set("CMS_API_KEY", "*****"); + expect(dynamicConfig.get("CMS_API_KEY")).toBe("real-super-secret"); + + dynamicConfig.set("CMS_API_KEY", "new-real-secret"); + expect(dynamicConfig.get("CMS_API_KEY")).toBe("new-real-secret"); + }); + + test("getNumber e getBoolean convertem tipos corretamente", () => { + repo.set("TABLE_EXPIRY_WARNING_DAYS", "45"); + expect(dynamicConfig.getNumber("TABLE_EXPIRY_WARNING_DAYS", 30)).toBe(45); + + repo.set("CUSTOM_BOOL", "true"); + expect(dynamicConfig.getBoolean("CUSTOM_BOOL", false)).toBe(true); + + repo.set("CUSTOM_BOOL", "false"); + expect(dynamicConfig.getBoolean("CUSTOM_BOOL", true)).toBe(false); + }); + + test("getEffectiveSettings mascara segredos", () => { + repo.set("CMS_API_KEY", "my-secret-key"); + const settings = dynamicConfig.getEffectiveSettings(true); + const cmsKeySetting = settings.find(s => s.key === "CMS_API_KEY"); + expect(cmsKeySetting).toBeDefined(); + expect(cmsKeySetting?.value).toBe("••••••••"); + expect(cmsKeySetting?.isSecret).toBe(true); + }); +}); diff --git a/tests/unit/table-service-evaluation.test.ts b/tests/unit/table-service-evaluation.test.ts new file mode 100644 index 0000000..8b85c85 --- /dev/null +++ b/tests/unit/table-service-evaluation.test.ts @@ -0,0 +1,100 @@ +import { test, expect, describe, beforeEach } from "bun:test"; +import { TableService, calculateTableStatus } from "../../src/application/services/table-service.js"; +import type { TableInfo } from "../../src/domain/models/table.js"; + +describe("Table Service Status Evaluation & Publish Filtering", () => { + test("Tabela em dia (como exemplo do usuario) e avaliada como vigente", () => { + const table: TableInfo = { + id: "55c02939-aadd-4403-8766-f5da1a506454", + title: "SBS Up Health – Empresarial – SINTRAMASSAS", + operadora: "São Bernardo Samp", + administradora: "Up Health", + revision_date: "Setembro/2027", + download_pdf: "https://media.rmscorretora.com.br/uploads/pdf.pdf", + vigencia: null, + produtos_json: { + _meta: { + extracted_at: "2026-11-26T20:04:10.700782+00:00", + }, + produtos: [{ nome: "Plano 1", tipo: "Ambulatorial", faixas: [] }], + }, + status: "sem_data", + extracted_at: "2026-11-26T20:04:10.700782+00:00", + last_checked: "2026-11-27T00:00:00.000Z", + vesting_status: "em_dia", + is_stale: false, + modified_gmt: "2026-11-26 20:06:09", + }; + + const status = calculateTableStatus(table, 30, 7); + expect(status).toBe("vigente"); + }); + + test("Tabela com vesting_status vencido ou is_stale e avaliada como vencida", () => { + const table: TableInfo = { + id: "stale-1", + title: "Tabela Vencida por Stale", + operadora: "Op", + administradora: null, + revision_date: "Setembro/2027", + download_pdf: null, + vigencia: null, + produtos_json: null, + status: "sem_data", + extracted_at: null, + last_checked: "2026-11-27T00:00:00.000Z", + vesting_status: "vencido", + is_stale: true, + modified_gmt: "2026-11-26 20:06:09", + }; + + expect(calculateTableStatus(table, 30, 7)).toBe("vencida"); + }); + + test("Tabela sem revision_date ou com * e avaliada como sem_data (falta)", () => { + const tableStar: TableInfo = { + id: "star-1", + title: "Tabela com Asterisco", + operadora: "Op", + administradora: null, + revision_date: "*", + download_pdf: null, + vigencia: null, + produtos_json: null, + status: "sem_data", + extracted_at: null, + last_checked: "2026-11-27T00:00:00.000Z", + vesting_status: "em_dia", + is_stale: false, + modified_gmt: null, + }; + expect(calculateTableStatus(tableStar, 30, 7)).toBe("sem_data"); + + const tableEmpty: TableInfo = { + ...tableStar, + id: "empty-1", + revision_date: null, + }; + expect(calculateTableStatus(tableEmpty, 30, 7)).toBe("sem_data"); + }); + + test("Tabela com vesting_status a_vencer e classificada como prestes_a_vencer", () => { + const table: TableInfo = { + id: "avencer-1", + title: "Tabela A Vencer", + operadora: "Op", + administradora: null, + revision_date: "Dezembro/2027", + download_pdf: null, + vigencia: null, + produtos_json: null, + status: "sem_data", + extracted_at: null, + last_checked: "2026-11-27T00:00:00.000Z", + vesting_status: "a_vencer", + is_stale: false, + modified_gmt: null, + }; + expect(calculateTableStatus(table, 30, 7)).toBe("prestes_a_vencer"); + }); +}); diff --git a/tests/unit/table-service.test.ts b/tests/unit/table-service.test.ts index cac67e6..a2b39a9 100644 --- a/tests/unit/table-service.test.ts +++ b/tests/unit/table-service.test.ts @@ -1,6 +1,7 @@ import { test, expect, describe, beforeEach, afterEach } from "bun:test"; import { calculateTableStatus, parseRevisionDate, calculateSeverity } from "../../src/application/services/table-service.ts"; import { TableAlertFormatter } from "../../src/domain/services/table-alert-formatter.ts"; +import type { ExpiryAlert } from "../../src/domain/models/table.ts"; describe("Table Status Calculation", () => { const originalWarningDays = process.env.TABLE_EXPIRY_WARNING_DAYS; @@ -124,7 +125,7 @@ describe("TableAlertFormatter", () => { const formatter = new TableAlertFormatter(); test("formatExpiryAlert: expired", () => { - const alert = { + const alert: ExpiryAlert = { table_id: "test-1", table_title: "Plano Teste", operadora: "Operadora X", @@ -145,7 +146,7 @@ describe("TableAlertFormatter", () => { }); test("formatExpiryAlert: critical", () => { - const alert = { + const alert: ExpiryAlert = { table_id: "test-2", table_title: "Plano Crítico", operadora: "Operadora Z", @@ -163,7 +164,7 @@ describe("TableAlertFormatter", () => { }); test("formatExpiryAlert: warning", () => { - const alert = { + const alert: ExpiryAlert = { table_id: "test-3", table_title: "Plano Warning", operadora: "Operadora W", @@ -181,7 +182,7 @@ describe("TableAlertFormatter", () => { }); test("escapeHtml: sanitiza caracteres perigosos", () => { - const alert = { + const alert: ExpiryAlert = { table_id: "test-4", table_title: "Plano ", operadora: "Op & Co", diff --git a/tests/unit/telegram-notifier.test.ts b/tests/unit/telegram-notifier.test.ts index d30b23c..6dc0059 100644 --- a/tests/unit/telegram-notifier.test.ts +++ b/tests/unit/telegram-notifier.test.ts @@ -3,7 +3,7 @@ import { TelegramNotifier } from "../../src/infrastructure/telegram/telegram-not describe("TelegramNotifier", () => { let notifier: TelegramNotifier; - let fetchMock: typeof fetch; + let fetchMock: any; beforeEach(() => { fetchMock = async (url: string, options: any) => { @@ -47,7 +47,7 @@ describe("TelegramNotifier", () => { const n = new TelegramNotifier({ botToken: "123456:TEST", chatId: "-1001111111111", - fetchFn: mockFetch, + fetchFn: mockFetch as any, delayMs: 0, }); @@ -74,7 +74,7 @@ describe("TelegramNotifier", () => { const n = new TelegramNotifier({ botToken: "123456:TEST", chatId: "-1001234567890", - fetchFn: mockFetch, + fetchFn: mockFetch as any, delayMs: 0, maxRetries: 3, }); @@ -98,7 +98,7 @@ describe("TelegramNotifier", () => { const n = new TelegramNotifier({ botToken: "123456:TEST", chatId: "-1001234567890", - fetchFn: mockFetch, + fetchFn: mockFetch as any, delayMs: 0, maxRetries: 3, }); @@ -121,7 +121,7 @@ describe("TelegramNotifier", () => { const n = new TelegramNotifier({ botToken: "123456:TEST", chatId: "-1001234567890", - fetchFn: mockFetch, + fetchFn: mockFetch as any, delayMs: 0, });