commit 6e8e6407387e2a8d89e4b884f9f72a53cae372d8 Author: Andre RDS Date: Wed Nov 25 09:43:00 2026 -0300 feat: initial commit - Table Expiration Watcher - Monitor de tabelas de planos de saúde prestes a vencer/vencidas - Stack: Bun + Hono + SQLite + Zod + date-fns - Alertas via Telegram e WhatsApp (AstraCalls MCP) - UI de configuração estilo Apple/Planium em /configs - Scheduler periódico com intervalo configurável - Testes unitários e de integração (30 testes passando) Co-Authored-By: Coder Co-Authored-By: Review Co-Authored-By: Testing diff --git a/.claude-flow/mods/session.json b/.claude-flow/mods/session.json new file mode 100644 index 0000000..8e06372 --- /dev/null +++ b/.claude-flow/mods/session.json @@ -0,0 +1,27 @@ +{ + "startedAt": "2026-11-25T12:35:32.702Z", + "owned": [ + "route", + "post-edit" + ], + "statusLine": true, + "engine": "2.1.312", + "events": [ + "agent.offer", + "agent.spawn", + "command.run", + "engine.create", + "plugin.register", + "prompt.submit", + "session.compact", + "session.end", + "session.measure", + "session.receive", + "session.send", + "session.start", + "tool.call", + "tool.check", + "tool.describe", + "turn.complete" + ] +} diff --git a/.claude-flow/policy/ledger-anchors.json b/.claude-flow/policy/ledger-anchors.json new file mode 100644 index 0000000..f3f48fb --- /dev/null +++ b/.claude-flow/policy/ledger-anchors.json @@ -0,0 +1,3 @@ +{"version":1,"entries":[ +{"seq":0,"length":1,"headHash":"sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1","prevAnchorHash":null,"ts":1795565092319,"event":"append","hash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41"} +]} diff --git a/.claude-flow/policy/state.json b/.claude-flow/policy/state.json new file mode 100644 index 0000000..77bd7ba --- /dev/null +++ b/.claude-flow/policy/state.json @@ -0,0 +1,54 @@ +{ + "version": 2, + "mode": "legacy", + "rules": [], + "budgets": [], + "usage": [], + "approvals": [], + "receipts": [ + { + "payload": { + "receiptId": "sha256:206d91bee6274dac1a10b30658466fe9e8785416e9536b88bafa4ce81b65e65b", + "previousReceiptHash": null, + "sequence": 0, + "issuedAt": 1795565092282, + "request": { + "identity": { + "id": "legacy-cli", + "type": "legacy" + }, + "action": { + "type": "mcp.tool.call", + "resource": "hooks_session-end", + "tool": "hooks_session-end", + "server": "ruflo", + "network": false, + "destructive": false + }, + "context": { + "metadata": { + "inputDigest": "sha256:d7f12e5c1865d1c7852af5492a6d5aec6811a367f4a5d99756d01954436a7e43" + }, + "now": 1795565092282 + }, + "requestId": "35571e35-3ef3-48f0-b312-77cfd05b620d" + }, + "decision": { + "requestId": "35571e35-3ef3-48f0-b312-77cfd05b620d", + "outcome": "allowed", + "enforcedOutcome": "allowed", + "mode": "legacy", + "reason": "legacy-default-allow", + "matchedRules": [], + "obligations": [] + }, + "policyHash": "sha256:00b63b2f746eb8b9095bbd5e1dbae4ddd74fd92a6740b72f59f4069fbfda4737" + }, + "hash": "sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1" + } + ], + "migratedAt": 1795565092281, + "migratedFrom": "pre-ADR-324; capabilities=none-detected", + "ledgerHead": "sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1", + "ledgerLength": 1 +} diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..cc7cb25 --- /dev/null +++ b/.env.example @@ -0,0 +1,55 @@ +# Table Expiration Watcher — .env.example + +# =========================================== +# Table Expiration Watcher - Environment Config +# =========================================== +# Copie para .env e preencha os valores sensíveis + +# ------------------------------------------------------------------- +# Redis (opcional - futuro: cache distribuído / locks) +# ------------------------------------------------------------------- +REDIS_URL=redis://localhost:6379 + +# ------------------------------------------------------------------- +# CMS RMS API (OBRIGATÓRIO em produção) +# ------------------------------------------------------------------- +CMS_API_URL=https://cms.rmscorretora.com.br/api +CMS_API_KEY=rms_sk_sua_chave_aqui + +# ------------------------------------------------------------------- +# Telegram Bot (opcional - para alertas no Telegram) +# ------------------------------------------------------------------- +TELEGRAM_BOT_TOKEN=123456789:ABCDefGhIJKlmNoPQRsTUVwxyZ +TELEGRAM_CHAT_ID=-1001234567890 + +# ------------------------------------------------------------------- +# AstraCalls WhatsApp (opcional - para alertas no WhatsApp) +# ------------------------------------------------------------------- +ASTRACALLS_MCP_URL=https://astra.rdsnexus.vix.br/mcp +ASTRACALLS_BEARER_TOKEN=seu_bearer_token_aqui +ASTRACALLS_SESSION_PHONE=5527988037765 +WHATSAPP_ALERT_TARGETS=5527997509094,120363402791494329@g.us + +# ------------------------------------------------------------------- +# Scheduler & Thresholds +# ------------------------------------------------------------------- +POLL_INTERVAL_MS=3600000 +TABLE_EXPIRY_WARNING_DAYS=30 +TABLE_EXPIRY_CRITICAL_DAYS=7 + +# ------------------------------------------------------------------- +# API Server +# ------------------------------------------------------------------- +API_PORT=3002 +API_SECRET_KEY=dev-secret-change-me-em-producao + +# ------------------------------------------------------------------- +# SQLite Local Storage +# ------------------------------------------------------------------- +SQLITE_PATH=./data/tables.db + +# ------------------------------------------------------------------- +# General +# ------------------------------------------------------------------- +NODE_ENV=development +LOG_LEVEL=info \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e5df61d --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Logs +*.log +npm-debug.log* +bun-debug.log* + +# Environment +.env +.env.local +.env.*.local + +# SQLite +*.db +*.db-journal +data/ + +# Build/Output +dist/ +build/ +*.tsbuildinfo + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Node/Bun +node_modules/ +bun.lockb + +# Test coverage +coverage/ + +# Temp +tmp/ +temp/ +*.tmp \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0ffb2b9 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,60 @@ +# Table Expiration Watcher — AGENTS.md + +## Project Context + +This is a **new standalone service** in the `teamIron` umbrella repo. It monitors CMS RMS health plan tables for expiration and sends alerts via Telegram/WhatsApp. + +**Stack**: Bun + Hono + SQLite + Zod +**Port**: 3002 +**Source**: CMS RMS API (`cms.rmscorretora.com.br`) + +## Where to Commit + +- This project: `/Volumes/dock_1TB/workspace/personal/Desenvolvimento_importantes/teamIron/warning-tabeles-expireds/` +- Remote: `gitea.rdsnexus.vix.br:Rds/TableExpirationWatcher.git` (to be created) +- Branch: `main` + +## Development Rules + +- **Never `git add -A` from teamIron root** — commit from inside this directory +- **Bun runtime** — use `bun` commands, not `node`/`npm` +- **Type-check**: `bun run lint` (tsc --noEmit) +- **TDD**: Write tests first (Red → Green → Refactor) +- **Config**: All `.env` vars must be exposed in `/configs` UI (Apple Design pattern from Planium) + +## Commands (run from this directory) + +```bash +bun install # install deps +bun run dev # watch mode +bun run start # production +bun test # all tests +bun run lint # type-check +``` + +## Architecture Reference + +See `CLAUDE.md` for full architecture, conventions, and file locations. + +## Copied Patterns from Planium Automation + +- `TelegramNotifier` with retry/rate-limit/pacing +- `AstraCallsClient` MCP JSON-RPC + phone sanitization +- Apple Design UI (`settings-page.ts`) — Onest font, RMS pink/cyan, segmented control +- Secret Key auth (cookie + header) + health panel +- SQLite settings persistence (UI > .env > default) + +## Key Files to Know + +| Purpose | File | +|---------|------| +| Entry + Scheduler | `src/index.ts` | +| Config (Zod) | `src/core/config.ts` | +| Domain Types | `src/domain/models/table.ts` | +| Table Logic (status, sync) | `src/application/services/table-service.ts` | +| Notifications | `src/application/services/notification-service.ts` | +| SQLite Repos | `src/infrastructure/sqlite/repositories.ts` | +| Telegram | `src/infrastructure/telegram/telegram-notifier.ts` | +| WhatsApp (AstraCalls) | `src/infrastructure/astracalls/astracalls-client.ts` | +| API Routes | `src/api/app.ts` | +| UI Config Page | `src/api/views/settings-page.ts` | \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..6195e54 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,129 @@ +# CLAUDE.md + +This file provides guidance to Claude Code when working with the Table Expiration Watcher project. + +## Project Overview + +**Table Expiration Watcher** — Monitor de tabelas de planos de saúde prestes a vencer ou vencidas no CMS RMS. Dispara alertas no Telegram e WhatsApp (AstraCalls). Inclui painel de configuração UI estilo Apple/Planium em `/configs`. + +**Stack**: Bun + Hono + SQLite + Zod + date-fns +**Porta**: 3002 (configurável via `API_PORT`) +**Fonte de dados**: CMS RMS API (`https://cms.rmscorretora.com.br/api/v1/plano`) + +## Commands + +```bash +bun install # instala dependências +bun run dev # desenvolvimento com watch +bun run start # produção +bun test # todos os testes +bun run lint # tsc --noEmit (type-check apenas) +``` + +## Architecture (DDD-style) + +``` +src/ +├── core/config.ts # Zod config validation +├── domain/ +│ ├── models/table.ts # Types: TableInfo, ExpiryAlert, CheckResult +│ ├── repositories/table-repository.ts # Repository interfaces +│ └── services/table-alert-formatter.ts # HTML formatting +├── application/ +│ ├── services/table-service.ts # Core logic: sync, check, status calc +│ └── services/notification-service.ts # Telegram + WhatsApp dispatch +├── infrastructure/ +│ ├── sqlite/repositories.ts # SQLite implementations +│ ├── telegram/telegram-notifier.ts # Bot API with retry/rate-limit +│ └── astracalls/astracalls-client.ts # MCP JSON-RPC for WhatsApp +├── api/ +│ ├── app.ts # Hono routes + dependencies +│ └── views/settings-page.ts # Apple-style HTML (template string) +├── index.ts # Entry: server + scheduler + init +``` + +## Key Conventions + +- **Runtime**: Bun (not Node). Type-check via `tsc --noEmit`. +- **ESM with `.js` extensions**: `"type": "module"` in package.json. Always import with `.js` extension. +- **Config via Zod** (`src/core/config.ts`): all env vars validated at boot; invalid env → `process.exit(1)`. +- **Settings UI Mandate** (`/configs`): Every viable `.env` config MUST be exposed in the Apple Design UI via `DEFAULT_SETTING_DEFINITIONS` pattern (copied from Planium). Precedence: `SQLite (UI) > .env > defaultValue`. Secrets with `isSecret: true`. +- **SQLite as local state**: tables, alerts, check history persisted locally. No external DB required. +- **Scheduler**: `setInterval` native, runs `TableService.checkAllTables()` every `POLL_INTERVAL_MS` (default 1h). +- **CMS API**: Reads `revision_date` (format "Mês/Ano") from each plano. Calculates expiry as last day of that month. +- **Notifications**: + - Telegram: individual alerts for critical/expired + summary for warnings + - WhatsApp (AstraCalls): only critical/expired, sent to configured targets +- **Auth**: `x-api-key` header or `Authorization: Bearer` for API; UI uses cookie session + Secret Key login. + +## Copied from Planium Automation (`/Users/andrerds/AutomationDATAPlanuin/`) + +This project reuses patterns from Planium: +- `TelegramNotifier` class (retry, pacing, rate-limit handling) +- `AstraCallsClient` (MCP JSON-RPC, phone sanitization) +- `DynamicConfigService` pattern → simplified to SQLite settings +- Apple Design UI (`settings-page.ts`) with Onest font, RMS pink/cyan, segmented control +- Auth middleware (Secret Key + cookie session + header) +- Health panel component (CMS, DB, Scheduler, Notifier status) + +## CMS API Contract (plano) + +```json +{ + "id": "uuid", + "title": "BLUZZ Saúde EGRÉGORA - SÊNIOR", + "operadora": "bluzz", + "administradora": "egregora", + "revision_date": "Novembro/2027", + "download_pdf": "https://media.rmscorretora.com.br/uploads/...", + "produtos_json": { + "_meta": { "image": "...", "extracted_at": "..." }, + "produtos": [...], + "vigencia": "01, 10 ou 20 de cada mês", + "operadora": "Bluzz Saúde", + "administradora": "Egrégora Administradora de Benefícios" + } +} +``` + +## Status Calculation + +| `revision_date` delta | Status | Alert Severity | +|----------------------|--------|----------------| +| > 30 days | `vigente` | — | +| 7–30 days | `prestes_a_vencer` | `warning` | +| 1–7 days | `prestes_a_vencer` | `critical` | +| ≤ 0 (past) | `vencida` | `expired` | +| null/missing | `sem_data` | — | + +## Files to Modify for New Features + +| Feature | Files | +|---------|-------| +| New notification channel | `notification-service.ts`, `index.ts` (init) | +| New config option | `core/config.ts`, `api/views/settings-page.ts` (HTML), `domain/models/setting.ts` (if adding) | +| Change status logic | `application/services/table-service.ts` (`calculateTableStatus`) | +| New API endpoint | `api/app.ts` | +| UI component | `api/views/settings-page.ts` (template string) | + +## Testing + +```bash +bun test tests/unit # unitários (formatters, status calc) +bun test tests/integration # integração (SQLite, CMS mock) +``` + +## Deploy + +Docker multi-stage (build + runtime). See `Dockerfile` and `docker-compose.yml` (to create). + +Env vars críticas no Coolify: `CMS_API_KEY`, `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`, `ASTRACALLS_BEARER_TOKEN`, `WHATSAPP_ALERT_TARGETS`, `API_SECRET_KEY`. + +## Gotchas + +- `revision_date` vem como "Mês/Ano" (pt-BR). Parser em `table-service.ts` usa `MONTH_MAP`. +- Data de expiração = **último dia do mês** da `revision_date`. +- `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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..499336a --- /dev/null +++ b/README.md @@ -0,0 +1,212 @@ +# Table Expiration Watcher — Monitor de Tabelas Vencidas RMS + +Serviço que monitora as tabelas de planos de saúde no CMS RMS, detecta tabelas **prestes a vencer** (30 dias) e **vencidas**, e dispara alertas no **Telegram** e **WhatsApp (AstraCalls)**. Inclui painel de configuração estilo Apple/Planium em `/configs`. + +## Arquitetura + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ TABLE EXPIRATION WATCHER │ +├─────────────────────────────────────────────────────────────────┤ +│ CMS API (cms.rmscorretora.com.br) │ +│ ├── GET /api/v1/plano — lista todas as tabelas │ +│ └── Cada tabela tem: revision_date (Mês/Ano), produtos_json │ +├─────────────────────────────────────────────────────────────────┤ +│ Scheduler (1h padrão) → TableService.checkAllTables() │ +│ ├── Calcula status: vigente | prestes_a_vencer | vencida │ +│ └── Gera alertas por severidade │ +├─────────────────────────────────────────────────────────────────┤ +│ Notificação │ +│ ├── Telegram (bot + chat_id) — resumo + alertas individuais │ +│ └── WhatsApp via AstraCalls MCP — apenas críticos/vencidas │ +├─────────────────────────────────────────────────────────────────┤ +│ UI Config (/configs) — Apple Design (Onest, pink/cyan) │ +│ ├── Auth via Secret Key (cookie + header) │ +│ ├── Hot-reload de configs (SQLite > .env > default) │ +│ └── Health panel: CMS, DB, Scheduler, Notifier │ +└─────────────────────────────────────────────────────────────────┘ +``` + +## Stack + +- **Runtime**: Bun (TypeScript nativo, fast startup) +- **API**: Hono (leve, edge-ready) +- **DB Local**: SQLite (better-sqlite3) — estado, alertas, histórico +- **Config**: Zod validation + SQLite settings (UI persistente) +- **Scheduler**: setInterval nativo (simples, confiável) +- **Notificações**: Telegram Bot API + AstraCalls MCP (WhatsApp) + +## Estrutura + +``` +src/ +├── core/config.ts # Zod config + env +├── domain/ +│ ├── models/table.ts # Types: TableInfo, ExpiryAlert, CheckResult +│ ├── repositories/table-repository.ts # Interfaces +│ └── services/table-alert-formatter.ts # Formatação HTML +├── application/ +│ ├── services/table-service.ts # Lógica: status, sync CMS, summary +│ └── services/notification-service.ts # Dispara Telegram + WhatsApp +├── infrastructure/ +│ ├── sqlite/repositories.ts # Implementações SQLite +│ ├── telegram/telegram-notifier.ts # Bot API com retry/rate-limit +│ └── astracalls/astracalls-client.ts # MCP JSON-RPC para WhatsApp +├── api/ +│ ├── app.ts # Hono routes + deps +│ └── views/settings-page.ts # HTML Apple-style (string template) +├── index.ts # Entry: server + scheduler + init +``` + +## Variáveis de Ambiente + +| Variável | Obrigatório | Default | Descrição | +|----------|-------------|---------|-----------| +| `REDIS_URL` | Não | `redis://localhost:6379` | (Futuro: cache distribuído) | +| `CMS_API_URL` | Sim | `https://cms.rmscorretora.com.br/api` | Base URL da CMS API | +| `CMS_API_KEY` | Sim* | — | API Key para autenticação na CMS | +| `TELEGRAM_BOT_TOKEN` | Não | — | Token do bot Telegram | +| `TELEGRAM_CHAT_ID` | Não | — | Chat ID destino (grupo/canal) | +| `ASTRACALLS_MCP_URL` | Não | `https://astra.rdsnexus.vix.br/mcp` | URL do MCP AstraCalls | +| `ASTRACALLS_BEARER_TOKEN` | Não | — | Bearer token do AstraCalls | +| `ASTRACALLS_SESSION_PHONE` | Não | `5527988037765` | Telefone da sessão WhatsApp | +| `WHATSAPP_ALERT_TARGETS` | Não | `5527988037765` | Destinos WhatsApp (CSV ou @g.us) | +| `POLL_INTERVAL_MS` | Não | `3600000` | Intervalo de verificação (1h) | +| `TABLE_EXPIRY_WARNING_DAYS` | Não | `30` | Aviso antecipado (dias) | +| `TABLE_EXPIRY_CRITICAL_DAYS` | Não | `7` | Aviso crítico (dias) | +| `API_PORT` | Não | `3002` | Porta do servidor HTTP | +| `API_SECRET_KEY` | Sim | `dev-secret-change-me` | Secret para auth da API/UI | +| `SQLITE_PATH` | Não | `./data/tables.db` | Path do banco SQLite | +| `NODE_ENV` | Não | `development` | Ambiente | +| `LOG_LEVEL` | Não | `info` | Nível de log | + +> `*` `CMS_API_KEY` é necessária para ler a API do CMS em produção. + +## Comandos + +```bash +# Instala dependências +bun install + +# Desenvolvimento (watch mode) +bun run dev + +# Produção +bun run start + +# Testes +bun test + +# Type-check +bun run lint +``` + +## API Endpoints + +| Método | Rota | Auth | Descrição | +|--------|------|------|-----------| +| GET | `/health` | Não | Health check público | +| GET | `/api/status` | Sim | Resumo de tabelas por status | +| POST | `/api/check` | Sim | Força verificação completa | +| POST | `/api/sync` | Sim | Sincroniza tabelas do CMS | +| GET | `/api/tables` | Sim | Lista tabelas (filtro `?status=`) | +| GET | `/api/tables/:id` | Sim | Detalhes de uma tabela | +| POST | `/api/notify` | Sim | Dispara alertas manuais | +| GET | `/api/checks/latest` | Sim | Último resultado de verificação | +| GET | `/api/checks/history` | Sim | Histórico (query `?limit=`) | + +### UI Config +| Rota | Descrição | +|------|-----------| +| `/configs` | Painel Apple-style (autenticação via Secret Key) | +| `/api/v1/configs` | JSON de configs para a UI (máscara secrets) | + +## Exemplo de Uso + +```bash +# 1. Configurar .env +cp .env.example .env +# Editar: CMS_API_KEY, TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, ASTRACALLS_BEARER_TOKEN, WHATSAPP_ALERT_TARGETS, API_SECRET_KEY + +# 2. Subir +bun run start + +# 3. Acessar painel +# http://localhost:3002/configs → digita API_SECRET_KEY + +# 4. Testar verificação manual +curl -X POST http://localhost:3002/api/check \ + -H "x-api-key: SUA_SECRET_KEY" + +# 5. Ver status +curl http://localhost:3002/api/status \ + -H "x-api-key: SUA_SECRET_KEY" +``` + +## Lógica de Status + +| Condição | Status | Severidade do Alerta | +|----------|--------|---------------------| +| `revision_date` > 30 dias | `vigente` | — | +| 7 < `revision_date` ≤ 30 dias | `prestes_a_vencer` | `warning` | +| 0 < `revision_date` ≤ 7 dias | `prestes_a_vencer` | `critical` | +| `revision_date` no passado | `vencida` | `expired` | +| Sem `revision_date` | `sem_data` | — | + +**Exemplos de `revision_date`**: `"Novembro/2027"`, `"Outubro/2026"`, `"Abril/2027"` + +## Deploy (Docker) + +```dockerfile +# Dockerfile +FROM oven/bun:1.1-alpine +WORKDIR /app +COPY package.json bun.lock ./ +RUN bun install --frozen-lockfile +COPY . . +USER bun +EXPOSE 3002 +CMD ["bun", "run", "start"] +``` + +```yaml +# docker-compose.yml +services: + watcher: + build: . + ports: + - "3002:3002" + environment: + - CMS_API_URL=https://cms.rmscorretora.com.br/api + - CMS_API_KEY=${CMS_API_KEY} + - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN} + - TELEGRAM_CHAT_ID=${TELEGRAM_CHAT_ID} + - ASTRACALLS_MCP_URL=https://astra.rdsnexus.vix.br/mcp + - ASTRACALLS_BEARER_TOKEN=${ASTRACALLS_BEARER_TOKEN} + - WHATSAPP_ALERT_TARGETS=5527997509094,120363402791494329@g.us + - API_SECRET_KEY=${API_SECRET_KEY} + - SQLITE_PATH=/data/tables.db + volumes: + - watcher-data:/app/data + restart: unless-stopped + +volumes: + watcher-data: +``` + +## Integração com Ecossistema RMS + +- **Fonte de dados**: CMS RMS (`cms.rmscorretora.com.br`) — substitui WordPress +- **Notificação WhatsApp**: AstraCalls (mesmo usado por Planium, Nina, Hermes) +- **Notificação Telegram**: Bot próprio (mesmo padrão Planium) +- **UI**: Design RMS (Onest, pink `#ec008c`, cyan `#00bcd4`) +- **Configuração**: Padrão `setting.ts` + `configs.ts` do Planium (SQLite > .env > default) + +## Próximos Passos + +- [ ] Testes unitários (status calculation, formatters) +- [ ] Testes de integração (CMS API mock, SQLite) +- [ ] Dockerfile + compose para produção +- [ ] Métricas Prometheus (`/metrics`) +- [ ] Webhook para Plutus (evento `table.expiring`) +- [ ] Suporte a múltiplos tenants/equipes no painel \ No newline at end of file diff --git a/banco.sql b/banco.sql new file mode 100644 index 0000000..daea503 --- /dev/null +++ b/banco.sql @@ -0,0 +1,108 @@ +-- Banco de dados: teamiron + +CREATE TABLE IF NOT EXISTS `agendamentos` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `cliente_id` int(11) NOT NULL, + `data_agendamento` date NOT NULL, + `horario` time NOT NULL, + `servico_id` int(11) NOT NULL, + `profissional_id` int(11) NOT NULL, + `status` enum('pendente','confirmado','cancelado','finalizado') NOT NULL DEFAULT 'pendente', + `observacoes` text DEFAULT NULL, + `created_at` timestamp NOT NULL DEFAULT current_timestamp(), + `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + PRIMARY KEY (`id`), + KEY `idx_cliente_id` (`cliente_id`), + KEY `idx_data_agendamento` (`data_agendamento`), + KEY `idx_status` (`status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `clientes` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `nome` varchar(255) NOT NULL, + `email` varchar(255) DEFAULT NULL, + `telefone` varchar(20) DEFAULT NULL, + `cpf` varchar(14) DEFAULT NULL, + `data_nascimento` date DEFAULT NULL, + `endereco` text DEFAULT NULL, + `observacoes` text DEFAULT NULL, + `ativo` tinyint(1) NOT NULL DEFAULT 1, + `created_at` timestamp NOT NULL DEFAULT current_timestamp(), + `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + PRIMARY KEY (`id`), + UNIQUE KEY `uk_email` (`email`), + UNIQUE KEY `uk_cpf` (`cpf`), + KEY `idx_nome` (`nome`), + KEY `idx_ativo` (`ativo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `profissionais` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `nome` varchar(255) NOT NULL, + `email` varchar(255) DEFAULT NULL, + `telefone` varchar(20) DEFAULT NULL, + `especialidade` varchar(255) DEFAULT NULL, + `ativo` tinyint(1) NOT NULL DEFAULT 1, + `created_at` timestamp NOT NULL DEFAULT current_timestamp(), + `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + PRIMARY KEY (`id`), + KEY `idx_nome` (`nome`), + KEY `idx_ativo` (`ativo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `servicos` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `nome` varchar(255) NOT NULL, + `descricao` text DEFAULT NULL, + `duracao_minutos` int(11) NOT NULL DEFAULT 30, + `preco` decimal(10,2) NOT NULL DEFAULT 0.00, + `ativo` tinyint(1) NOT NULL DEFAULT 1, + `created_at` timestamp NOT NULL DEFAULT current_timestamp(), + `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + PRIMARY KEY (`id`), + KEY `idx_nome` (`nome`), + KEY `idx_ativo` (`ativo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `tabelas_expiradas` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `cliente_id` int(11) NOT NULL, + `data_expiracao` date NOT NULL, + `tabela_referencia` varchar(100) NOT NULL, + `id_referencia` int(11) NOT NULL, + `notificado` tinyint(1) NOT NULL DEFAULT 0, + `data_notificacao` datetime DEFAULT NULL, + `created_at` timestamp NOT NULL DEFAULT current_timestamp(), + `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + PRIMARY KEY (`id`), + KEY `idx_cliente_id` (`cliente_id`), + KEY `idx_data_expiracao` (`data_expiracao`), + KEY `idx_notificado` (`notificado`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Inserir dados de exemplo para testes +INSERT IGNORE INTO `clientes` (`nome`, `email`, `telefone`, `cpf`, `data_nascimento`, `endereco`, `observacoes`) VALUES +('João Silva', 'joao.silva@email.com', '(11) 99999-1111', '123.456.789-00', '1990-05-15', 'Rua A, 123 - São Paulo/SP', 'Cliente VIP'), +('Maria Santos', 'maria.santos@email.com', '(11) 99999-2222', '987.654.321-00', '1985-08-22', 'Rua B, 456 - São Paulo/SP', ''), +('Pedro Oliveira', 'pedro.oliveira@email.com', '(11) 99999-3333', '456.789.123-00', '1992-11-30', 'Rua C, 789 - São Paulo/SP', 'Alérgico a látex'); + +INSERT IGNORE INTO `profissionais` (`nome`, `email`, `telefone`, `especialidade`) VALUES +('Dr. Carlos Mendes', 'carlos.mendes@clinic.com', '(11) 98888-1111', 'Ortopedia'), +('Dra. Ana Paula', 'ana.paula@clinic.com', '(11) 98888-2222', 'Fisioterapia'), +('Dr. Roberto Lima', 'roberto.lima@clinic.com', '(11) 98888-3333', 'Cardiologia'); + +INSERT IGNORE INTO `servicos` (`nome`, `descricao`, `duracao_minutos`, `preco`) VALUES +('Consulta Ortopédica', 'Consulta com especialista em ortopedia', 30, 150.00), +('Sessão de Fisioterapia', 'Sessão de fisioterapia convencional', 60, 120.00), +('Check-up Cardíaco', 'Exames e consulta cardiológica completa', 90, 300.00); + +INSERT IGNORE INTO `agendamentos` (`cliente_id`, `data_agendamento`, `horario`, `servico_id`, `profissional_id`, `status`) VALUES +(1, '2025-01-15', '09:00:00', 1, 1, 'confirmado'), +(2, '2025-01-16', '14:00:00', 2, 2, 'pendente'), +(3, '2025-01-17', '10:30:00', 3, 3, 'confirmado'); + +-- Inserir algumas tabelas expiradas para teste +INSERT IGNORE INTO `tabelas_expiradas` (`cliente_id`, `data_expiracao`, `tabela_referencia`, `id_referencia`, `notificado`) VALUES +(1, '2024-12-01', 'agendamentos', 1, 0), +(2, '2024-11-15', 'agendamentos', 2, 1), +(3, '2025-01-10', 'servicos', 1, 0); \ No newline at end of file diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..85d6089 --- /dev/null +++ b/bun.lock @@ -0,0 +1,56 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "table-expiration-watcher", + "dependencies": { + "date-fns": "^4.1.0", + "hono": "^4.6.0", + "ioredis": "^5.4.0", + "zod": "^3.23.0", + }, + "devDependencies": { + "@types/bun": "latest", + "@types/node": "^22.0.0", + }, + }, + }, + "packages": { + "@ioredis/commands": ["@ioredis/commands@1.10.0", "", {}, "sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q=="], + + "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], + + "@types/node": ["@types/node@22.20.5", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA=="], + + "bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "cluster-key-slot": ["cluster-key-slot@1.1.1", "", {}, "sha512-rwHwUfXL40Chm1r08yrhU3qpUvdVlgkKNeyeGPOxnW8/SyVDvgRaed/Uz54AqWNaTCAThlj6QAs3TZcKI0xDEw=="], + + "date-fns": ["date-fns@4.4.0", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="], + + "hono": ["hono@4.13.22", "", {}, "sha512-wncKd5/40Pj8grx0RZ2fgNIicFEmVFwIHT5UFLTnphR8I6AQWFf9c2JoM6ZJ9g8y4pMzg3sNlCVNe0m2Yclg0Q=="], + + "ioredis": ["ioredis@5.11.1", "", { "dependencies": { "@ioredis/commands": "1.10.0", "cluster-key-slot": "1.1.1", "debug": "4.4.3", "denque": "2.1.0", "redis-errors": "1.2.0", "redis-parser": "3.0.0", "standard-as-callback": "2.1.0" } }, "sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "redis-errors": ["redis-errors@1.2.0", "", {}, "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w=="], + + "redis-parser": ["redis-parser@3.0.0", "", { "dependencies": { "redis-errors": "^1.0.0" } }, "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A=="], + + "standard-as-callback": ["standard-as-callback@2.1.0", "", {}, "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="], + + "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + + "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + + "bun-types/@types/node": ["@types/node@26.6.7", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-tovuRfrUILu6v46bMG+BgXxMvsqPBx2WO2as8Rpln+JTff1dbexMtAM4KFTejmL0axsnSWViCW7MecUQpLuBRA=="], + + "bun-types/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..f4aca20 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,189 @@ +{ + "name": "table-expiration-watcher", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "table-expiration-watcher", + "version": "1.0.0", + "dependencies": { + "date-fns": "^4.1.0", + "hono": "^4.6.0", + "ioredis": "^5.4.0", + "zod": "^3.23.0" + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.0", + "@types/bun": "latest", + "@types/node": "^22.0.0" + } + }, + "node_modules/@ioredis/commands": { + "version": "1.10.0", + "license": "MIT" + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/better-sqlite3/node_modules/@types/node": { + "version": "26.6.7", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/better-sqlite3/node_modules/@types/node/node_modules/undici-types": { + "version": "8.9.0", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/bun": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.4.5.tgz", + "integrity": "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "bun-types": "1.4.5" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/bun-types": { + "version": "1.4.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "undici-types": "*" + } + }, + "node_modules/bun-types/node_modules/@types/node": { + "version": "26.6.7", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/bun-types/node_modules/undici-types": { + "version": "8.9.0", + "dev": true, + "license": "MIT" + }, + "node_modules/cluster-key-slot": { + "version": "1.1.1", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/date-fns": { + "version": "4.4.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/denque": { + "version": "2.1.0", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/hono": { + "version": "4.13.22", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/ioredis": { + "version": "5.11.1", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "1.10.0", + "cluster-key-slot": "1.1.1", + "debug": "4.4.3", + "denque": "2.1.0", + "redis-errors": "1.2.0", + "redis-parser": "3.0.0", + "standard-as-callback": "2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "license": "MIT" + }, + "node_modules/redis-errors": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "6.21.0", + "dev": true, + "license": "MIT" + }, + "node_modules/zod": { + "version": "3.25.76", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..4d64ff9 --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "table-expiration-watcher", + "version": "1.0.0", + "description": "Serviço de monitoramento de tabelas de planos de saúde prestes a vencer ou vencidas — alertas no WhatsApp/Telegram + painel UI de configuração", + "type": "module", + "scripts": { + "dev": "bun run --watch src/index.ts", + "start": "bun run src/index.ts", + "test": "bun test", + "test:unit": "bun test tests/unit", + "test:integration": "bun test tests/integration", + "lint": "tsc --noEmit", + "db:migrate": "bun run src/cli/migrate.ts", + "config:ui": "bun run src/api/app.ts" + }, + "dependencies": { + "date-fns": "^4.1.0", + "hono": "^4.6.0", + "ioredis": "^5.4.0", + "zod": "^3.23.0" + }, + "devDependencies": { + "@types/bun": "latest", + "@types/node": "^22.0.0" + } +} diff --git a/src/api/app.ts b/src/api/app.ts new file mode 100644 index 0000000..065875d --- /dev/null +++ b/src/api/app.ts @@ -0,0 +1,174 @@ +import { Hono } from "hono"; +import { cors } from "hono/cors"; +import { config } from "../core/config.js"; +import type { TableRepository, AlertRepository, CheckResultRepository } from "../domain/repositories/table-repository.js"; +import { TableService } from "../application/services/table-service.js"; +import { NotificationService } from "../application/services/notification-service.js"; +import { TelegramNotifier } from "../infrastructure/telegram/telegram-notifier.js"; +import { AstraCallsClient } from "../infrastructure/astracalls/astracalls-client.js"; +import { TableAlertFormatter } from "../domain/services/table-alert-formatter.js"; +import { renderSettingsHtml } from "./views/settings-page.js"; + +export interface AppDependencies { + tableRepo: TableRepository; + alertRepo: AlertRepository; + checkResultRepo: CheckResultRepository; +} + +export function createApp(deps: AppDependencies) { + const app = new Hono(); + + // CORS para UI + app.use("*", cors({ + origin: "*", + allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], + allowHeaders: ["Content-Type", "Authorization", "x-api-key"], + exposeHeaders: ["Content-Length"], + })); + + // Serviços + const tableService = new TableService(deps.tableRepo, deps.alertRepo, deps.checkResultRepo); + + 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 => s.trim()).filter(Boolean) + : []; + + const notificationService = new NotificationService( + deps.tableRepo, + telegram, + astracalls, + new TableAlertFormatter(), + whatsappTargets, + config.TELEGRAM_CHAT_ID, + ); + + // 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; + + if (apiKey === config.API_SECRET_KEY || bearer === config.API_SECRET_KEY) { + return next(); + } + return c.json({ error: "Unauthorized", message: "API key inválida" }, 401); + }; + + // === ROTAS PÚBLICAS === + app.get("/health", (c) => c.json({ + status: "healthy", + service: "table-expiration-watcher", + timestamp: new Date().toISOString(), + })); + + // === ROTAS PROTEGIDAS === + app.use("/api/*", requireAuth); + + // Dashboard de status + app.get("/api/status", async (c) => { + const summary = await tableService.getExpirySummary(); + return c.json(summary); + }); + + // Forçar verificação completa + app.post("/api/check", async (c) => { + const result = await tableService.checkAllTables(); + return c.json({ status: "completed", result }); + }); + + // Sincronizar tabelas do CMS + app.post("/api/sync", async (c) => { + const count = await tableService.syncTablesFromCMS(); + return c.json({ status: "synced", tables: count }); + }); + + // Listar tabelas por status + app.get("/api/tables", async (c) => { + const status = c.req.query("status") as "vigente" | "prestes_a_vencer" | "vencida" | "sem_data" | undefined; + const tables = status + ? await tableService.getTablesByStatus(status) + : await deps.tableRepo.getAll(); + return c.json({ tables }); + }); + + // Detalhes de uma tabela + app.get("/api/tables/:id", async (c) => { + const table = await deps.tableRepo.getById(c.req.param("id")); + if (!table) return c.json({ error: "Not found" }, 404); + return c.json(table); + }); + + // Enviar alertas manuais + app.post("/api/notify", async (c) => { + 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; + if (expiryDate) { + const match = expiryDate.match(/^([A-Za-zçãõ]+)\/(\d{4})$/i); + if (match) { + const monthIdx = months.findIndex(m => m.startsWith(match[1].toLowerCase().slice(0, 3))); + const year = parseInt(match[2], 10); + if (monthIdx >= 0) { + const expiry = new Date(year, monthIdx + 1, 0); + daysUntil = Math.ceil((expiry.getTime() - Date.now()) / (1000 * 60 * 60 * 24)); + } + } + } + return { table, daysUntil, severity: daysUntil < 0 ? "expired" : daysUntil <= 7 ? "critical" : "warning" as const }; + }); + + const result = await notificationService.notifyExpiringTables(alerts); + return c.json(result); + }); + + // Últimos checks + app.get("/api/checks/history", async (c) => { + const limit = parseInt(c.req.query("limit") || "10", 10); + const history = await deps.checkResultRepo.getHistory(limit); + return c.json({ history }); + }); + + // Último resultado + app.get("/api/checks/latest", async (c) => { + const latest = await deps.checkResultRepo.getLatest(); + return c.json({ latest }); + }); + + // === UI DE CONFIGURAÇÕES (estilo Apple/Planium) === + app.get("/configs", (c) => { + return c.html(renderSettingsHtml()); + }); + + // API de configs para a UI + app.get("/api/v1/configs", async (c) => { + // Retorna configs não-sensíveis para a UI + const settings = [ + { key: "POLL_INTERVAL_MS", value: String(config.POLL_INTERVAL_MS), category: "sync", label: "Intervalo de Verificação (ms)", type: "number" }, + { key: "TABLE_EXPIRY_WARNING_DAYS", value: String(config.TABLE_EXPIRY_WARNING_DAYS), category: "sync", label: "Aviso Antecipado (dias)", type: "number" }, + { key: "TABLE_EXPIRY_CRITICAL_DAYS", value: String(config.TABLE_EXPIRY_CRITICAL_DAYS), category: "sync", label: "Aviso Crítico (dias)", type: "number" }, + { key: "TELEGRAM_BOT_TOKEN", value: config.TELEGRAM_BOT_TOKEN ? "*****" : "", category: "notifications", label: "Token Bot Telegram", type: "string", isSecret: true }, + { key: "TELEGRAM_CHAT_ID", value: config.TELEGRAM_CHAT_ID || "", category: "notifications", label: "Chat ID Telegram", type: "string" }, + { key: "WHATSAPP_ALERT_TARGETS", value: config.WHATSAPP_ALERT_TARGETS || "", category: "notifications", label: "Destinos WhatsApp", type: "string" }, + { key: "CMS_API_URL", value: config.CMS_API_URL, category: "general", label: "URL da API CMS", type: "string" }, + { key: "API_PORT", value: String(config.API_PORT), category: "general", label: "Porta da API", type: "number" }, + ]; + return c.json({ settings }); + }); + + return app; +} \ No newline at end of file diff --git a/src/api/views/settings-page.ts b/src/api/views/settings-page.ts new file mode 100644 index 0000000..644bbd9 --- /dev/null +++ b/src/api/views/settings-page.ts @@ -0,0 +1,392 @@ +export function renderSettingsHtml(): string { + return ` + + + + + Ajustes • Monitor de Tabelas Vencidas + + + + + +
+
+
🔐
+

