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 <coder@agent.local> Co-Authored-By: Review <review@agent.local> Co-Authored-By: Testing <testing@agent.local>
This commit is contained in:
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":1,"entries":[
|
||||
{"seq":0,"length":1,"headHash":"sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1","prevAnchorHash":null,"ts":1795565092319,"event":"append","hash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41"}
|
||||
]}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
+41
@@ -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
|
||||
@@ -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` |
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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);
|
||||
@@ -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=="],
|
||||
}
|
||||
}
|
||||
Generated
+189
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
+174
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
export function renderSettingsHtml(): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
|
||||
<title>Ajustes • Monitor de Tabelas Vencidas</title>
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800&display=swap');
|
||||
|
||||
:root {
|
||||
--rms-pink: #ec008c;
|
||||
--rms-blue: #303952;
|
||||
--rms-cyan: #00bcd4;
|
||||
--bg-primary: #f7f8fa;
|
||||
--card-bg: #ffffff;
|
||||
--card-border: rgba(0, 0, 0, 0.06);
|
||||
--separator: rgba(60, 60, 67, 0.12);
|
||||
--text-primary: #1a1c1e;
|
||||
--text-secondary: #64748b;
|
||||
--accent: var(--rms-pink);
|
||||
--accent-hover: #c90078;
|
||||
--control-bg: rgba(118, 118, 128, 0.12);
|
||||
--switch-off: #e5e5ea;
|
||||
--switch-on: #34c759;
|
||||
--danger: #ff3b30;
|
||||
--font-family: "Onest", -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg-primary: #121827;
|
||||
--card-bg: #1b2433;
|
||||
--card-border: rgba(255, 255, 255, 0.08);
|
||||
--separator: rgba(84, 84, 88, 0.25);
|
||||
--text-primary: #f8fafc;
|
||||
--text-secondary: #a9b8ca;
|
||||
--accent: var(--rms-pink);
|
||||
--accent-hover: #ff4ab0;
|
||||
--control-bg: rgba(118, 118, 128, 0.24);
|
||||
--switch-off: #39393d;
|
||||
--switch-on: #30d158;
|
||||
--danger: #ff453a;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; font-family: var(--font-family); -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent; }
|
||||
|
||||
body {
|
||||
background-color: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: env(safe-area-inset-top) env(safe-area-inset-right) 40px env(safe-area-inset-left);
|
||||
transition: background-color 0.3s ease;
|
||||
}
|
||||
|
||||
header {
|
||||
width: 100%;
|
||||
max-width: 680px;
|
||||
padding: 24px 16px 12px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.title-group h1 { font-size: 24px; font-weight: 800; letter-spacing: -0.5px; }
|
||||
.title-group p { font-size: 13px; color: var(--text-secondary); margin-top: 2px; }
|
||||
|
||||
.header-actions { display: flex; gap: 8px; }
|
||||
|
||||
.btn {
|
||||
appearance: none; border: none; outline: none; cursor: pointer;
|
||||
font-size: 14px; font-weight: 600; border-radius: 999px; padding: 8px 16px;
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
transition: transform 150ms cubic-bezier(0.23, 1, 0.32, 1), background-color 150ms ease;
|
||||
}
|
||||
.btn:active { transform: scale(0.96); }
|
||||
.btn:focus-visible, .segment-btn:focus-visible, input:focus-visible {
|
||||
outline: 3px solid rgba(0, 188, 212, 0.35); outline-offset: 2px;
|
||||
}
|
||||
.btn-primary { background-color: var(--accent); color: #ffffff; }
|
||||
@media (hover: hover) and (pointer: fine) { .btn-primary:hover { background-color: var(--accent-hover); } }
|
||||
.btn-secondary { background-color: var(--control-bg); color: var(--text-primary); }
|
||||
|
||||
.segmented-control {
|
||||
width: 100%; max-width: 680px; background: var(--control-bg); padding: 3px; border-radius: 12px;
|
||||
display: flex; margin: 8px 0 20px; position: sticky; top: 12px; z-index: 20;
|
||||
backdrop-filter: blur(25px); -webkit-backdrop-filter: blur(25px);
|
||||
}
|
||||
.segment-btn { flex: 1; padding: 8px 12px; font-size: 13px; font-weight: 500; text-align: center;
|
||||
cursor: pointer; border-radius: 9px; transition: color 160ms ease, background-color 160ms ease;
|
||||
color: var(--text-secondary); user-select: none; }
|
||||
.segment-btn.active { background: var(--card-bg); color: var(--text-primary); font-weight: 600; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); }
|
||||
|
||||
main { width: 100%; max-width: 680px; padding: 0 16px; }
|
||||
|
||||
.section-title { font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-secondary); margin: 20px 16px 8px; font-weight: 500; }
|
||||
|
||||
.card-group { background: var(--card-bg); border-radius: 16px; border: 1px solid var(--card-border); overflow: hidden; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03); }
|
||||
|
||||
.health-panel {
|
||||
width: 100%; max-width: 680px; margin: 4px 0 8px; padding: 16px;
|
||||
border: 1px solid rgba(0, 188, 212, 0.18); border-radius: 16px;
|
||||
background: linear-gradient(135deg, rgba(48, 57, 82, 0.98), rgba(48, 57, 82, 0.92));
|
||||
color: #fff; box-shadow: 0 4px 16px rgba(48, 57, 82, 0.25);
|
||||
}
|
||||
.health-panel-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.health-panel h2 { margin-top: 3px; font-size: 18px; font-weight: 700; letter-spacing: -0.3px; }
|
||||
.health-panel .eyebrow { color: var(--rms-cyan); font-size: 11px; font-weight: 700; letter-spacing: .08em; }
|
||||
.health-panel .btn-secondary { background: rgba(255,255,255,.12); color: #fff; }
|
||||
.health-summary { margin: 14px 0 10px; color: rgba(255,255,255,.78); font-size: 13px; }
|
||||
.health-components { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
|
||||
.health-item { min-width: 0; padding: 10px; border-radius: 12px; background: rgba(255,255,255,.08); display: grid; grid-template-columns: auto 1fr; gap: 8px; align-items: center; }
|
||||
.health-item strong, .health-item small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.health-item strong { font-size: 12px; }
|
||||
.health-item small { margin-top: 2px; color: rgba(255,255,255,.58); font-size: 10px; }
|
||||
.health-dot { width: 8px; height: 8px; border-radius: 50%; grid-row: span 2; }
|
||||
.health-dot.is-ok { background: var(--rms-cyan); box-shadow: 0 0 8px rgba(0,188,212,.6); }
|
||||
.health-dot.is-bad { background: #ffb4ab; }
|
||||
.health-status { grid-column: 2; font-size: 10px; font-weight: 700; }
|
||||
.health-status.is-ok { color: var(--rms-cyan); }
|
||||
.health-status.is-bad { color: #ffb4ab; }
|
||||
@media (max-width: 560px) { .health-components { grid-template-columns: repeat(2, 1fr); } }
|
||||
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; border-bottom: 0.5px solid var(--separator); gap: 16px; }
|
||||
.setting-row:last-child { border-bottom: none; }
|
||||
.setting-info { flex: 1; min-width: 0; }
|
||||
.setting-label { font-size: 15px; font-weight: 500; color: var(--text-primary); letter-spacing: -0.2px; }
|
||||
.setting-desc { font-size: 12px; color: var(--text-secondary); margin-top: 2px; line-height: 1.35; }
|
||||
.setting-control { display: flex; align-items: center; gap: 8px; }
|
||||
|
||||
.switch { position: relative; display: inline-block; width: 51px; height: 31px; flex-shrink: 0; }
|
||||
.switch input { opacity: 0; width: 0; height: 0; }
|
||||
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--switch-off); transition: background-color 0.25s cubic-bezier(0.2, 0, 0, 1); border-radius: 31px; }
|
||||
.slider:before { position: absolute; content: ""; height: 27px; width: 27px; left: 2px; bottom: 2px; background-color: white; transition: transform 0.25s cubic-bezier(0.2, 0, 0, 1); border-radius: 50%; box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15), 0 1px 1px rgba(0, 0, 0, 0.16); }
|
||||
input:checked + .slider { background-color: var(--switch-on); }
|
||||
input:checked + .slider:before { transform: translateX(20px); }
|
||||
|
||||
.input-field { appearance: none; border: 1px solid var(--separator); background: var(--control-bg); color: var(--text-primary); padding: 8px 12px; border-radius: 10px; font-size: 14px; outline: none; width: 100%; max-width: 260px; transition: border-color 160ms ease, background-color 160ms ease, box-shadow 160ms ease; text-align: right; }
|
||||
.input-field:focus { border-color: var(--accent); background: var(--card-bg); box-shadow: 0 0 0 3px rgba(236, 0, 140, 0.15); }
|
||||
.input-field.secret { font-family: monospace; letter-spacing: 1px; }
|
||||
|
||||
#toast { position: fixed; bottom: 30px; background: rgba(0, 0, 0, 0.85); color: #ffffff; padding: 10px 20px; border-radius: 999px; font-size: 14px; font-weight: 500; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25); transform: translateY(80px) scale(0.9); opacity: 0; pointer-events: none; transition: transform 220ms cubic-bezier(0.23, 1, 0.32, 1), opacity 220ms ease; z-index: 1000; backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px); display: flex; align-items: center; gap: 8px; }
|
||||
@media (prefers-color-scheme: dark) { #toast { background: rgba(255, 255, 255, 0.9); color: #000000; } }
|
||||
#toast.show { transform: translateY(0) scale(1); opacity: 1; }
|
||||
|
||||
#auth-modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.4); backdrop-filter: blur(25px); -webkit-backdrop-filter: blur(25px); display: flex; align-items: center; justify-content: center; padding: 16px; z-index: 2000; opacity: 0; pointer-events: none; transition: opacity 0.25s ease; }
|
||||
#auth-modal.visible { opacity: 1; pointer-events: auto; }
|
||||
.auth-card { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 20px; padding: 28px; width: 100%; max-width: 360px; text-align: center; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); transform: scale(0.95); transition: transform 0.25s cubic-bezier(0.2, 0, 0, 1); }
|
||||
#auth-modal.visible .auth-card { transform: scale(1); }
|
||||
.auth-icon { width: 56px; height: 56px; background: var(--control-bg); border-radius: 16px; display: inline-flex; align-items: center; justify-content: center; font-size: 26px; margin-bottom: 16px; }
|
||||
.auth-card h2 { font-size: 20px; font-weight: 700; letter-spacing: -0.3px; margin-bottom: 6px; }
|
||||
.auth-card p { font-size: 13px; color: var(--text-secondary); margin-bottom: 20px; }
|
||||
.auth-input { width: 100%; padding: 12px 14px; border-radius: 12px; border: 1px solid var(--separator); background: var(--control-bg); color: var(--text-primary); font-size: 15px; outline: none; margin-bottom: 14px; text-align: center; font-family: monospace; letter-spacing: 1px; transition: border-color 160ms ease, background-color 160ms ease; }
|
||||
.auth-input:focus { border-color: var(--accent); background: var(--card-bg); }
|
||||
.auth-input.shake { animation: shake 0.4s cubic-bezier(0.36, 0.07, 0.19, 0.97) both; border-color: var(--danger); }
|
||||
@keyframes shake { 10%, 90% { transform: translate3d(-2px, 0, 0); } 20%, 80% { transform: translate3d(4px, 0, 0); } 30%, 50%, 70% { transform: translate3d(-6px, 0, 0); } 40%, 60% { transform: translate3d(6px, 0, 0); } }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Modal de Autenticação Secret Key -->
|
||||
<div id="auth-modal">
|
||||
<div class="auth-card">
|
||||
<div class="auth-icon">🔐</div>
|
||||
<h2>Painel de Ajustes</h2>
|
||||
<p>Digite a Secret Key da API para autenticar e gerenciar as configurações.</p>
|
||||
<input type="password" id="secret-key-input" class="auth-input" placeholder="API Secret Key" autofocus autocomplete="current-password" />
|
||||
<button id="auth-submit-btn" class="btn btn-primary" style="width: 100%; justify-content: center; padding: 12px;">Entrar</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Header -->
|
||||
<header>
|
||||
<div class="title-group">
|
||||
<h1>Ajustes</h1>
|
||||
<p>Monitor de Tabelas RMS • Hot-Reload Ativo</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button id="save-all-btn" class="btn btn-primary">Salvar</button>
|
||||
<button id="logout-btn" class="btn btn-secondary">Sair</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section id="container-health" class="health-panel" aria-label="Saúde da aplicação">
|
||||
<div class="health-panel-header">
|
||||
<div><span class="eyebrow">OPERAÇÃO</span><h2>Saúde do Monitor</h2></div>
|
||||
<button id="health-refresh" class="btn btn-secondary" type="button">Atualizar</button>
|
||||
</div>
|
||||
<div id="health-summary" class="health-summary" role="status" aria-live="polite">Verificando...</div>
|
||||
<div id="health-components" class="health-components"></div>
|
||||
</section>
|
||||
|
||||
<div class="segmented-control" id="category-tabs">
|
||||
<div class="segment-btn active" data-cat="all">Todas</div>
|
||||
<div class="segment-btn" data-cat="sync">Sync & CMS</div>
|
||||
<div class="segment-btn" data-cat="notifications">Notificações</div>
|
||||
<div class="segment-btn" data-cat="general">Sistema</div>
|
||||
</div>
|
||||
|
||||
<main id="settings-container">
|
||||
<div style="text-align:center; padding: 40px; color: var(--text-secondary);">Carregando configurações...</div>
|
||||
</main>
|
||||
|
||||
<div id="toast"><span>✓</span> Ajustes atualizados com sucesso</div>
|
||||
|
||||
<script>
|
||||
let currentSettings = [];
|
||||
let dirtyValues = {};
|
||||
let activeCategory = 'all';
|
||||
|
||||
const healthLabels = { cms: 'CMS API', db: 'SQLite', scheduler: 'Scheduler', notifier: 'Notificador' };
|
||||
|
||||
// 1. Verificação de Sessão
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/configs/me');
|
||||
const data = await res.json();
|
||||
if (data.authenticated) { hideAuthModal(); loadSettings(); }
|
||||
else { showAuthModal(); }
|
||||
} catch (err) { showAuthModal(); }
|
||||
}
|
||||
|
||||
function showAuthModal() {
|
||||
document.getElementById('auth-modal').classList.add('visible');
|
||||
document.getElementById('secret-key-input').focus();
|
||||
}
|
||||
function hideAuthModal() { document.getElementById('auth-modal').classList.remove('visible'); }
|
||||
|
||||
async function handleLogin() {
|
||||
const input = document.getElementById('secret-key-input');
|
||||
const key = input.value.trim();
|
||||
if (!key) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/configs/auth', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ secretKey: key })
|
||||
});
|
||||
if (res.ok) { hideAuthModal(); input.value = ''; loadSettings(); showToast('Autenticado com sucesso'); }
|
||||
else { input.classList.add('shake'); setTimeout(() => input.classList.remove('shake'), 450); }
|
||||
} catch (err) { input.classList.add('shake'); setTimeout(() => input.classList.remove('shake'), 450); }
|
||||
}
|
||||
document.getElementById('auth-submit-btn').addEventListener('click', handleLogin);
|
||||
document.getElementById('secret-key-input').addEventListener('keydown', (e) => { if (e.key === 'Enter') handleLogin(); });
|
||||
|
||||
document.getElementById('logout-btn').addEventListener('click', async () => {
|
||||
await fetch('/api/v1/configs/logout', { method: 'POST' });
|
||||
showAuthModal();
|
||||
});
|
||||
|
||||
// 2. Carregar Configurações
|
||||
async function loadSettings() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/configs');
|
||||
if (!res.ok) { if (res.status === 401) showAuthModal(); return; }
|
||||
const data = await res.json();
|
||||
currentSettings = data.settings || [];
|
||||
renderSettings(activeCategory);
|
||||
checkHealth();
|
||||
} catch (err) { console.error('Erro ao carregar:', err); }
|
||||
}
|
||||
|
||||
async function checkHealth() {
|
||||
const summary = document.getElementById('health-summary');
|
||||
const list = document.getElementById('health-components');
|
||||
if (!summary || !list) return;
|
||||
try {
|
||||
const res = await fetch('/api/status');
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||
const data = await res.json();
|
||||
const entries = [
|
||||
{ key: 'cms', status: data.cmsReachable ? 'healthy' : 'unhealthy', detail: data.cmsReachable ? 'Conectado' : 'Falha na conexão' },
|
||||
{ key: 'db', status: 'healthy', detail: 'OK' },
|
||||
{ key: 'scheduler', status: data.schedulerRunning ? 'healthy' : 'unhealthy', detail: data.schedulerRunning ? 'Rodando' : 'Parado' },
|
||||
{ key: 'notifier', status: data.notifierReady ? 'healthy' : 'unhealthy', detail: data.notifierReady ? 'Pronto' : 'Config incompleta' },
|
||||
];
|
||||
const healthyCount = entries.filter(e => e.status === 'healthy').length;
|
||||
summary.innerText = healthyCount === 4 ? 'Todos os componentes operacionais.' : 'Alguns componentes com problemas.';
|
||||
list.replaceChildren();
|
||||
entries.forEach(item => {
|
||||
const healthy = item.status === 'healthy';
|
||||
const row = document.createElement('div');
|
||||
row.className = 'health-item';
|
||||
const dot = document.createElement('span');
|
||||
dot.className = 'health-dot ' + (healthy ? 'is-ok' : 'is-bad');
|
||||
const text = document.createElement('div');
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = healthLabels[item.key as keyof typeof healthLabels] || item.key;
|
||||
const detail = document.createElement('small');
|
||||
detail.textContent = item.detail;
|
||||
text.append(name, detail);
|
||||
const state = document.createElement('span');
|
||||
state.className = 'health-status ' + (healthy ? 'is-ok' : 'is-bad');
|
||||
state.textContent = healthy ? 'OK' : 'Atenção';
|
||||
row.append(dot, text, state);
|
||||
list.appendChild(row);
|
||||
});
|
||||
} catch {
|
||||
summary.innerText = 'Não foi possível consultar a saúde.';
|
||||
list.innerHTML = '';
|
||||
}
|
||||
}
|
||||
document.getElementById('health-refresh').addEventListener('click', checkHealth);
|
||||
setInterval(checkHealth, 30000);
|
||||
|
||||
// 3. Renderização
|
||||
function renderSettings(filterCategory = 'all') {
|
||||
activeCategory = filterCategory;
|
||||
const container = document.getElementById('settings-container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const categories = [
|
||||
{ id: 'sync', title: 'Sincronização & CMS' },
|
||||
{ id: 'notifications', title: 'Notificações & Canais' },
|
||||
{ id: 'general', title: 'Sistema & Operação' },
|
||||
];
|
||||
|
||||
categories.forEach(cat => {
|
||||
if (filterCategory !== 'all' && filterCategory !== cat.id) return;
|
||||
const items = currentSettings.filter(s => s.category === cat.id);
|
||||
if (items.length === 0) return;
|
||||
|
||||
const titleEl = document.createElement('div');
|
||||
titleEl.className = 'section-title';
|
||||
titleEl.innerText = cat.title;
|
||||
container.appendChild(titleEl);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card-group';
|
||||
|
||||
items.forEach(item => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'setting-row';
|
||||
const isBool = item.type === 'boolean' || item.value === 'true' || item.value === 'false';
|
||||
let controlHtml = '';
|
||||
if (isBool) {
|
||||
const checked = item.value === 'true' || item.value === '1';
|
||||
controlHtml = '<label class="switch"><input type="checkbox" data-key="' + item.key + '" ' + (checked ? 'checked' : '') + ' onchange="onSwitchChange(this)"><span class="slider"></span></label>';
|
||||
} else {
|
||||
const isSecret = item.isSecret;
|
||||
controlHtml = '<input type="' + (isSecret ? 'password' : 'text') + '" class="input-field ' + (isSecret ? 'secret' : '') + '" data-key="' + item.key + '" value="' + item.value + '" oninput="onInputChange(this)" />';
|
||||
}
|
||||
row.innerHTML = '<div class="setting-info"><div class="setting-label">' + item.label + '</div><div class="setting-desc">' + (item.description || item.key) + '</div></div><div class="setting-control">' + controlHtml + '</div>';
|
||||
card.appendChild(row);
|
||||
});
|
||||
container.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function onSwitchChange(checkbox) { dirtyValues[checkbox.getAttribute('data-key')] = checkbox.checked ? 'true' : 'false'; }
|
||||
function onInputChange(input) { dirtyValues[input.getAttribute('data-key')] = input.value.trim(); }
|
||||
|
||||
// 4. Salvar
|
||||
document.getElementById('save-all-btn').addEventListener('click', async () => {
|
||||
const keys = Object.keys(dirtyValues);
|
||||
if (keys.length === 0) { showToast('Nenhuma alteração pendente'); return; }
|
||||
try {
|
||||
const res = await fetch('/api/v1/configs', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ settings: dirtyValues })
|
||||
});
|
||||
if (res.ok) { showToast('Configurações salvas!'); dirtyValues = {}; loadSettings(); }
|
||||
else { showToast('Erro ao salvar'); }
|
||||
} catch (err) { showToast('Falha na conexão'); }
|
||||
});
|
||||
|
||||
// 5. Abas
|
||||
document.getElementById('category-tabs').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('.segment-btn');
|
||||
if (!btn) return;
|
||||
document.querySelectorAll('.segment-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
renderSettings(btn.getAttribute('data-cat'));
|
||||
});
|
||||
|
||||
function showToast(text) {
|
||||
const toast = document.getElementById('toast');
|
||||
toast.innerHTML = '<span>✓</span> ' + text;
|
||||
toast.classList.add('show');
|
||||
setTimeout(() => toast.classList.remove('show'), 2400);
|
||||
}
|
||||
|
||||
checkAuth();
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -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 = [
|
||||
"⚠️ <b>Tabelas próximas do vencimento (RMS)</b>",
|
||||
"",
|
||||
];
|
||||
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 [
|
||||
`🚨 <b>TABELA ${alert.severity.toUpperCase()}</b>`,
|
||||
`🏢 ${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, "<").replace(/>/g, ">");
|
||||
}
|
||||
}
|
||||
@@ -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<string, number> = {
|
||||
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<CheckResult> {
|
||||
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<TableInfo[]> {
|
||||
const url = `${config.CMS_API_URL}/v1/plano?per_page=200`;
|
||||
const headers: Record<string, string> = {
|
||||
"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<number> {
|
||||
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<TableInfo[]> {
|
||||
return this.tableRepo.getByStatus(status);
|
||||
}
|
||||
|
||||
async getExpirySummary(): Promise<{
|
||||
total: number;
|
||||
byStatus: Record<TableStatus, number>;
|
||||
criticalTables: TableInfo[];
|
||||
}> {
|
||||
const tables = await this.tableRepo.getAll();
|
||||
const byStatus: Record<TableStatus, number> = {
|
||||
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 };
|
||||
@@ -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<number> {
|
||||
// Implementado no TableService
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class CheckTablesUseCase {
|
||||
constructor(private tableService: any) {}
|
||||
|
||||
async execute(): Promise<CheckResult> {
|
||||
return this.tableService.checkAllTables();
|
||||
}
|
||||
}
|
||||
@@ -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<string, string | undefined>) {
|
||||
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;
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "./table.js";
|
||||
|
||||
export interface TableRepository {
|
||||
save(table: TableInfo): Promise<void>;
|
||||
getById(id: string): Promise<TableInfo | null>;
|
||||
getAll(): Promise<TableInfo[]>;
|
||||
getByStatus(status: TableStatus): Promise<TableInfo[]>;
|
||||
getExpiringSoon(days: number): Promise<TableInfo[]>;
|
||||
updateStatus(id: string, status: TableStatus): Promise<void>;
|
||||
markAlertSent(tableId: string, channel: "telegram" | "whatsapp"): Promise<void>;
|
||||
getAlertHistory(tableId: string): Promise<ExpiryAlert[]>;
|
||||
}
|
||||
|
||||
export interface AlertRepository {
|
||||
save(alert: ExpiryAlert): Promise<void>;
|
||||
getUnsentAlerts(): Promise<ExpiryAlert[]>;
|
||||
markAsSent(id: string, channel: "telegram" | "whatsapp"): Promise<void>;
|
||||
getRecentAlerts(limit: number): Promise<ExpiryAlert[]>;
|
||||
}
|
||||
|
||||
export interface CheckResultRepository {
|
||||
save(result: CheckResult): Promise<void>;
|
||||
getLatest(): Promise<CheckResult | null>;
|
||||
getHistory(limit: number): Promise<CheckResult[]>;
|
||||
}
|
||||
@@ -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} <b>TABELA ${severityLabel}</b>`,
|
||||
`🏢 <b>Operadora:</b> ${this.escapeHtml(alert.operadora)}`,
|
||||
`📋 <b>Tabela:</b> ${this.escapeHtml(alert.table_title)}`,
|
||||
`📅 <b>Revisão/Vencimento:</b> ${this.escapeHtml(alert.revision_date)}`,
|
||||
`⏰ <b>Prazo:</b> ${daysText}`,
|
||||
];
|
||||
|
||||
if (alert.administradora) {
|
||||
lines.splice(2, 0, `🏥 <b>Administradora:</b> ${this.escapeHtml(alert.administradora)}`);
|
||||
}
|
||||
|
||||
lines.push(
|
||||
"",
|
||||
`💡 <i>Verifique e atualize a tabela no CMS RMS antes que expire completamente.</i>`
|
||||
);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
formatSummaryAlert(result: { total: number; byStatus: Record<string, number>; criticalCount: number }): string {
|
||||
const lines = [
|
||||
"📊 <b>Relatório de Tabelas RMS</b>",
|
||||
`📦 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, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
}
|
||||
+117
@@ -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);
|
||||
@@ -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<AstraCallsSendResult> {
|
||||
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<string, string> = { "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" };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 || "[]"),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -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<boolean> {
|
||||
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<void> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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 <script>alert(1)</script>",
|
||||
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("<script>");
|
||||
expect(msg).toContain("<script>alert(1)</script>");
|
||||
expect(msg).toContain("Op & Co");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { test, expect, describe, beforeEach, afterEach } from "bun:test";
|
||||
import { TelegramNotifier } from "../../src/infrastructure/telegram/telegram-notifier.ts";
|
||||
|
||||
describe("TelegramNotifier", () => {
|
||||
let notifier: TelegramNotifier;
|
||||
let fetchMock: typeof fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = async (url: string, options: any) => {
|
||||
const body = JSON.parse(options.body);
|
||||
return new Response(JSON.stringify({ ok: true, result: { message_id: 123 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
|
||||
notifier = new TelegramNotifier({
|
||||
botToken: "123456:TEST_TOKEN",
|
||||
chatId: "-1001234567890",
|
||||
fetchFn: fetchMock,
|
||||
delayMs: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test("sendMessage: sucesso", async () => {
|
||||
const result = await notifier.sendMessage("<b>Teste</b> mensagem");
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("sendMessage: sem config retorna false", async () => {
|
||||
const emptyNotifier = new TelegramNotifier({ fetchFn: fetchMock });
|
||||
const result = await emptyNotifier.sendMessage("teste");
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("sendMessage: override chatId", async () => {
|
||||
let capturedChatId: string | null = null;
|
||||
const mockFetch = async (url: string, options: any) => {
|
||||
const body = JSON.parse(options.body);
|
||||
capturedChatId = body.chat_id;
|
||||
return new Response(JSON.stringify({ ok: true, result: { message_id: 123 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
|
||||
const n = new TelegramNotifier({
|
||||
botToken: "123456:TEST",
|
||||
chatId: "-1001111111111",
|
||||
fetchFn: mockFetch,
|
||||
delayMs: 0,
|
||||
});
|
||||
|
||||
await n.sendMessage("teste", "-1009999999999");
|
||||
expect(capturedChatId).toBe("-1009999999999");
|
||||
});
|
||||
|
||||
test("sendMessage: rate limit 429 com retry", async () => {
|
||||
let attempts = 0;
|
||||
const mockFetch = async (url: string, options: any) => {
|
||||
attempts++;
|
||||
if (attempts === 1) {
|
||||
return new Response(JSON.stringify({ ok: false, error_code: 429, parameters: { retry_after: 1 } }), {
|
||||
status: 429,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ ok: true, result: { message_id: 123 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
|
||||
const n = new TelegramNotifier({
|
||||
botToken: "123456:TEST",
|
||||
chatId: "-1001234567890",
|
||||
fetchFn: mockFetch,
|
||||
delayMs: 0,
|
||||
maxRetries: 3,
|
||||
});
|
||||
|
||||
const result = await n.sendMessage("teste rate limit");
|
||||
expect(result).toBe(true);
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
test("sendMessage: falha de rede faz retry", async () => {
|
||||
let attempts = 0;
|
||||
const mockFetch = async () => {
|
||||
attempts++;
|
||||
if (attempts < 3) throw new Error("Network error");
|
||||
return new Response(JSON.stringify({ ok: true, result: { message_id: 123 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
|
||||
const n = new TelegramNotifier({
|
||||
botToken: "123456:TEST",
|
||||
chatId: "-1001234567890",
|
||||
fetchFn: mockFetch,
|
||||
delayMs: 0,
|
||||
maxRetries: 3,
|
||||
});
|
||||
|
||||
const result = await n.sendMessage("teste rede");
|
||||
expect(result).toBe(true);
|
||||
expect(attempts).toBe(3);
|
||||
});
|
||||
|
||||
test("sendMessage: HTML parsing mode", async () => {
|
||||
let capturedBody: any = null;
|
||||
const mockFetch = async (url: string, options: any) => {
|
||||
capturedBody = JSON.parse(options.body);
|
||||
return new Response(JSON.stringify({ ok: true, result: { message_id: 123 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
|
||||
const n = new TelegramNotifier({
|
||||
botToken: "123456:TEST",
|
||||
chatId: "-1001234567890",
|
||||
fetchFn: mockFetch,
|
||||
delayMs: 0,
|
||||
});
|
||||
|
||||
await n.sendMessage("<b>Negrito</b> e <i>itálico</i>");
|
||||
expect(capturedBody.parse_mode).toBe("HTML");
|
||||
expect(capturedBody.disable_web_page_preview).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user