6.0 KiB
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/v3/plano)
Commands
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
.jsextensions:"type": "module"in package.json. Always import with.jsextension. - Config via Zod (
src/core/config.ts): all env vars validated at boot; invalid env →process.exit(1). - Settings UI Mandate (
/configs): Every viable.envconfig MUST be exposed in the Apple Design UI viaDEFAULT_SETTING_DEFINITIONSpattern (copied from Planium). Precedence:SQLite (UI) > .env > defaultValue. Secrets withisSecret: true. - SQLite as local state: tables, alerts, check history persisted locally. No external DB required.
- Scheduler:
setIntervalnative, runsTableService.checkAllTables()everyPOLL_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-keyheader orAuthorization: Bearerfor API; UI uses cookie session + Secret Key login.
Copied from Planium Automation (/Users/andrerds/AutomationDATAPlanuin/)
This project reuses patterns from Planium:
TelegramNotifierclass (retry, pacing, rate-limit handling)AstraCallsClient(MCP JSON-RPC, phone sanitization)DynamicConfigServicepattern → 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)
{
"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
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_datevem como "Mês/Ano" (pt-BR). Parser emtable-service.tsusaMONTH_MAP.- Data de expiração = último dia do mês da
revision_date. produtos_jsonpode ser null → trata comosem_data.- AstraCalls MCP usa JSON-RPC 2.0 (
tools/call+send_text). - UI
/configsé servida como HTML string (sem build step). Modifiquesettings-page.tspara mudanças visuais. - SQLite path default
./data/tables.db— volume persistente no Docker.
Get tabelas .env. CMS_API_KEY
curl -s -H "Authorization: Bearer $CMS_API_KEY" "https://cms.rmscorretora.com.br/api/v3/plano?per_page=200" | bun -e 'const input = JSON.parse(await Bun.stdin.text()); const statuses = {}; for (const p of input.data) statuses[p.status] = (statuses[p.status] || 0) + 1; console.log("Statuses:", statuses); console.log("Total:", input.data.length);'