feat: add CIE-10 sync endpoint and migration button in ERP tab
- POST /envios/erp/sync-diagnosticos: reads all 12422 diagnosticos from Firebird, sends to WhatsApp in batches of 500 via ingest_diagnosticos.php - envios_erp.html: new "Migración CIE-10" card with Migrar button and result Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
b65fdf0d9c
commit
9a7e4e219b
+63
-2
@@ -1,8 +1,12 @@
|
||||
import httpx
|
||||
import traceback as tb
|
||||
|
||||
from fastapi import APIRouter, Request, Depends, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.auth import get_current_user
|
||||
from app.database import get_connection
|
||||
from app.services.scheduler import sync_recientes
|
||||
from app.services.firebird_service import get_firebird_from_config
|
||||
|
||||
router = APIRouter(prefix="/envios", tags=["envios"])
|
||||
|
||||
@@ -33,9 +37,66 @@ async def erp_sync_now(
|
||||
ventana_min: int = Query(default=30, ge=1, le=1440),
|
||||
user: dict = Depends(get_current_user),
|
||||
):
|
||||
import traceback as tb
|
||||
try:
|
||||
resultado = await sync_recientes(ventana_min=ventana_min)
|
||||
return JSONResponse(resultado)
|
||||
except Exception as e:
|
||||
return JSONResponse({"ok": False, "error": str(e), "traceback": tb.format_exc()}, status_code=200)
|
||||
return JSONResponse({"ok": False, "error": str(e), "traceback": tb.format_exc()})
|
||||
|
||||
|
||||
@router.post("/erp/sync-diagnosticos")
|
||||
async def erp_sync_diagnosticos(user: dict = Depends(get_current_user)):
|
||||
"""Migra los 12.422 diagnósticos CIE-10 de Firebird → WhatsApp en lotes de 500."""
|
||||
try:
|
||||
conn = get_connection()
|
||||
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
||||
conn.close()
|
||||
|
||||
wa_url = configs.get("whatsapp_url", "").rstrip("/")
|
||||
wa_key = configs.get("whatsapp_api_key", "")
|
||||
if not wa_url or not wa_key:
|
||||
return JSONResponse({"ok": False, "error": "whatsapp_url o whatsapp_api_key no configurados"})
|
||||
|
||||
fb, ok, msg = get_firebird_from_config(configs)
|
||||
if not ok:
|
||||
return JSONResponse({"ok": False, "error": f"Firebird: {msg}"})
|
||||
|
||||
ok_r, err_r, rows = fb.execute_query(
|
||||
"SELECT TRIM(d.COD_DIAG) AS COD_DIAG, TRIM(d.CONCEPTO) AS CONCEPTO "
|
||||
"FROM DIAGNOSTICO d ORDER BY d.COD_DIAG", None
|
||||
)
|
||||
fb.disconnect()
|
||||
|
||||
if not ok_r:
|
||||
return JSONResponse({"ok": False, "error": f"Query Firebird: {err_r}"})
|
||||
|
||||
diagnosticos = [{"cod": r["COD_DIAG"], "concepto": r["CONCEPTO"]} for r in (rows or [])]
|
||||
total = len(diagnosticos)
|
||||
batch_size = 500
|
||||
url = f"{wa_url}/api/lab/ingest_diagnosticos.php"
|
||||
headers = {"Content-Type": "application/json", "X-Lab-Key": wa_key}
|
||||
|
||||
insertados = 0
|
||||
errores = []
|
||||
async with httpx.AsyncClient(timeout=60) as client:
|
||||
for i in range(0, total, batch_size):
|
||||
lote = diagnosticos[i:i + batch_size]
|
||||
try:
|
||||
resp = await client.post(url, json={"rows": lote}, headers=headers)
|
||||
data = resp.json()
|
||||
if data.get("ok"):
|
||||
insertados += data.get("insertados", len(lote))
|
||||
else:
|
||||
errores.append(f"Lote {i}-{i+len(lote)}: {data.get('error', '?')}")
|
||||
except Exception as ex:
|
||||
errores.append(f"Lote {i}-{i+len(lote)}: {ex}")
|
||||
|
||||
return JSONResponse({
|
||||
"ok": len(errores) == 0,
|
||||
"total": total,
|
||||
"insertados": insertados,
|
||||
"lotes": (total + batch_size - 1) // batch_size,
|
||||
"errores": errores,
|
||||
})
|
||||
except Exception as e:
|
||||
return JSONResponse({"ok": False, "error": str(e), "traceback": tb.format_exc()})
|
||||
|
||||
Reference in New Issue
Block a user