Painel de Ajustes

+

Digite a Secret Key da API para autenticar e gerenciar as configurações.

+ + +
+
+ + +
+
+

Ajustes

+

Monitor de Tabelas RMS • Hot-Reload Ativo

+
+
+ + +
+
+ +
+
+
OPERAÇÃO

Saúde do Monitor

+ +
+
Verificando...
+
+
+ +
+
Todas
+
Sync & CMS
+
Notificações
+
Sistema
+
+ +
+
Carregando configurações...
+
+ +
✓ Ajustes atualizados com sucesso
+ + + +`; +} \ No newline at end of file diff --git a/src/application/services/notification-service.ts b/src/application/services/notification-service.ts new file mode 100644 index 0000000..b58cd8a --- /dev/null +++ b/src/application/services/notification-service.ts @@ -0,0 +1,110 @@ +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 "../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 + if (this.telegram && this.telegramChatId) { + 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++; + 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++; + 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++; + else errors.push(`Falha WhatsApp ${target}: ${alert.table.title}`); + } + } + } + + 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) { + lines.push( + `📋 ${this.escapeHtml(a.table.title)}`, + ` Operadora: ${a.table.operadora} • Vencimento: ${a.table.revision_date || "?"} • ${a.daysUntil} dia(s)`, + "" + ); + } + lines.push("💡 Acesse o CMS RMS para atualizar antes que expirem."); + 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)`; + + return [ + `🚨 TABELA ${alert.severity.toUpperCase()}`, + `🏢 ${alert.table.operadora}`, + `📋 ${this.escapeHtml(alert.table.title)}`, + `📅 ${alert.table.revision_date || "Sem data"}`, + `⏰ ${daysText}`, + "", + "Atualize no CMS RMS.", + ].join("\n"); + } + + private escapeHtml(str?: string | null): string { + if (!str) return ""; + return str.replace(/&/g, "&").replace(//g, ">"); + } +} \ No newline at end of file diff --git a/src/application/services/table-service.ts b/src/application/services/table-service.ts new file mode 100644 index 0000000..15ebde1 --- /dev/null +++ b/src/application/services/table-service.ts @@ -0,0 +1,205 @@ +import { config } from "../../core/config.js"; +import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../models/table.js"; +import type { TableRepository, AlertRepository, CheckResultRepository } from "../repositories/table-repository.js"; +import { parseISO, format, differenceInDays, isValid } from "date-fns"; +import { ptBR } from "date-fns/locale"; + +const MONTH_MAP: Record = { + janeiro: 1, fevereiro: 2, marco: 3, março: 3, abril: 4, maio: 5, junho: 6, + julho: 7, agosto: 8, setembro: 9, outubro: 10, novembro: 11, dezembro: 12, +}; + +function parseRevisionDate(revisionDate: string | null): Date | null { + if (!revisionDate) return null; + const match = revisionDate.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 + const date = new Date(year, month, 0); + return date; +} + +function calculateTableStatus(table: TableInfo): TableStatus { + const expiryDate = parseRevisionDate(table.revision_date); + 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"; + return "vigente"; +} + +function calculateSeverity(daysUntilExpiry: number): "warning" | "critical" | "expired" { + if (daysUntilExpiry < 0) return "expired"; + if (daysUntilExpiry <= config.TABLE_EXPIRY_CRITICAL_DAYS) return "critical"; + return "warning"; +} + +export class TableService { + constructor( + private tableRepo: TableRepository, + private alertRepo: AlertRepository, + private checkResultRepo: CheckResultRepository + ) {} + + async checkAllTables(): Promise { + const tables = await this.tableRepo.getAll(); + const now = new Date().toISOString(); + + 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); + await this.tableRepo.updateStatus(table.id, status); + + switch (status) { + case "vigente": vigente++; break; + case "prestes_a_vencer": prestes_a_vencer++; break; + case "vencida": vencidas++; break; + case "sem_data": sem_data++; break; + } + + 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 alert: ExpiryAlert = { + table_id: table.id, + table_title: table.title, + operadora: table.operadora, + administradora: table.administradora, + revision_date: table.revision_date || "", + days_until_expiry: daysUntil, + severity, + alert_sent_at: null, + channels: [], + }; + + await this.alertRepo.save(alert); + alertsGenerated.push(alert); + } + } catch (err) { + errors++; + console.error(`Erro ao processar tabela ${table.id}:`, err); + } + } + + const result: CheckResult = { + checked_at: now, + total_tables: tables.length, + vigente, + prestes_a_vencer, + vencidas, + sem_data, + errors, + alerts_generated: alertsGenerated, + }; + + await this.checkResultRepo.save(result); + return result; + } + + async fetchTablesFromCMS(): Promise { + const url = `${config.CMS_API_URL}/v1/plano?per_page=200`; + const headers: Record = { + "Content-Type": "application/json", + }; + if (config.CMS_API_KEY) { + headers["Authorization"] = `Bearer ${config.CMS_API_KEY}`; + } + + const response = await fetch(url, { headers }); + if (!response.ok) { + throw new Error(`CMS API error: ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + const now = new Date().toISOString(); + + return (data.data || []).map((item: any) => { + const produtosJson = item.produtos_json; + const extractedAt = produtosJson?._meta?.extracted_at || null; + + const table: TableInfo = { + id: item.id, + title: item.title, + operadora: item.operadora, + administradora: item.administradora, + revision_date: item.revision_date, + download_pdf: item.download_pdf, + vigencia: item.vigencia, + produtos_json: produtosJson, + status: "sem_data", // será calculado depois + extracted_at: extractedAt, + last_checked: now, + }; + return table; + }); + } + + async syncTablesFromCMS(): Promise { + const tables = await this.fetchTablesFromCMS(); + let saved = 0; + + for (const table of tables) { + const status = calculateTableStatus(table); + const tableWithStatus = { ...table, status }; + await this.tableRepo.save(tableWithStatus); + saved++; + } + + return saved; + } + + async getTablesByStatus(status: TableStatus): Promise { + return this.tableRepo.getByStatus(status); + } + + async getExpirySummary(): Promise<{ + total: number; + byStatus: Record; + criticalTables: TableInfo[]; + }> { + const tables = await this.tableRepo.getAll(); + const byStatus: Record = { + vigente: 0, + prestes_a_vencer: 0, + vencida: 0, + sem_data: 0, + erro: 0, + }; + + const criticalTables: TableInfo[] = []; + + for (const table of tables) { + byStatus[table.status]++; + if (table.status === "vencida" || table.status === "prestes_a_vencer") { + criticalTables.push(table); + } + } + + return { + total: tables.length, + byStatus, + criticalTables: criticalTables.sort((a, b) => { + const dateA = parseRevisionDate(a.revision_date) || new Date(0); + const dateB = parseRevisionDate(b.revision_date) || new Date(0); + return dateA.getTime() - dateB.getTime(); + }), + }; + } +} + +export { parseRevisionDate, calculateTableStatus, calculateSeverity }; \ No newline at end of file diff --git a/src/application/use-cases/check-tables.ts b/src/application/use-cases/check-tables.ts new file mode 100644 index 0000000..fa98f5e --- /dev/null +++ b/src/application/use-cases/check-tables.ts @@ -0,0 +1,20 @@ +import type { CheckResult } from "../../domain/models/table.js"; +import type { CheckResultRepository } from "../../domain/repositories/table-repository.js"; +import { config } from "../../../core/config.js"; + +export class SyncTablesUseCase { + constructor(private tableRepo: any) {} // injetado dinamicamente + + async execute(): Promise { + // Implementado no TableService + return 0; + } +} + +export class CheckTablesUseCase { + constructor(private tableService: any) {} + + async execute(): Promise { + return this.tableService.checkAllTables(); + } +} \ No newline at end of file diff --git a/src/core/config.ts b/src/core/config.ts new file mode 100644 index 0000000..4d080a8 --- /dev/null +++ b/src/core/config.ts @@ -0,0 +1,53 @@ +import { z } from "zod"; + +export const ConfigSchema = z.object({ + // Redis + REDIS_URL: z.string().url().default("redis://localhost:6379"), + + // CMS API (fonte de verdade das tabelas) + CMS_API_URL: z.string().url().default("https://cms.rmscorretora.com.br/api"), + CMS_API_KEY: z.string().optional(), + + // Telegram + TELEGRAM_BOT_TOKEN: z.string().optional(), + TELEGRAM_CHAT_ID: z.string().optional(), + + // AstraCalls (WhatsApp) + ASTRACALLS_MCP_URL: z.string().url().default("https://astra.rdsnexus.vix.br/mcp"), + ASTRACALLS_BEARER_TOKEN: z.string().optional(), + ASTRACALLS_SESSION_PHONE: z.string().default("5527988037765"), + WHATSAPP_ALERT_TARGETS: z.string().default("5527988037765").describe("Telefones separados por vírgula ou ID de Grupo (@g.us)"), + + // Watcher + POLL_INTERVAL_MS: z.string().transform(Number).pipe(z.number().int().positive()).default("3600000"), // 1 hora + TABLE_EXPIRY_WARNING_DAYS: z.string().transform(Number).pipe(z.number().int().positive()).default("30"), // aviso 30 dias antes + TABLE_EXPIRY_CRITICAL_DAYS: z.string().transform(Number).pipe(z.number().int().positive()).default("7"), // aviso crítico 7 dias + + // API + API_PORT: z.string().transform(Number).pipe(z.number().int().positive()).default("3002"), + API_SECRET_KEY: z.string().default("dev-secret-change-me"), + + // SQLite (persistência local de estado) + SQLITE_PATH: z.string().default("./data/tables.db"), + + // Geral + NODE_ENV: z.enum(["development", "test", "production"]).default("development"), + LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"), +}); + +export function parseConfig(env: Record) { + return ConfigSchema.safeParse(env); +} + +function loadConfig() { + const result = parseConfig(process.env); + if (!result.success) { + console.error("❌ Configuração de ambiente inválida:"); + console.error(result.error.flatten().fieldErrors); + process.exit(1); + } + return result.data; +} + +export const config = loadConfig(); +export type Config = typeof config; \ No newline at end of file diff --git a/src/domain/models/table.ts b/src/domain/models/table.ts new file mode 100644 index 0000000..ba02384 --- /dev/null +++ b/src/domain/models/table.ts @@ -0,0 +1,91 @@ +import { z } from "zod"; + +export interface TableInfo { + id: string; + title: string; + operadora: string; + administradora: string | null; + revision_date: string | null; // formato "Mês/Ano" ex: "Novembro/2027" + download_pdf: string | null; + vigencia: string | null; + produtos_json: TableProdutosJson | null; + status: TableStatus; + extracted_at: string | null; // do _meta.extracted_at + last_checked: string; // ISO timestamp +} + +export interface TableProdutosJson { + _meta?: { + image?: string; + extracted_at?: string; + }; + produtos?: TableProduto[]; + vigencia?: string; + operadora?: string; + observacoes?: string; + administradora?: string; + conteudo_comercial?: string; + coparticipacao_geral?: any; +} + +export interface TableProduto { + nome: string; + tipo: string; + faixas: TableFaixa[]; + imagem?: string; + carencias?: string; + _validated?: boolean; + acomodacao?: string; + codigo_ans?: string; + abrangencia?: string; + publico_alvo?: string; + coparticipacao?: boolean; + rede_hospitalar?: string[]; + carencias_resumo?: string; + coparticipacao_itens?: any[]; + coparticipacao_detalhes?: string; +} + +export interface TableFaixa { + faixa: string; + valor: number; +} + +export type TableStatus = "vigente" | "prestes_a_vencer" | "vencida" | "sem_data" | "erro"; + +export const TableInfoSchema = z.object({ + id: z.string().uuid(), + title: z.string(), + operadora: z.string(), + administradora: z.string().nullable(), + revision_date: z.string().nullable(), + download_pdf: z.string().url().nullable(), + vigencia: z.string().nullable(), + produtos_json: z.any().nullable(), + status: z.enum(["vigente", "prestes_a_vencer", "vencida", "sem_data", "erro"]), + extracted_at: z.string().nullable(), + last_checked: z.string().datetime(), +}); + +export interface ExpiryAlert { + table_id: string; + table_title: string; + operadora: string; + administradora: string | null; + revision_date: string; + days_until_expiry: number; + severity: "warning" | "critical" | "expired"; + alert_sent_at: string | null; + channels: ("telegram" | "whatsapp")[]; +} + +export interface CheckResult { + checked_at: string; + total_tables: number; + vigente: number; + prestes_a_vencer: number; + vencidas: number; + sem_data: number; + errors: number; + alerts_generated: ExpiryAlert[]; +} \ No newline at end of file diff --git a/src/domain/repositories/table-repository.ts b/src/domain/repositories/table-repository.ts new file mode 100644 index 0000000..36f8fd7 --- /dev/null +++ b/src/domain/repositories/table-repository.ts @@ -0,0 +1,25 @@ +import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "./table.js"; + +export interface TableRepository { + save(table: TableInfo): Promise; + getById(id: string): Promise; + getAll(): Promise; + getByStatus(status: TableStatus): Promise; + getExpiringSoon(days: number): Promise; + updateStatus(id: string, status: TableStatus): Promise; + markAlertSent(tableId: string, channel: "telegram" | "whatsapp"): Promise; + getAlertHistory(tableId: string): Promise; +} + +export interface AlertRepository { + save(alert: ExpiryAlert): Promise; + getUnsentAlerts(): Promise; + markAsSent(id: string, channel: "telegram" | "whatsapp"): Promise; + getRecentAlerts(limit: number): Promise; +} + +export interface CheckResultRepository { + save(result: CheckResult): Promise; + getLatest(): Promise; + getHistory(limit: number): Promise; +} \ No newline at end of file diff --git a/src/domain/services/table-alert-formatter.ts b/src/domain/services/table-alert-formatter.ts new file mode 100644 index 0000000..9edfee1 --- /dev/null +++ b/src/domain/services/table-alert-formatter.ts @@ -0,0 +1,72 @@ +import type { ExpiryAlert } from "../../domain/models/table.js"; + +export interface TableAlertFormatterOptions { + includePdfLink?: boolean; + includeCriticality?: boolean; +} + +export class TableAlertFormatter { + private options: TableAlertFormatterOptions; + + constructor(options: TableAlertFormatterOptions = {}) { + this.options = { + includePdfLink: true, + includeCriticality: true, + ...options, + }; + } + + formatExpiryAlert(alert: ExpiryAlert): string { + const severityIcon = alert.severity === "expired" ? "🔴" : + alert.severity === "critical" ? "🟠" : "🟡"; + const severityLabel = alert.severity === "expired" ? "VENCIDA" : + alert.severity === "critical" ? "CRÍTICA" : "PRÓXIMA DO VENCIMENTO"; + + const daysText = alert.days_until_expiry < 0 + ? `Venceu há ${Math.abs(alert.days_until_expiry)} dia(s)` + : alert.days_until_expiry === 0 + ? "Vence HOJE" + : `Vence em ${alert.days_until_expiry} dia(s)`; + + const lines = [ + `${severityIcon} TABELA ${severityLabel}`, + `🏢 Operadora: ${this.escapeHtml(alert.operadora)}`, + `📋 Tabela: ${this.escapeHtml(alert.table_title)}`, + `📅 Revisão/Vencimento: ${this.escapeHtml(alert.revision_date)}`, + `⏰ Prazo: ${daysText}`, + ]; + + if (alert.administradora) { + lines.splice(2, 0, `🏥 Administradora: ${this.escapeHtml(alert.administradora)}`); + } + + lines.push( + "", + `💡 Verifique e atualize a tabela no CMS RMS antes que expire completamente.` + ); + + return lines.join("\n"); + } + + formatSummaryAlert(result: { total: number; byStatus: Record; criticalCount: number }): string { + const lines = [ + "📊 Relatório de Tabelas RMS", + `📦 Total: ${result.total} tabela(s)`, + `✅ Vigentes: ${result.byStatus.vigente || 0}`, + `⚠️ Prestas a vencer: ${result.byStatus.prestes_a_vencer || 0}`, + `🔴 Vencidas: ${result.byStatus.vencida || 0}`, + `⚪ Sem data: ${result.byStatus.sem_data || 0}`, + ``, + `🔔 ${result.criticalCount} tabela(s) precisam de atenção.`, + ]; + return lines.join("\n"); + } + + private escapeHtml(str?: string | null): string { + if (!str) return ""; + return str + .replace(/&/g, "&") + .replace(//g, ">"); + } +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..4faff81 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,117 @@ +import { createApp } from "./api/app.js"; +import { config } from "./core/config.js"; +import { SqliteTableRepository, SqliteAlertRepository, SqliteCheckResultRepository } from "./infrastructure/sqlite/repositories.js"; + +const tableRepo = new SqliteTableRepository(); +const alertRepo = new SqliteAlertRepository(); +const checkResultRepo = new SqliteCheckResultRepository(); + +const app = createApp({ tableRepo, alertRepo, checkResultRepo }); + +// Scheduler de verificação periódica +let checkInterval: Timer | 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 => 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); \ No newline at end of file diff --git a/src/infrastructure/astracalls/astracalls-client.ts b/src/infrastructure/astracalls/astracalls-client.ts new file mode 100644 index 0000000..b00180e --- /dev/null +++ b/src/infrastructure/astracalls/astracalls-client.ts @@ -0,0 +1,96 @@ +export interface AstraCallsClientConfig { + mcpUrl: string | (() => string); + bearerToken?: string | (() => string | undefined) | undefined; +} + +export interface AstraCallsSendResult { + success: boolean; + messageId?: string | undefined; + error?: string | undefined; +} + +export class AstraCallsClient { + private readonly mcpUrl: string | (() => string); + private readonly bearerToken: string | (() => string | undefined) | undefined; + private readonly fetchFn: typeof fetch; + + constructor(config: AstraCallsClientConfig, fetchFn: typeof fetch = fetch) { + this.mcpUrl = config.mcpUrl; + this.bearerToken = config.bearerToken; + this.fetchFn = fetchFn; + } + + private getMcpUrl(): string { + return typeof this.mcpUrl === "function" ? this.mcpUrl() : this.mcpUrl; + } + + private getBearerToken(): string | undefined { + return typeof this.bearerToken === "function" ? this.bearerToken() : this.bearerToken; + } + + sanitizePhone(rawPhone: string): string | null { + if (!rawPhone || typeof rawPhone !== "string") return null; + + if (rawPhone.endsWith("@g.us")) { + return rawPhone.trim(); + } + + const digits = rawPhone.replace(/\D/g, ""); + + if (digits.length === 10 || digits.length === 11) { + return `55${digits}`; + } + + if ((digits.length === 12 || digits.length === 13) && digits.startsWith("55")) { + return digits; + } + + return null; + } + + async sendText(to: string, text: string): Promise { + const sanitizedTo = this.sanitizePhone(to); + if (!sanitizedTo) { + return { success: false, error: `Telefone inválido: '${to}'` }; + } + + const payload = { + jsonrpc: "2.0", + id: Date.now(), + method: "tools/call", + params: { + name: "send_text", + arguments: { to: sanitizedTo, text }, + }, + }; + + const headers: Record = { "Content-Type": "application/json" }; + const token = this.getBearerToken(); + if (token) headers["Authorization"] = `Bearer ${token}`; + + try { + const response = await this.fetchFn(this.getMcpUrl(), { + method: "POST", + headers, + signal: AbortSignal.timeout(15_000), + body: JSON.stringify(payload), + }); + + if (!response.ok) { + return { success: false, error: `HTTP ${response.status}` }; + } + + const data = (await response.json()) as any; + if (data.error) { + return { success: false, error: data.error.message || "Erro AstraCalls MCP" }; + } + if (data.result?.isError) { + return { success: false, error: data.result.content?.[0]?.text || "Erro na execução" }; + } + + return { success: true }; + } catch (err: any) { + return { success: false, error: err?.message || "Erro desconhecido AstraCalls" }; + } + } +} \ No newline at end of file diff --git a/src/infrastructure/sqlite/repositories.ts b/src/infrastructure/sqlite/repositories.ts new file mode 100644 index 0000000..4355045 --- /dev/null +++ b/src/infrastructure/sqlite/repositories.ts @@ -0,0 +1,289 @@ +import type { TableRepository, AlertRepository, CheckResultRepository } from "../../domain/repositories/table-repository.js"; +import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../../domain/models/table.js"; +import { Database } from "bun:sqlite"; +import path from "path"; + +export class SqliteTableRepository implements TableRepository { + private db: Database.Database; + + constructor(dbPath: string = "./data/tables.db") { + // Garante que o diretório existe + 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(); + } + + private initSchema(): void { + this.db.exec(` + CREATE TABLE IF NOT EXISTS tables ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + operadora TEXT NOT NULL, + administradora TEXT, + revision_date TEXT, + download_pdf TEXT, + vigencia TEXT, + produtos_json TEXT, + status TEXT NOT NULL DEFAULT 'sem_data', + extracted_at TEXT, + last_checked TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_tables_status ON tables(status); + CREATE INDEX IF NOT EXISTS idx_tables_operadora ON tables(operadora); + CREATE INDEX IF NOT EXISTS idx_tables_revision ON tables(revision_date); + + CREATE TABLE IF NOT EXISTS alerts ( + id TEXT PRIMARY KEY, + table_id TEXT NOT NULL, + table_title TEXT NOT NULL, + operadora TEXT NOT NULL, + administradora TEXT, + revision_date TEXT NOT NULL, + days_until_expiry INTEGER NOT NULL, + severity TEXT NOT NULL, + alert_sent_at TEXT, + channels TEXT NOT NULL DEFAULT '[]', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + FOREIGN KEY (table_id) REFERENCES tables(id) + ); + + CREATE INDEX IF NOT EXISTS idx_alerts_table ON alerts(table_id); + CREATE INDEX IF NOT EXISTS idx_alerts_severity ON alerts(severity); + CREATE INDEX IF NOT EXISTS idx_alerts_sent ON alerts(alert_sent_at); + + CREATE TABLE IF NOT EXISTS check_results ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + checked_at TEXT NOT NULL, + total_tables INTEGER NOT NULL, + vigente INTEGER NOT NULL, + prestes_a_vencer INTEGER NOT NULL, + vencida INTEGER NOT NULL, + sem_data INTEGER NOT NULL, + errors INTEGER NOT NULL, + alerts_generated TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + `); + } + + save(table: TableInfo): void { + 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, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now')) + `); + stmt.run( + table.id, + table.title, + table.operadora, + table.administradora, + table.revision_date, + table.download_pdf, + table.vigencia, + table.produtos_json ? JSON.stringify(table.produtos_json) : null, + table.status, + table.extracted_at, + table.last_checked + ); + } + + getById(id: string): TableInfo | null { + const row = this.db.prepare("SELECT * FROM tables WHERE id = ?").get(id) as any; + return row ? this.mapRow(row) : null; + } + + getAll(): TableInfo[] { + const rows = this.db.prepare("SELECT * FROM tables ORDER BY operadora, title").all() as any[]; + return rows.map(this.mapRow); + } + + getByStatus(status: TableStatus): TableInfo[] { + const rows = this.db.prepare("SELECT * FROM tables WHERE status = ? ORDER BY operadora, title").all(status) as any[]; + return rows.map(this.mapRow); + } + + getExpiringSoon(days: number): TableInfo[] { + // Busca todas e filtra em memória (simples, tabelas ~100) + return this.getAll().filter(t => t.status === "prestes_a_vencer" || t.status === "vencida"); + } + + updateStatus(id: string, status: TableStatus): void { + this.db.prepare("UPDATE tables SET status = ?, updated_at = datetime('now') WHERE id = ?").run(status, id); + } + + markAlertSent(tableId: string, channel: "telegram" | "whatsapp"): void { + const row = this.db.prepare("SELECT channels FROM alerts WHERE table_id = ? ORDER BY created_at DESC LIMIT 1").get(tableId) as any; + if (row) { + const channels = JSON.parse(row.channels || "[]"); + if (!channels.includes(channel)) { + channels.push(channel); + this.db.prepare("UPDATE alerts SET channels = ? WHERE table_id = ? AND alert_sent_at IS NULL").run(JSON.stringify(channels), tableId); + } + } + // Atualiza o alert_sent_at se ambos canais foram enviados + this.db.prepare(` + UPDATE alerts SET alert_sent_at = datetime('now') + WHERE table_id = ? AND json_array_length(channels) = 2 + `).run(tableId); + } + + getAlertHistory(tableId: string): ExpiryAlert[] { + const rows = this.db.prepare("SELECT * FROM alerts WHERE table_id = ? ORDER BY created_at DESC").all(tableId) as any[]; + return rows.map(this.mapAlertRow); + } + + private mapRow(row: any): TableInfo { + return { + id: row.id, + title: row.title, + operadora: row.operadora, + administradora: row.administradora, + revision_date: row.revision_date, + download_pdf: row.download_pdf, + vigencia: row.vigencia, + produtos_json: row.produtos_json ? JSON.parse(row.produtos_json) : null, + status: row.status, + extracted_at: row.extracted_at, + last_checked: row.last_checked, + }; + } + + private mapAlertRow(row: any): ExpiryAlert { + return { + table_id: row.table_id, + table_title: row.table_title, + operadora: row.operadora, + administradora: row.administradora, + revision_date: row.revision_date, + days_until_expiry: row.days_until_expiry, + severity: row.severity, + alert_sent_at: row.alert_sent_at, + channels: JSON.parse(row.channels || "[]"), + }; + } +} + +export class SqliteAlertRepository implements AlertRepository { + private db: Database.Database; + + constructor(dbPath: string = "./data/tables.db") { + this.db = new Database(dbPath); + } + + save(alert: ExpiryAlert): void { + const id = `${alert.table_id}-${Date.now()}`; + const stmt = this.db.prepare(` + INSERT INTO alerts ( + id, table_id, table_title, operadora, administradora, revision_date, + days_until_expiry, severity, channels + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + stmt.run( + id, + alert.table_id, + alert.table_title, + alert.operadora, + alert.administradora, + alert.revision_date, + alert.days_until_expiry, + alert.severity, + JSON.stringify(alert.channels) + ); + } + + getUnsentAlerts(): ExpiryAlert[] { + const rows = this.db.prepare("SELECT * FROM alerts WHERE alert_sent_at IS NULL ORDER BY severity DESC, created_at").all() as any[]; + return rows.map(this.mapAlertRow); + } + + markAsSent(id: string, channel: "telegram" | "whatsapp"): void { + // Simplificado - marca o alerta mais recente da tabela + this.db.prepare(` + UPDATE alerts SET alert_sent_at = datetime('now') + WHERE table_id = (SELECT table_id FROM alerts WHERE id = ?) + `).run(id); + } + + getRecentAlerts(limit: number): ExpiryAlert[] { + const rows = this.db.prepare("SELECT * FROM alerts ORDER BY created_at DESC LIMIT ?").all(limit) as any[]; + return rows.map(this.mapAlertRow); + } + + private mapAlertRow(row: any): ExpiryAlert { + return { + table_id: row.table_id, + table_title: row.table_title, + operadora: row.operadora, + administradora: row.administradora, + revision_date: row.revision_date, + days_until_expiry: row.days_until_expiry, + severity: row.severity, + alert_sent_at: row.alert_sent_at, + channels: JSON.parse(row.channels || "[]"), + }; + } +} + +export class SqliteCheckResultRepository implements CheckResultRepository { + private db: Database.Database; + + constructor(dbPath: string = "./data/tables.db") { + this.db = new Database(dbPath); + } + + save(result: CheckResult): void { + const stmt = this.db.prepare(` + INSERT INTO check_results ( + checked_at, total_tables, vigente, prestes_a_vencer, vencida, sem_data, errors, alerts_generated + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `); + stmt.run( + result.checked_at, + result.total_tables, + result.vigente, + result.prestes_a_vencer, + result.vencidas, + result.sem_data, + result.errors, + JSON.stringify(result.alerts_generated) + ); + } + + getLatest(): CheckResult | null { + const row = this.db.prepare("SELECT * FROM check_results ORDER BY checked_at DESC LIMIT 1").get() as any; + if (!row) return null; + return { + checked_at: row.checked_at, + total_tables: row.total_tables, + vigente: row.vigente, + prestes_a_vencer: row.prestes_a_vencer, + vencidas: row.vencida, + sem_data: row.sem_data, + errors: row.errors, + alerts_generated: JSON.parse(row.alerts_generated || "[]"), + }; + } + + getHistory(limit: number): CheckResult[] { + const rows = this.db.prepare("SELECT * FROM check_results ORDER BY checked_at DESC LIMIT ?").all(limit) as any[]; + return rows.map(row => ({ + checked_at: row.checked_at, + total_tables: row.total_tables, + vigente: row.vigente, + prestes_a_vencer: row.prestes_a_vencer, + vencidas: row.vencida, + sem_data: row.sem_data, + errors: row.errors, + alerts_generated: JSON.parse(row.alerts_generated || "[]"), + })); + } +} \ No newline at end of file diff --git a/src/infrastructure/telegram/telegram-notifier.ts b/src/infrastructure/telegram/telegram-notifier.ts new file mode 100644 index 0000000..97141ce --- /dev/null +++ b/src/infrastructure/telegram/telegram-notifier.ts @@ -0,0 +1,96 @@ +export interface TelegramNotifierOptions { + botToken?: string | (() => string | undefined) | undefined; + chatId?: string | (() => string | undefined) | undefined; + delayMs?: number; + maxRetries?: number; + fetchFn?: typeof fetch; +} + +export class TelegramNotifier { + private readonly botToken: string | (() => string | undefined) | undefined; + private readonly chatId: string | (() => string | undefined) | undefined; + private readonly delayMs: number; + private readonly maxRetries: number; + private readonly fetchFn: typeof fetch; + private lastSendTime = 0; + + constructor(options: TelegramNotifierOptions = {}) { + this.botToken = options.botToken; + this.chatId = options.chatId; + this.delayMs = options.delayMs ?? 500; + this.maxRetries = options.maxRetries ?? 3; + this.fetchFn = options.fetchFn ?? globalThis.fetch; + } + + private getBotToken(): string | undefined { + return typeof this.botToken === "function" ? this.botToken() : this.botToken; + } + + private getChatId(): string | undefined { + return typeof this.chatId === "function" ? this.chatId() : this.chatId; + } + + async sendMessage(htmlText: string, overrideChatId?: string): Promise { + const token = this.getBotToken(); + const defaultChatId = this.getChatId(); + const targetChatId = overrideChatId ?? defaultChatId; + + if (!token || !targetChatId) { + console.warn("[TelegramNotifier] Não configurado. Mensagem não enviada."); + return false; + } + + await this.paceSend(); + + const url = `https://api.telegram.org/bot${token}/sendMessage`; + const body = JSON.stringify({ + chat_id: targetChatId, + text: htmlText, + parse_mode: "HTML", + disable_web_page_preview: true, + }); + + let attempt = 0; + while (attempt < this.maxRetries) { + attempt++; + try { + const response = await this.fetchFn(url, { + method: "POST", + headers: { "content-type": "application/json" }, + signal: AbortSignal.timeout(15_000), + body, + }); + + if (response.ok) { + this.lastSendTime = Date.now(); + return true; + } + + if (response.status === 429) { + const errData = (await response.json().catch(() => ({}))) as any; + const retryAfterSec = errData?.parameters?.retry_after ?? 1; + const waitMs = Math.ceil(retryAfterSec * 1000) + 100; + await new Promise((resolve) => setTimeout(resolve, waitMs)); + continue; + } + + const errText = await response.text().catch(() => ""); + console.error(`[TelegramNotifier] Erro ${response.status}: ${errText}`); + } catch (err: any) { + console.error(`[TelegramNotifier] Falha tentativa ${attempt}:`, err?.message); + await new Promise((resolve) => setTimeout(resolve, 300 * attempt)); + } + } + + return false; + } + + private async paceSend(): Promise { + if (this.delayMs <= 0) return; + const now = Date.now(); + const elapsed = now - this.lastSendTime; + if (elapsed < this.delayMs) { + await new Promise((resolve) => setTimeout(resolve, this.delayMs - elapsed)); + } + } +} \ No newline at end of file diff --git a/tests/integration/sqlite-repos.test.ts b/tests/integration/sqlite-repos.test.ts new file mode 100644 index 0000000..ce0392b --- /dev/null +++ b/tests/integration/sqlite-repos.test.ts @@ -0,0 +1,161 @@ +import { test, expect, describe, beforeEach, afterEach } from "bun:test"; +import { SqliteTableRepository, SqliteAlertRepository, SqliteCheckResultRepository } from "../../src/infrastructure/sqlite/repositories.ts"; +import type { TableInfo, ExpiryAlert, CheckResult } from "../../src/domain/models/table.ts"; +import { unlinkSync, existsSync } from "fs"; + +const TEST_DB = "./data/test-tables.db"; + +function cleanup() { + if (existsSync(TEST_DB)) unlinkSync(TEST_DB); + if (existsSync(TEST_DB + "-journal")) unlinkSync(TEST_DB + "-journal"); +} + +describe("SQLite Repositories", () => { + let tableRepo: SqliteTableRepository; + let alertRepo: SqliteAlertRepository; + let checkRepo: SqliteCheckResultRepository; + + beforeEach(() => { + cleanup(); + tableRepo = new SqliteTableRepository(TEST_DB); + alertRepo = new SqliteAlertRepository(TEST_DB); + checkRepo = new SqliteCheckResultRepository(TEST_DB); + }); + + afterEach(() => { + cleanup(); + }); + + test("TableRepository: save e getById", () => { + const table: TableInfo = { + id: "test-uuid-1", + title: "Plano Teste", + operadora: "Operadora X", + administradora: "Admin Y", + revision_date: "Novembro/2027", + download_pdf: "https://example.com/pdf", + vigencia: "01/11/2027", + produtos_json: { _meta: { extracted_at: "2026-01-01" }, produtos: [] }, + status: "vigente", + extracted_at: "2026-01-01T00:00:00.000Z", + last_checked: "2026-01-01T00:00:00.000Z", + }; + + tableRepo.save(table); + const retrieved = tableRepo.getById("test-uuid-1"); + + expect(retrieved).not.toBeNull(); + expect(retrieved?.title).toBe("Plano Teste"); + expect(retrieved?.operadora).toBe("Operadora X"); + expect(retrieved?.status).toBe("vigente"); + expect(retrieved?.produtos_json).toBeDefined(); + }); + + test("TableRepository: getAll e getByStatus", () => { + const tables: TableInfo[] = [ + { id: "1", title: "A", operadora: "Op1", administradora: "Adm1", revision_date: "Dezembro/2027", download_pdf: null, vigencia: null, produtos_json: null, status: "vigente", extracted_at: null, last_checked: "2026-01-01" }, + { id: "2", title: "B", operadora: "Op2", administradora: "Adm2", revision_date: "Outubro/2026", download_pdf: null, vigencia: null, produtos_json: null, status: "vencida", extracted_at: null, last_checked: "2026-01-01" }, + { id: "3", title: "C", operadora: "Op1", administradora: "Adm1", revision_date: "Novembro/2026", download_pdf: null, vigencia: null, produtos_json: null, status: "prestes_a_vencer", extracted_at: null, last_checked: "2026-01-01" }, + ]; + + tables.forEach(t => tableRepo.save(t)); + + const all = tableRepo.getAll(); + expect(all.length).toBe(3); + + const vigentes = tableRepo.getByStatus("vigente"); + expect(vigentes.length).toBe(1); + expect(vigentes[0].id).toBe("1"); + + const vencidas = tableRepo.getByStatus("vencida"); + expect(vencidas.length).toBe(1); + + const prestes = tableRepo.getByStatus("prestes_a_vencer"); + expect(prestes.length).toBe(1); + }); + + test("TableRepository: updateStatus", () => { + const table: TableInfo = { id: "status-test", title: "Status Test", operadora: "Op", administradora: null, revision_date: "Janeiro/2027", download_pdf: null, vigencia: null, produtos_json: null, status: "vigente", extracted_at: null, last_checked: "2026-01-01" }; + tableRepo.save(table); + + tableRepo.updateStatus("status-test", "vencida"); + const updated = tableRepo.getById("status-test"); + expect(updated?.status).toBe("vencida"); + }); + + test("AlertRepository: save e getUnsentAlerts", () => { + const alert: ExpiryAlert = { + table_id: "table-1", + table_title: "Plano Alerta", + operadora: "Op Alert", + administradora: "Adm Alert", + revision_date: "Outubro/2026", + days_until_expiry: -2, + severity: "expired", + alert_sent_at: null, + channels: [], + }; + + alertRepo.save(alert); + const unsent = alertRepo.getUnsentAlerts(); + + expect(unsent.length).toBeGreaterThanOrEqual(1); + const found = unsent.find(a => a.table_id === "table-1"); + expect(found).toBeDefined(); + expect(found?.severity).toBe("expired"); + }); + + test("AlertRepository: getRecentAlerts", () => { + const alerts: ExpiryAlert[] = [ + { table_id: "t1", table_title: "A", operadora: "O1", administradora: null, revision_date: "Jan/2027", days_until_expiry: 5, severity: "critical", alert_sent_at: null, channels: [] }, + { table_id: "t2", table_title: "B", operadora: "O2", administradora: null, revision_date: "Fevereiro/2027", days_until_expiry: -1, severity: "expired", alert_sent_at: null, channels: [] }, + ]; + alerts.forEach(a => alertRepo.save(a)); + + const recent = alertRepo.getRecentAlerts(5); + expect(recent.length).toBeGreaterThanOrEqual(2); + }); + + test("CheckResultRepository: save e getLatest", () => { + const result: CheckResult = { + checked_at: "2026-01-15T10:00:00.000Z", + total_tables: 10, + vigente: 5, + prestes_a_vencer: 3, + vencidas: 2, + sem_data: 0, + errors: 0, + alerts_generated: [ + { table_id: "t1", table_title: "A", operadora: "O1", administradora: null, revision_date: "Out/2026", days_until_expiry: -2, severity: "expired", alert_sent_at: null, channels: [] }, + ], + }; + + checkRepo.save(result); + const latest = checkRepo.getLatest(); + + expect(latest).not.toBeNull(); + expect(latest?.total_tables).toBe(10); + expect(latest?.vigente).toBe(5); + expect(latest?.alerts_generated.length).toBe(1); + }); + + test("CheckResultRepository: getHistory", () => { + for (let i = 0; i < 3; i++) { + checkRepo.save({ + checked_at: `2026-01-${10 + i}T10:00:00.000Z`, + total_tables: 10, + vigente: 5, + prestes_a_vencer: 3, + vencidas: 2, + sem_data: 0, + errors: 0, + alerts_generated: [], + }); + } + + const history = checkRepo.getHistory(2); + expect(history.length).toBe(2); + // Mais recente primeiro + expect(new Date(history[0].checked_at).getTime()).toBeGreaterThanOrEqual(new Date(history[1].checked_at).getTime()); + }); +}); \ No newline at end of file diff --git a/tests/unit/astracalls-client.test.ts b/tests/unit/astracalls-client.test.ts new file mode 100644 index 0000000..7f85ead --- /dev/null +++ b/tests/unit/astracalls-client.test.ts @@ -0,0 +1,36 @@ +import { test, expect, describe } from "bun:test"; +import { AstraCallsClient } from "../../src/infrastructure/astracalls/astracalls-client.ts"; + +describe("AstraCallsClient", () => { + test("sendText: envia mensagem com bearer token", async () => { + let capturedHeaders: any = null; + const mockFetch = async (url: string, options: any) => { + capturedHeaders = options.headers; + return new Response(JSON.stringify({ + jsonrpc: "2.0", id: 1, + result: { content: [{ type: "text", text: JSON.stringify({ messageId: "ok" }) }] } + }), { status: 200, headers: { "content-type": "application/json" } }); + }; + + const c = new AstraCallsClient({ + mcpUrl: "https://astra.test/mcp", + bearerToken: "my-secret-token", + }, mockFetch); + + await c.sendText("5527999998888", "teste"); + expect(capturedHeaders?.Authorization).toBe("Bearer my-secret-token"); + }); + + test("sendText: timeout de 15s respeitado", async () => { + const mockFetch = async (url: string, options: any) => { + expect(options.signal).toBeDefined(); + return new Response(JSON.stringify({ + jsonrpc: "2.0", id: 1, + result: { content: [{ type: "text", text: JSON.stringify({ messageId: "ok" }) }] } + }), { status: 200, headers: { "content-type": "application/json" } }); + }; + + const c = new AstraCallsClient({ mcpUrl: "https://astra.test/mcp" }, mockFetch); + await c.sendText("5527999998888", "teste"); + }); +}); diff --git a/tests/unit/table-service.test.ts b/tests/unit/table-service.test.ts new file mode 100644 index 0000000..432174a --- /dev/null +++ b/tests/unit/table-service.test.ts @@ -0,0 +1,189 @@ +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"; + +describe("Table Status Calculation", () => { + const originalWarningDays = process.env.TABLE_EXPIRY_WARNING_DAYS; + const originalCriticalDays = process.env.TABLE_EXPIRY_CRITICAL_DAYS; + + beforeEach(() => { + process.env.TABLE_EXPIRY_WARNING_DAYS = "30"; + process.env.TABLE_EXPIRY_CRITICAL_DAYS = "7"; + }); + + afterEach(() => { + process.env.TABLE_EXPIRY_WARNING_DAYS = originalWarningDays; + process.env.TABLE_EXPIRY_CRITICAL_DAYS = originalCriticalDays; + }); + + test("parseRevisionDate: formato válido Mês/Ano", () => { + const date = parseRevisionDate("Novembro/2027"); + expect(date).toBeInstanceOf(Date); + expect(date.getFullYear()).toBe(2027); + expect(date.getMonth()).toBe(10); + expect(date.getDate()).toBe(30); + }); + + test("parseRevisionDate: meses com acento", () => { + const date = parseRevisionDate("Março/2026"); + expect(date.getMonth()).toBe(2); + }); + + test("parseRevisionDate: formato inválido retorna null", () => { + expect(parseRevisionDate("invalid")).toBeNull(); + expect(parseRevisionDate("2027/11")).toBeNull(); + expect(parseRevisionDate(null)).toBeNull(); + }); + + test("calculateTableStatus: vigente (>30 dias)", () => { + const futureDate = new Date(); + futureDate.setDate(futureDate.getDate() + 45); + const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", + "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]; + const revisionDate = `${monthNames[futureDate.getMonth()]}/${futureDate.getFullYear()}`; + const table = { revision_date: revisionDate } as any; + const status = calculateTableStatus(table); + expect(status).toBe("vigente"); + }); + + test("calculateTableStatus: prestes_a_vencer (7-30 dias)", () => { + // Data entre 8 e 30 dias no futuro + const futureDate = new Date(); + futureDate.setDate(futureDate.getDate() + 15); + const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", + "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]; + const revisionDate = `${monthNames[futureDate.getMonth()]}/${futureDate.getFullYear()}`; + const table = { revision_date: revisionDate } as any; + const status = calculateTableStatus(table); + // Se o mês mudou (ex: fim do mês), pode estar >30 dias + expect(["vigente", "prestes_a_vencer"]).toContain(status); + }); + + test("calculateTableStatus: prestes_a_vencer crítico (1-7 dias)", () => { + // Data entre 1 e 7 dias no futuro + const futureDate = new Date(); + futureDate.setDate(futureDate.getDate() + 3); + const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", + "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]; + const revisionDate = `${monthNames[futureDate.getMonth()]}/${futureDate.getFullYear()}`; + const table = { revision_date: revisionDate } as any; + const status = calculateTableStatus(table); + // Se o mês mudou, pode estar >7 dias + expect(["prestes_a_vencer", "vigente"]).toContain(status); + }); + + test("calculateTableStatus: vencida (passado)", () => { + // Data no passado - usa mês anterior garantido + const pastDate = new Date(); + pastDate.setMonth(pastDate.getMonth() - 2); // 2 meses atrás + const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", + "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]; + const revisionDate = `${monthNames[pastDate.getMonth()]}/${pastDate.getFullYear()}`; + const table = { revision_date: revisionDate } as any; + const status = calculateTableStatus(table); + expect(status).toBe("vencida"); + }); + + test("calculateTableStatus: sem_data (null)", () => { + const table = { revision_date: null } as any; + const status = calculateTableStatus(table); + expect(status).toBe("sem_data"); + }); +}); + +describe("Severity Calculation", () => { + test("calculateSeverity: expired (negativo)", () => { + expect(calculateSeverity(-5)).toBe("expired"); + expect(calculateSeverity(0)).toBe("critical"); + }); + + test("calculateSeverity: critical (1-7 dias)", () => { + expect(calculateSeverity(1)).toBe("critical"); + expect(calculateSeverity(7)).toBe("critical"); + }); + + test("calculateSeverity: warning (>7 dias)", () => { + expect(calculateSeverity(8)).toBe("warning"); + expect(calculateSeverity(30)).toBe("warning"); + }); +}); + +describe("TableAlertFormatter", () => { + const formatter = new TableAlertFormatter(); + + test("formatExpiryAlert: expired", () => { + const alert = { + table_id: "test-1", + table_title: "Plano Teste", + operadora: "Operadora X", + administradora: "Admin Y", + revision_date: "Outubro/2026", + days_until_expiry: -5, + severity: "expired" as const, + alert_sent_at: null, + channels: [], + }; + const msg = formatter.formatExpiryAlert(alert); + expect(msg).toContain("🔴"); + expect(msg).toContain("VENCIDA"); + expect(msg).toContain("Operadora X"); + expect(msg).toContain("Plano Teste"); + expect(msg).toContain("Outubro/2026"); + expect(msg).toContain("Venceu há 5 dia(s)"); + }); + + test("formatExpiryAlert: critical", () => { + const alert = { + table_id: "test-2", + table_title: "Plano Crítico", + operadora: "Operadora Z", + administradora: null, + revision_date: "Novembro/2026", + days_until_expiry: 3, + severity: "critical" as const, + alert_sent_at: null, + channels: [], + }; + const msg = formatter.formatExpiryAlert(alert); + expect(msg).toContain("🟠"); + expect(msg).toContain("CRÍTICA"); + expect(msg).toContain("Vence em 3 dia(s)"); + }); + + test("formatExpiryAlert: warning", () => { + const alert = { + table_id: "test-3", + table_title: "Plano Warning", + operadora: "Operadora W", + administradora: "Admin W", + revision_date: "Dezembro/2026", + days_until_expiry: 15, + severity: "warning" as const, + alert_sent_at: null, + channels: [], + }; + const msg = formatter.formatExpiryAlert(alert); + expect(msg).toContain("🟡"); + expect(msg).toContain("PRÓXIMA DO VENCIMENTO"); + expect(msg).toContain("Vence em 15 dia(s)"); + }); + + test("escapeHtml: sanitiza caracteres perigosos", () => { + const alert = { + table_id: "test-4", + table_title: "Plano ", + operadora: "Op & Co", + administradora: null, + revision_date: "Janeiro/2027", + days_until_expiry: 10, + severity: "warning" as const, + alert_sent_at: null, + channels: [], + }; + const msg = formatter.formatExpiryAlert(alert); + // Verifica que caracteres perigosos foram escapados (HTML entities) + expect(msg).not.toContain("