feat: GET /pacientes/examenes — exams registered in last 5 min for a cedula

Queries Firebird RECEPCION+RELACION+EXAMEN for today's date,
filters by HORAINICIORECEPCION >= now-5min in Python, returns
list of {recepcion_id, hora, cod_examen, nombre, cups, precio}.
Auth via X-Lab-Key header (whatsapp_api_key config value).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-09 14:06:22 -05:00
co-authored by Claude Sonnet 4.6
parent e2a9e7c4d3
commit 7d2a9df447
+79
View File
@@ -1,3 +1,5 @@
from datetime import datetime, timedelta
from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import JSONResponse
@@ -33,6 +35,23 @@ WHERE (:fecha_ini IS NULL OR r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin
AND r.NUM_FACTURA > 0
"""
_SQL_EXAMENES_CEDULA = """
SELECT
r.IDRECEPCION,
r.HORAINICIORECEPCION,
TRIM(rel.COD_EXAMEN) AS COD_EXAMEN,
TRIM(ex.NOMBRE) AS NOM_EXAMEN,
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
rel.PRECIO
FROM RECEPCION r
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
JOIN PACIENTE p ON p.CODIGO = r.COD_PACIENTE
WHERE TRIM(p.DOCIDENT) = :cedula
AND r.FECHA_RECEPCION = CURRENT_DATE
ORDER BY r.IDRECEPCION DESC
"""
_SQL_SIN_FILTRO = """
SELECT DISTINCT
p.CODIGO,
@@ -55,6 +74,66 @@ WHERE p.DOCIDENT IS NOT NULL AND p.NOMBRES IS NOT NULL
"""
@router.get("/examenes")
async def examenes_paciente(request: Request, cedula: str = ""):
"""Server-to-server: exámenes registrados hoy (últimos 5 min) para una cédula."""
conn = get_connection()
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
conn.close()
api_key = request.headers.get("X-Lab-Key", "")
if not api_key or api_key != configs.get("whatsapp_api_key", ""):
return JSONResponse({"ok": False, "error": "No autorizado"}, status_code=401)
cedula = cedula.strip()
if not cedula:
return JSONResponse({"ok": False, "error": "cedula requerida"}, status_code=400)
fb, ok, msg = get_firebird_from_config(configs)
if not ok:
return JSONResponse({"ok": False, "error": f"Error Firebird: {msg}"}, status_code=503)
ok_q, err_q, rows = fb.execute_query(_SQL_EXAMENES_CEDULA, {"cedula": cedula})
fb.disconnect()
if not ok_q:
return JSONResponse({"ok": False, "error": f"Error consulta: {err_q}"}, status_code=500)
# Filtrar últimos 5 minutos por HORAINICIORECEPCION
ahora = datetime.now()
limite = ahora - timedelta(minutes=5)
def parse_hora(raw) -> datetime | None:
if not raw:
return None
s = str(raw)
try:
if "T" in s:
dt = datetime.fromisoformat(s)
return ahora.replace(hour=dt.hour, minute=dt.minute, second=dt.second, microsecond=0)
partes = s.split(":")
return ahora.replace(hour=int(partes[0]), minute=int(partes[1]),
second=int(partes[2].split(".")[0]), microsecond=0)
except Exception:
return None
examenes = []
for row in rows:
hora_dt = parse_hora(row.get("HORAINICIORECEPCION"))
if hora_dt and hora_dt < limite:
continue
examenes.append({
"recepcion_id": row.get("IDRECEPCION"),
"hora": row.get("HORAINICIORECEPCION"),
"cod_examen": (row.get("COD_EXAMEN") or "").strip(),
"nombre": (row.get("NOM_EXAMEN") or "").strip(),
"cups": (row.get("CUPS") or "").strip(),
"precio": row.get("PRECIO"),
})
return JSONResponse({"ok": True, "examenes": examenes})
@router.get("")
async def pacientes_page(request: Request, user: dict = Depends(get_current_user)):
conn = get_connection()