Files
TableExpirationWatcher/CLAUDE.md
T

132 lines
6.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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
```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.
## 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);'