feat: suporte à API v3 do CMS, detecção is_stale/vesting_status, redirect raiz e script de deploy com fallback
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"startedAt": "2026-11-25T12:35:32.702Z",
|
||||
"startedAt": "2026-11-26T00:23:00.409Z",
|
||||
"owned": [
|
||||
"route",
|
||||
"post-edit"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{"version":1,"entries":[
|
||||
{"seq":0,"length":1,"headHash":"sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1","prevAnchorHash":null,"ts":1795565092319,"event":"append","hash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41"},
|
||||
{"seq":1,"length":2,"headHash":"sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d","prevAnchorHash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41","ts":1795610841630,"event":"append","hash":"88c060b098fcbc163f153a2f8f3034eab7d2adf6d6ee60dc7ed23a8227105610"}
|
||||
{"seq":1,"length":2,"headHash":"sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d","prevAnchorHash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41","ts":1795610841630,"event":"append","hash":"88c060b098fcbc163f153a2f8f3034eab7d2adf6d6ee60dc7ed23a8227105610"},
|
||||
{"seq":2,"length":3,"headHash":"sha256:c010a0a6b6a8f4e030de411fc5eaec9bd13330520dd6388c605acf8e9768f46e","prevAnchorHash":"88c060b098fcbc163f153a2f8f3034eab7d2adf6d6ee60dc7ed23a8227105610","ts":1795661300239,"event":"append","hash":"51845eeae1348001e7c4528c9abd4556d9bc2e6cb6beed9ee20bd977f29944db"}
|
||||
]}
|
||||
|
||||
@@ -85,10 +85,50 @@
|
||||
"policyHash": "sha256:00b63b2f746eb8b9095bbd5e1dbae4ddd74fd92a6740b72f59f4069fbfda4737"
|
||||
},
|
||||
"hash": "sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d"
|
||||
},
|
||||
{
|
||||
"payload": {
|
||||
"receiptId": "sha256:0f43689fdf0c0bae5cd652472e565cc42359fdd9a7a583f8eeb262e2a5c22a42",
|
||||
"previousReceiptHash": "sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d",
|
||||
"sequence": 2,
|
||||
"issuedAt": 1795661300228,
|
||||
"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:61f609e946fb1dc3e1fdd58a6e7c6cfed6356891cf89e8ff5a5f43847f2fdb73"
|
||||
},
|
||||
"now": 1795661300228
|
||||
},
|
||||
"requestId": "ae366b5c-cdd0-4505-88f5-9337734e6d94"
|
||||
},
|
||||
"decision": {
|
||||
"requestId": "ae366b5c-cdd0-4505-88f5-9337734e6d94",
|
||||
"outcome": "allowed",
|
||||
"enforcedOutcome": "allowed",
|
||||
"mode": "legacy",
|
||||
"reason": "legacy-default-allow",
|
||||
"matchedRules": [],
|
||||
"obligations": []
|
||||
},
|
||||
"policyHash": "sha256:00b63b2f746eb8b9095bbd5e1dbae4ddd74fd92a6740b72f59f4069fbfda4737"
|
||||
},
|
||||
"hash": "sha256:c010a0a6b6a8f4e030de411fc5eaec9bd13330520dd6388c605acf8e9768f46e"
|
||||
}
|
||||
],
|
||||
"migratedAt": 1795565092281,
|
||||
"migratedFrom": "pre-ADR-324; capabilities=none-detected",
|
||||
"ledgerLength": 2,
|
||||
"ledgerHead": "sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d"
|
||||
"ledgerLength": 3,
|
||||
"ledgerHead": "sha256:c010a0a6b6a8f4e030de411fc5eaec9bd13330520dd6388c605acf8e9768f46e"
|
||||
}
|
||||
|
||||
+2
-1
@@ -6,4 +6,5 @@ coverage
|
||||
*.sqlite
|
||||
*.db
|
||||
data/
|
||||
cookies.txt
|
||||
cookies.txt
|
||||
variaveis.env
|
||||
@@ -8,7 +8,7 @@ This file provides guidance to Claude Code when working with the Table Expiratio
|
||||
|
||||
**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`)
|
||||
**Fonte de dados**: CMS RMS API (`https://cms.rmscorretora.com.br/api/v3/plano`)
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ RUN bun install --production
|
||||
|
||||
# Copy source
|
||||
COPY src ./src
|
||||
COPY tsconfig.json ./
|
||||
|
||||
# Create data directory
|
||||
RUN mkdir -p /data
|
||||
|
||||
@@ -9,7 +9,7 @@ Serviço que monitora as tabelas de planos de saúde no CMS RMS, detecta tabelas
|
||||
│ TABLE EXPIRATION WATCHER │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ CMS API (cms.rmscorretora.com.br) │
|
||||
│ ├── GET /api/v1/plano — lista todas as tabelas │
|
||||
│ ├── GET /api/v3/plano — lista todas as tabelas │
|
||||
│ └── Cada tabela tem: revision_date (Mês/Ano), produtos_json │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ Scheduler (1h padrão) → TableService.checkAllTables() │
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
|
||||
# ==============================================================================
|
||||
# Script de Deploy - Table Expiration Watcher
|
||||
# Commits, push para Gitea e rebuild dos containers no AJAX
|
||||
# Conexão: Rede Local (192.168.15.200) com fallback para Tailscale (100.102.147.7)
|
||||
# ==============================================================================
|
||||
|
||||
# Cores para logs
|
||||
GREEN='\033[0;32m'
|
||||
BLUE='\033[0;34m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m'
|
||||
|
||||
LOCAL_HOST="andrerds@192.168.15.200"
|
||||
TAILSCALE_HOST="andrerds@100.102.147.7"
|
||||
REMOTE_DIR="/home/andrerds/table-expiration-watcher"
|
||||
GITEA_REPO="ssh://git@gitea.rdsnexus.vix.br:22222/Rds/TableExpirationWatcher.git"
|
||||
SSH_OPTS="-o ConnectTimeout=4 -o BatchMode=yes -o StrictHostKeyChecking=accept-new"
|
||||
|
||||
echo -e "${BLUE}=====================================================${NC}"
|
||||
echo -e "${BLUE} 🚀 Table Expiration Watcher - Pipeline de Deploy ${NC}"
|
||||
echo -e "${BLUE}=====================================================${NC}"
|
||||
|
||||
# 1. Validação local (testes)
|
||||
if [[ "$*" != *"--skip-tests"* ]]; then
|
||||
echo -e "\n${YELLOW}🧪 [1/4] Executando testes locais...${NC}"
|
||||
if command -v bun >/dev/null 2>&1; then
|
||||
bun test
|
||||
echo -e "${GREEN}✓ Testes passaram com sucesso!${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}Bun não encontrado localmente, pulando testes.${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e "\n${YELLOW}🧪 [1/4] Flag --skip-tests detectada. Pulando testes.${NC}"
|
||||
fi
|
||||
|
||||
# 2. Git Commit & Push
|
||||
echo -e "\n${YELLOW}📦 [2/4] Verificando alterações no repositório...${NC}"
|
||||
COMMIT_MSG="${1:-}"
|
||||
|
||||
# Remove flag --skip-tests da mensagem se tiver
|
||||
COMMIT_MSG=$(echo "$COMMIT_MSG" | sed 's/--skip-tests//g' | xargs)
|
||||
|
||||
if [ -z "$COMMIT_MSG" ]; then
|
||||
COMMIT_MSG="feat: deploy automático $(date +'%Y-%m-%d %H:%M')"
|
||||
fi
|
||||
|
||||
# Verifica se há alterações para commitar
|
||||
if [ -n "$(git status --porcelain)" ]; then
|
||||
echo -e "${BLUE}Alterações detectadas. Criando commit: \"${COMMIT_MSG}\"${NC}"
|
||||
git add .
|
||||
git commit -m "$COMMIT_MSG"
|
||||
else
|
||||
echo -e "${GREEN}Nenhuma nova alteração pendente para commit.${NC}"
|
||||
fi
|
||||
|
||||
echo -e "${BLUE}Enviando alterações para o Gitea (origin/main)...${NC}"
|
||||
git push origin main || git push -u origin main
|
||||
|
||||
# 3. Resolução do Host SSH (Local vs Tailscale)
|
||||
echo -e "\n${YELLOW}🌐 [3/4] Determinando rota de conexão com o AJAX...${NC}"
|
||||
TARGET_HOST=""
|
||||
|
||||
echo -e "Testando conexão na rede local (${LOCAL_HOST})..."
|
||||
if ssh $SSH_OPTS "$LOCAL_HOST" "echo ok" >/dev/null 2>&1; then
|
||||
TARGET_HOST="$LOCAL_HOST"
|
||||
echo -e "${GREEN}✓ Conectado via REDE LOCAL (${LOCAL_HOST})${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}⚠️ Rede local indisponível. Tentando via TAILSCALE (${TAILSCALE_HOST})...${NC}"
|
||||
if ssh $SSH_OPTS "$TAILSCALE_HOST" "echo ok" >/dev/null 2>&1; then
|
||||
TARGET_HOST="$TAILSCALE_HOST"
|
||||
echo -e "${GREEN}✓ Conectado via TAILSCALE (${TAILSCALE_HOST})${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ Erro: Não foi possível alcançar o AJAX via Rede Local nem via Tailscale.${NC}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# 4. Atualização e Rebuild no AJAX
|
||||
echo -e "\n${YELLOW}🐳 [4/4] Atualizando código e reconstruindo container no AJAX...${NC}"
|
||||
|
||||
ssh $SSH_OPTS "$TARGET_HOST" bash << EOF
|
||||
set -e
|
||||
mkdir -p "$REMOTE_DIR"
|
||||
cd "$REMOTE_DIR"
|
||||
|
||||
# Configura remote origin caso não exista
|
||||
if ! git remote get-url origin >/dev/null 2>&1; then
|
||||
git remote add origin "$GITEA_REPO"
|
||||
else
|
||||
git remote set-url origin "$GITEA_REPO"
|
||||
fi
|
||||
|
||||
echo "📥 Puxando versão mais recente do repositório..."
|
||||
git fetch origin main
|
||||
git reset --hard origin/main
|
||||
|
||||
echo "🔨 Reconstruindo e reiniciando container com Docker Compose..."
|
||||
docker compose up -d --build
|
||||
|
||||
echo "⏳ Aguardando subida do container..."
|
||||
sleep 4
|
||||
|
||||
echo "🩺 Verificando healthcheck interno..."
|
||||
curl -s -f http://127.0.0.1:3002/health || (sleep 2; curl -s http://127.0.0.1:3002/health)
|
||||
EOF
|
||||
|
||||
# 5. Validação Externa (HTTPS Cloudflare)
|
||||
echo -e "\n${YELLOW}🌐 Validando endpoint público HTTPS...${NC}"
|
||||
HTTP_STATUS=\$(curl -s -o /dev/null -w "%{http_code}" https://table-watcher.rdsnexus.com/)
|
||||
if [ "\$HTTP_STATUS" = "302" ] || [ "\$HTTP_STATUS" = "200" ]; then
|
||||
echo -e "${GREEN}✓ Endpoint público HTTPS respondendo OK (HTTP \$HTTP_STATUS): https://table-watcher.rdsnexus.com${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}Aviso: Resposta HTTPS retornou HTTP \$HTTP_STATUS. Verifique o status do Cloudflared.${NC}"
|
||||
fi
|
||||
|
||||
echo -e "\n${GREEN}=====================================================${NC}"
|
||||
echo -e "${GREEN} 🎉 Deploy concluído com sucesso no AJAX! ${NC}"
|
||||
echo -e "${GREEN}=====================================================${NC}"
|
||||
@@ -0,0 +1,41 @@
|
||||
version: "3.8"
|
||||
|
||||
services:
|
||||
table-watcher:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: table-watcher
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:3002:3002"
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- REDIS_URL=redis://localhost:6379
|
||||
- CMS_API_URL=${CMS_API_URL}
|
||||
- CMS_API_KEY=${CMS_API_KEY}
|
||||
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
|
||||
- TELEGRAM_CHAT_ID=${TELEGRAM_CHAT_ID}
|
||||
- ASTRACALLS_MCP_URL=${ASTRACALLS_MCP_URL}
|
||||
- ASTRACALLS_BEARER_TOKEN=${ASTRACALLS_BEARER_TOKEN}
|
||||
- ASTRACALLS_SESSION_PHONE=${ASTRACALLS_SESSION_PHONE}
|
||||
- WHATSAPP_ALERT_TARGETS=${WHATSAPP_ALERT_TARGETS}
|
||||
- POLL_INTERVAL_MS=${POLL_INTERVAL_MS}
|
||||
- TABLE_EXPIRY_WARNING_DAYS=${TABLE_EXPIRY_WARNING_DAYS}
|
||||
- TABLE_EXPIRY_CRITICAL_DAYS=${TABLE_EXPIRY_CRITICAL_DAYS}
|
||||
- API_PORT=3002
|
||||
- API_SECRET_KEY=${API_SECRET_KEY}
|
||||
- SQLITE_PATH=/data/tables.db
|
||||
- LOG_LEVEL=info
|
||||
volumes:
|
||||
- table-watcher-data:/data
|
||||
networks:
|
||||
- table-watcher-network
|
||||
|
||||
networks:
|
||||
table-watcher-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
table-watcher-data:
|
||||
driver: local
|
||||
@@ -10,6 +10,7 @@
|
||||
"test:unit": "bun test tests/unit",
|
||||
"test:integration": "bun test tests/integration",
|
||||
"lint": "tsc --noEmit",
|
||||
"deploy": "./deploy.sh",
|
||||
"db:migrate": "bun run src/cli/migrate.ts",
|
||||
"config:ui": "bun run src/api/app.ts"
|
||||
},
|
||||
|
||||
+103
-56
@@ -1,18 +1,20 @@
|
||||
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 type { TableRepository, AlertRepository, CheckResultRepository, SettingsRepository } 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";
|
||||
import { SqliteSettingsRepository } from "../infrastructure/sqlite/repositories.js";
|
||||
|
||||
export interface AppDependencies {
|
||||
tableRepo: TableRepository;
|
||||
alertRepo: AlertRepository;
|
||||
checkResultRepo: CheckResultRepository;
|
||||
settingsRepo: SettingsRepository;
|
||||
}
|
||||
|
||||
export function createApp(deps: AppDependencies) {
|
||||
@@ -41,7 +43,7 @@ export function createApp(deps: AppDependencies) {
|
||||
: null;
|
||||
|
||||
const whatsappTargets = config.WHATSAPP_ALERT_TARGETS
|
||||
? config.WHATSAPP_ALERT_TARGETS.split(",").map(s => s.trim()).filter(Boolean)
|
||||
? config.WHATSAPP_ALERT_TARGETS.split(",").map((s: string) => s.trim()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
const notificationService = new NotificationService(
|
||||
@@ -66,12 +68,109 @@ export function createApp(deps: AppDependencies) {
|
||||
};
|
||||
|
||||
// === ROTAS PÚBLICAS ===
|
||||
app.get("/", (c) => c.redirect("/configs"));
|
||||
|
||||
app.get("/health", (c) => c.json({
|
||||
status: "healthy",
|
||||
service: "table-expiration-watcher",
|
||||
timestamp: new Date().toISOString(),
|
||||
}));
|
||||
|
||||
// === UI DE CONFIGURAÇÕES (estilo Apple/Planium) ===
|
||||
app.get("/configs", (c) => {
|
||||
return c.html(renderSettingsHtml());
|
||||
});
|
||||
|
||||
// Auth state (cookie simples)
|
||||
const AUTH_COOKIE = "tw_auth";
|
||||
const AUTH_VALUE = "ok";
|
||||
|
||||
// Login
|
||||
app.post("/api/v1/configs/auth", async (c) => {
|
||||
const raw = await c.req.text();
|
||||
console.log("[DEBUG] Raw body:", JSON.stringify(raw));
|
||||
let body: any = {};
|
||||
try {
|
||||
body = JSON.parse(raw);
|
||||
} catch (e) {
|
||||
console.log("[DEBUG] JSON parse error:", e);
|
||||
}
|
||||
console.log("[DEBUG] Parsed body:", JSON.stringify(body));
|
||||
const key = body?.secretKey?.trim();
|
||||
console.log("[DEBUG] Key:", key);
|
||||
console.log("[DEBUG] Config API_SECRET_KEY:", config.API_SECRET_KEY);
|
||||
console.log("[DEBUG] Match:", key === config.API_SECRET_KEY);
|
||||
if (key && key === config.API_SECRET_KEY) {
|
||||
const cookieValue = `${AUTH_COOKIE}=${AUTH_VALUE}; HttpOnly; Path=/; SameSite=Lax; Max-Age=86400`;
|
||||
console.log("[DEBUG] Setting cookie:", cookieValue);
|
||||
c.header("Set-Cookie", cookieValue);
|
||||
return c.json({ authenticated: true });
|
||||
}
|
||||
return c.json({ authenticated: false, error: "Secret Key inválida" }, 401);
|
||||
});
|
||||
|
||||
// Check auth
|
||||
app.get("/api/v1/configs/me", (c) => {
|
||||
const cookie = c.req.header("Cookie") || "";
|
||||
const authed = cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`);
|
||||
return c.json({ authenticated: authed });
|
||||
});
|
||||
|
||||
// Logout
|
||||
app.post("/api/v1/configs/logout", (c) => {
|
||||
c.header("Set-Cookie", `${AUTH_COOKIE}=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0`);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// API de configs para a UI (protegida por cookie)
|
||||
app.get("/api/v1/configs", async (c) => {
|
||||
const cookie = c.req.header("Cookie") || "";
|
||||
if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`)) {
|
||||
return c.json({ authenticated: false }, 401);
|
||||
}
|
||||
// Retorna configs do banco (SQLite) — prioridade UI > .env > default
|
||||
const allSettings = deps.settingsRepo.getAll();
|
||||
const defs = SqliteSettingsRepository.getDefinitions();
|
||||
|
||||
const settings = defs.map(def => {
|
||||
const stored = allSettings.find(s => s.key === def.key);
|
||||
const value = stored ? stored.value : def.defaultValue;
|
||||
return {
|
||||
key: def.key,
|
||||
value: def.isSecret && value ? "*****" : value,
|
||||
category: def.category,
|
||||
label: def.label,
|
||||
type: def.type,
|
||||
isSecret: def.isSecret,
|
||||
description: def.description,
|
||||
};
|
||||
});
|
||||
return c.json({ settings });
|
||||
});
|
||||
|
||||
// PUT /api/v1/configs - Atualizar múltiplas configs
|
||||
app.put("/api/v1/configs", async (c) => {
|
||||
const cookie = c.req.header("Cookie") || "";
|
||||
if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`)) {
|
||||
return c.json({ authenticated: false }, 401);
|
||||
}
|
||||
const body = await c.req.json();
|
||||
const { settings } = body;
|
||||
if (!settings || typeof settings !== "object") {
|
||||
return c.json({ error: "Invalid payload" }, 400);
|
||||
}
|
||||
const results: Record<string, boolean> = {};
|
||||
for (const [key, value] of Object.entries(settings)) {
|
||||
try {
|
||||
deps.settingsRepo.set(key, String(value));
|
||||
results[key] = true;
|
||||
} catch (err) {
|
||||
results[key] = false;
|
||||
}
|
||||
}
|
||||
return c.json({ results });
|
||||
});
|
||||
|
||||
// === ROTAS PROTEGIDAS ===
|
||||
app.use("/api/*", requireAuth);
|
||||
|
||||
@@ -129,7 +228,8 @@ export function createApp(deps: AppDependencies) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return { table, daysUntil, severity: daysUntil < 0 ? "expired" : daysUntil <= 7 ? "critical" : "warning" as const };
|
||||
const severity = (daysUntil < 0 ? "expired" : daysUntil <= 7 ? "critical" : "warning") as "warning" | "critical" | "expired";
|
||||
return { table, daysUntil, severity };
|
||||
});
|
||||
|
||||
const result = await notificationService.notifyExpiringTables(alerts);
|
||||
@@ -149,58 +249,5 @@ export function createApp(deps: AppDependencies) {
|
||||
return c.json({ latest });
|
||||
});
|
||||
|
||||
// === UI DE CONFIGURAÇÕES (estilo Apple/Planium) ===
|
||||
app.get("/configs", (c) => {
|
||||
return c.html(renderSettingsHtml());
|
||||
});
|
||||
|
||||
// Auth state (cookie simples)
|
||||
const AUTH_COOKIE = "tw_auth";
|
||||
const AUTH_VALUE = "ok";
|
||||
|
||||
// Login
|
||||
app.post("/api/v1/configs/auth", async (c) => {
|
||||
const body = await c.req.json();
|
||||
const key = body?.secretKey?.trim();
|
||||
if (key === config.API_SECRET_KEY) {
|
||||
c.header("Set-Cookie", `${AUTH_COOKIE}=${AUTH_VALUE}; HttpOnly; Path=/; SameSite=Lax; Max-Age=86400`);
|
||||
return c.json({ authenticated: true });
|
||||
}
|
||||
return c.json({ authenticated: false, error: "Secret Key inválida" }, 401);
|
||||
});
|
||||
|
||||
// Check auth
|
||||
app.get("/api/v1/configs/me", (c) => {
|
||||
const cookie = c.req.header("Cookie") || "";
|
||||
const authed = cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`);
|
||||
return c.json({ authenticated: authed });
|
||||
});
|
||||
|
||||
// Logout
|
||||
app.post("/api/v1/configs/logout", (c) => {
|
||||
c.header("Set-Cookie", `${AUTH_COOKIE}=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0`);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// API de configs para a UI (protegida por cookie)
|
||||
app.get("/api/v1/configs", async (c) => {
|
||||
const cookie = c.req.header("Cookie") || "";
|
||||
if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`)) {
|
||||
return c.json({ authenticated: false }, 401);
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ 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";
|
||||
import { TableAlertFormatter } from "../../domain/services/table-alert-formatter.js";
|
||||
|
||||
export class NotificationService {
|
||||
constructor(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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 type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../../domain/models/table.js";
|
||||
import type { TableRepository, AlertRepository, CheckResultRepository } from "../../domain/repositories/table-repository.js";
|
||||
import { parseISO, format, differenceInDays, isValid } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
|
||||
@@ -26,6 +26,10 @@ function parseRevisionDate(revisionDate: string | null): Date | null {
|
||||
}
|
||||
|
||||
function calculateTableStatus(table: TableInfo): TableStatus {
|
||||
if (table.is_stale || table.vesting_status === "vencido") {
|
||||
return "vencida";
|
||||
}
|
||||
|
||||
const expiryDate = parseRevisionDate(table.revision_date);
|
||||
if (!expiryDate) return "sem_data";
|
||||
|
||||
@@ -112,7 +116,7 @@ export class TableService {
|
||||
}
|
||||
|
||||
async fetchTablesFromCMS(): Promise<TableInfo[]> {
|
||||
const url = `${config.CMS_API_URL}/v1/plano?per_page=200`;
|
||||
const url = `${config.CMS_API_URL}/v3/plano?per_page=200`;
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
@@ -147,6 +151,8 @@ export class TableService {
|
||||
extracted_at: extractedAt,
|
||||
last_checked: now,
|
||||
edit_url: `${cmsBaseUrl}/admin/tabelas/${item.id}/editar`,
|
||||
is_stale: Boolean(item.is_stale),
|
||||
vesting_status: item.vesting_status || null,
|
||||
};
|
||||
return table;
|
||||
});
|
||||
@@ -187,8 +193,9 @@ export class TableService {
|
||||
const criticalTables: TableInfo[] = [];
|
||||
|
||||
for (const table of tables) {
|
||||
byStatus[table.status]++;
|
||||
if (table.status === "vencida" || table.status === "prestes_a_vencer") {
|
||||
const status = table.status as TableStatus;
|
||||
byStatus[status]++;
|
||||
if (status === "vencida" || status === "prestes_a_vencer") {
|
||||
criticalTables.push(table);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CheckResult } from "../../domain/models/table.js";
|
||||
import type { CheckResultRepository } from "../../domain/repositories/table-repository.js";
|
||||
import { config } from "../../../core/config.js";
|
||||
import { config } from "../../core/config.js";
|
||||
|
||||
export class SyncTablesUseCase {
|
||||
constructor(private tableRepo: any) {} // injetado dinamicamente
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ export function parseConfig(env: Record<string, string | undefined>) {
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
const result = parseConfig(process.env);
|
||||
const result = parseConfig(process.env as Record<string, string | undefined>);
|
||||
if (!result.success) {
|
||||
console.error("❌ Configuração de ambiente inválida:");
|
||||
console.error(result.error.flatten().fieldErrors);
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface TableInfo {
|
||||
extracted_at: string | null; // do _meta.extracted_at
|
||||
last_checked: string; // ISO timestamp
|
||||
edit_url?: string | null; // URL de edição no CMS
|
||||
is_stale?: boolean;
|
||||
vesting_status?: string | null;
|
||||
}
|
||||
|
||||
export interface TableProdutosJson {
|
||||
@@ -66,6 +68,8 @@ export const TableInfoSchema = z.object({
|
||||
status: z.enum(["vigente", "prestes_a_vencer", "vencida", "sem_data", "erro"]),
|
||||
extracted_at: z.string().nullable(),
|
||||
last_checked: z.string().datetime(),
|
||||
is_stale: z.boolean().optional(),
|
||||
vesting_status: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export interface ExpiryAlert {
|
||||
|
||||
@@ -1,25 +1,28 @@
|
||||
import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "./table.js";
|
||||
import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../models/table.js";
|
||||
import type { SettingsRepository } from "../repositories/settings-repository.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[]>;
|
||||
save(table: TableInfo): void;
|
||||
getById(id: string): TableInfo | null;
|
||||
getAll(): TableInfo[];
|
||||
getByStatus(status: TableStatus): TableInfo[];
|
||||
getExpiringSoon(days: number): TableInfo[];
|
||||
updateStatus(id: string, status: TableStatus): void;
|
||||
markAlertSent(tableId: string, channel: "telegram" | "whatsapp"): void;
|
||||
getAlertHistory(tableId: string): 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[]>;
|
||||
save(alert: ExpiryAlert): void;
|
||||
getUnsentAlerts(): ExpiryAlert[];
|
||||
markAsSent(id: string, channel: "telegram" | "whatsapp"): void;
|
||||
getRecentAlerts(limit: number): ExpiryAlert[];
|
||||
}
|
||||
|
||||
export interface CheckResultRepository {
|
||||
save(result: CheckResult): Promise<void>;
|
||||
getLatest(): Promise<CheckResult | null>;
|
||||
getHistory(limit: number): Promise<CheckResult[]>;
|
||||
}
|
||||
save(result: CheckResult): void;
|
||||
getLatest(): CheckResult | null;
|
||||
getHistory(limit: number): CheckResult[];
|
||||
}
|
||||
|
||||
export { SettingsRepository };
|
||||
+8
-7
@@ -1,15 +1,16 @@
|
||||
import { createApp } from "./api/app.js";
|
||||
import { config } from "./core/config.js";
|
||||
import { SqliteTableRepository, SqliteAlertRepository, SqliteCheckResultRepository } from "./infrastructure/sqlite/repositories.js";
|
||||
import { SqliteTableRepository, SqliteAlertRepository, SqliteCheckResultRepository, SqliteSettingsRepository } from "./infrastructure/sqlite/repositories.js";
|
||||
|
||||
const tableRepo = new SqliteTableRepository();
|
||||
const alertRepo = new SqliteAlertRepository();
|
||||
const checkResultRepo = new SqliteCheckResultRepository();
|
||||
const tableRepo = new SqliteTableRepository(config.SQLITE_PATH);
|
||||
const alertRepo = new SqliteAlertRepository(config.SQLITE_PATH);
|
||||
const checkResultRepo = new SqliteCheckResultRepository(config.SQLITE_PATH);
|
||||
const settingsRepo = new SqliteSettingsRepository(config.SQLITE_PATH);
|
||||
|
||||
const app = createApp({ tableRepo, alertRepo, checkResultRepo });
|
||||
const app = createApp({ tableRepo, alertRepo, checkResultRepo, settingsRepo });
|
||||
|
||||
// Scheduler de verificação periódica
|
||||
let checkInterval: Timer | null = null;
|
||||
let checkInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function startScheduler() {
|
||||
if (checkInterval) return;
|
||||
@@ -37,7 +38,7 @@ function startScheduler() {
|
||||
: null;
|
||||
|
||||
const whatsappTargets = config.WHATSAPP_ALERT_TARGETS
|
||||
? config.WHATSAPP_ALERT_TARGETS.split(",").map(s => s.trim()).filter(Boolean)
|
||||
? config.WHATSAPP_ALERT_TARGETS.split(",").map((s: string) => s.trim()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
const notificationService = new NotificationService(
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { TableRepository, AlertRepository, CheckResultRepository } from "../../domain/repositories/table-repository.js";
|
||||
import type { TableRepository, AlertRepository, CheckResultRepository, SettingsRepository } from "../../domain/repositories/table-repository.js";
|
||||
import type { TableInfo, TableStatus, ExpiryAlert, CheckResult } from "../../domain/models/table.js";
|
||||
import type { SettingValue, SettingDefinition } from "../../domain/models/setting.js";
|
||||
import { Database } from "bun:sqlite";
|
||||
import path from "path";
|
||||
|
||||
export class SqliteTableRepository implements TableRepository {
|
||||
private db: Database.Database;
|
||||
private db: Database;
|
||||
|
||||
constructor(dbPath: string = "./data/tables.db") {
|
||||
// Garante que o diretório existe
|
||||
@@ -32,6 +33,8 @@ export class SqliteTableRepository implements TableRepository {
|
||||
status TEXT NOT NULL DEFAULT 'sem_data',
|
||||
extracted_at TEXT,
|
||||
last_checked TEXT NOT NULL,
|
||||
is_stale INTEGER NOT NULL DEFAULT 0,
|
||||
vesting_status TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
@@ -39,7 +42,16 @@ export class SqliteTableRepository implements TableRepository {
|
||||
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);
|
||||
`);
|
||||
|
||||
try {
|
||||
this.db.exec("ALTER TABLE tables ADD COLUMN is_stale INTEGER NOT NULL DEFAULT 0;");
|
||||
} catch {}
|
||||
try {
|
||||
this.db.exec("ALTER TABLE tables ADD COLUMN vesting_status TEXT;");
|
||||
} catch {}
|
||||
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS alerts (
|
||||
id TEXT PRIMARY KEY,
|
||||
table_id TEXT NOT NULL,
|
||||
@@ -78,8 +90,8 @@ export class SqliteTableRepository implements TableRepository {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO tables (
|
||||
id, title, operadora, administradora, revision_date, download_pdf,
|
||||
vigencia, produtos_json, status, extracted_at, last_checked, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
vigencia, produtos_json, status, extracted_at, last_checked, is_stale, vesting_status, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`);
|
||||
stmt.run(
|
||||
table.id,
|
||||
@@ -92,7 +104,9 @@ export class SqliteTableRepository implements TableRepository {
|
||||
table.produtos_json ? JSON.stringify(table.produtos_json) : null,
|
||||
table.status,
|
||||
table.extracted_at,
|
||||
table.last_checked
|
||||
table.last_checked,
|
||||
table.is_stale ? 1 : 0,
|
||||
table.vesting_status || null
|
||||
);
|
||||
}
|
||||
|
||||
@@ -154,6 +168,8 @@ export class SqliteTableRepository implements TableRepository {
|
||||
status: row.status,
|
||||
extracted_at: row.extracted_at,
|
||||
last_checked: row.last_checked,
|
||||
is_stale: Boolean(row.is_stale),
|
||||
vesting_status: row.vesting_status || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -173,7 +189,7 @@ export class SqliteTableRepository implements TableRepository {
|
||||
}
|
||||
|
||||
export class SqliteAlertRepository implements AlertRepository {
|
||||
private db: Database.Database;
|
||||
private db: Database;
|
||||
|
||||
constructor(dbPath: string = "./data/tables.db") {
|
||||
this.db = new Database(dbPath);
|
||||
@@ -233,8 +249,70 @@ export class SqliteAlertRepository implements AlertRepository {
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_SETTING_DEFINITIONS: SettingDefinition[] = [
|
||||
// Sync & CMS
|
||||
{ key: "POLL_INTERVAL_MS", label: "Intervalo de Verificação (ms)", description: "Frequência de sincronização e verificação automática", category: "sync", type: "number", defaultValue: "3600000" },
|
||||
{ key: "TABLE_EXPIRY_WARNING_DAYS", label: "Aviso Antecipado (dias)", description: "Dias antes do vencimento para emitir aviso (warning)", category: "sync", type: "number", defaultValue: "30" },
|
||||
{ key: "TABLE_EXPIRY_CRITICAL_DAYS", label: "Aviso Crítico (dias)", description: "Dias antes do vencimento para emitir aviso crítico", category: "sync", type: "number", defaultValue: "7" },
|
||||
{ key: "CMS_API_URL", label: "URL da API CMS", description: "Endpoint base da API CMS RMS", category: "sync", type: "string", defaultValue: "https://cms.rmscorretora.com.br/api" },
|
||||
|
||||
// Notificações
|
||||
{ key: "TELEGRAM_BOT_TOKEN", label: "Token Bot Telegram", description: "Token do bot Telegram para alertas", category: "notifications", type: "string", isSecret: true, defaultValue: "" },
|
||||
{ key: "TELEGRAM_CHAT_ID", label: "Chat ID Telegram", description: "Chat/grupo onde enviar alertas", category: "notifications", type: "string", defaultValue: "" },
|
||||
{ key: "WHATSAPP_ALERT_TARGETS", label: "Destinos WhatsApp", description: "Telefones/grupos separados por vírgula para alertas WhatsApp", category: "notifications", type: "string", defaultValue: "5527988037765" },
|
||||
|
||||
// Sistema
|
||||
{ key: "API_PORT", label: "Porta da API", description: "Porta onde o servidor HTTP escuta", category: "general", type: "number", defaultValue: "3002" },
|
||||
{ key: "SQLITE_PATH", label: "Caminho do SQLite", description: "Arquivo de banco de dados local", category: "general", type: "string", defaultValue: "./data/tables.db" },
|
||||
];
|
||||
|
||||
export class SqliteSettingsRepository implements SettingsRepository {
|
||||
private db: Database;
|
||||
|
||||
constructor(dbPath: string = "./data/tables.db") {
|
||||
this.db = new Database(dbPath);
|
||||
this.initSchema();
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
`);
|
||||
|
||||
// Insere defaults se não existirem
|
||||
for (const def of DEFAULT_SETTING_DEFINITIONS) {
|
||||
const exists = this.db.prepare("SELECT 1 FROM settings WHERE key = ?").get(def.key);
|
||||
if (!exists) {
|
||||
this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?)").run(def.key, def.defaultValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get(key: string): SettingValue | null {
|
||||
const row = this.db.prepare("SELECT * FROM settings WHERE key = ?").get(key) as any;
|
||||
return row ? { key: row.key, value: row.value, updated_at: row.updated_at } : null;
|
||||
}
|
||||
|
||||
getAll(): SettingValue[] {
|
||||
const rows = this.db.prepare("SELECT * FROM settings ORDER BY key").all() as any[];
|
||||
return rows.map(r => ({ key: r.key, value: r.value, updated_at: r.updated_at }));
|
||||
}
|
||||
|
||||
set(key: string, value: string): void {
|
||||
this.db.prepare("INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?, ?, datetime('now'))").run(key, value);
|
||||
}
|
||||
|
||||
static getDefinitions(): SettingDefinition[] {
|
||||
return DEFAULT_SETTING_DEFINITIONS;
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteCheckResultRepository implements CheckResultRepository {
|
||||
private db: Database.Database;
|
||||
private db: Database;
|
||||
|
||||
constructor(dbPath: string = "./data/tables.db") {
|
||||
this.db = new Database(dbPath);
|
||||
|
||||
@@ -89,6 +89,18 @@ describe("Table Status Calculation", () => {
|
||||
const status = calculateTableStatus(table);
|
||||
expect(status).toBe("sem_data");
|
||||
});
|
||||
|
||||
test("calculateTableStatus: vencida por is_stale true", () => {
|
||||
const table = { revision_date: "Outubro/2027", is_stale: true } as any;
|
||||
const status = calculateTableStatus(table);
|
||||
expect(status).toBe("vencida");
|
||||
});
|
||||
|
||||
test("calculateTableStatus: vencida por vesting_status vencido", () => {
|
||||
const table = { revision_date: "Outubro/2027", vesting_status: "vencido" } as any;
|
||||
const status = calculateTableStatus(table);
|
||||
expect(status).toBe("vencida");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Severity Calculation", () => {
|
||||
|
||||
Reference in New Issue
Block a user