fix: usar FECHA_RECEPCION en SQL del scheduler en lugar de filtro Python por HORAINICIORECEPCION

El filtro Python era frágil: si HORAINICIORECEPCION era NULL o tenía formato inesperado, los pacientes no se capturaban. Ahora el filtro de ventana de tiempo va directo en Firebird usando DATEADD sobre FECHA_RECEPCION, que siempre está poblado.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-23 11:38:11 -05:00
co-authored by Claude Sonnet 4.6
parent cffeae7e94
commit 78e9c31d90
+8 -11
View File
@@ -1,6 +1,6 @@
"""
Scheduler: sync automático de pacientes con recepción reciente → WhatsApp Lab.
Corre cada minuto y envía solo los pacientes con HORAINICIORECEPCION en los últimos 2 min.
Corre cada minuto y envía los pacientes con FECHA_RECEPCION en los últimos ventana_min minutos.
"""
from datetime import datetime, timedelta
@@ -9,7 +9,8 @@ from app.database import get_connection
from app.services.firebird_service import get_firebird_from_config
from app.services.whatsapp_sync import sync_todos, guardar_sync_log
_SQL_HOY = """
# Filtra directamente en Firebird por FECHA_RECEPCION para no depender de HORAINICIORECEPCION
_SQL_RECIENTES = """
SELECT DISTINCT
p.CODIGO,
p.TIPOIDENT,
@@ -29,7 +30,7 @@ SELECT DISTINCT
FROM PACIENTE p
LEFT JOIN CIUDAD c ON c.CODIGO = p.CIUDAD
JOIN RECEPCION r ON r.COD_PACIENTE = p.CODIGO
WHERE CAST(r.FECHA_RECEPCION AS DATE) = CURRENT_DATE
WHERE r.FECHA_RECEPCION >= DATEADD(MINUTE, ?, CURRENT_TIMESTAMP)
"""
_SQL_EXAMENES_VENTANA = """
@@ -124,23 +125,19 @@ async def sync_recientes(ventana_min: int = 2) -> dict:
if not ok:
return {"ok": False, "error": f"Firebird: {msg}"}
ok_pac, err_pac, rows_pac = fb.execute_query(_SQL_HOY, None)
ok_pac, err_pac, rows_pac = fb.execute_query(_SQL_RECIENTES, (-ventana_min,))
ok_ex, _, rows_ex = fb.execute_query(_SQL_EXAMENES_VENTANA, (-ventana_min,))
fb.disconnect()
if not ok_pac:
return {"ok": False, "error": f"Query pacientes: {err_pac}"}
total_hoy = len(rows_pac) if rows_pac else 0
limite = datetime.now() - timedelta(minutes=ventana_min)
recientes = rows_pac or []
total_hoy = len(recientes)
recientes = [
row for row in (rows_pac or [])
if (h := _parse_hora(row.get("HORAINICIORECEPCION"))) is None or h >= limite
]
if not recientes:
return {"ok": True, "total": 0, "created": 0, "updated": 0,
"skipped": 0, "errores": 0, "total_hoy": total_hoy,
"skipped": 0, "errores": 0, "total_hoy": 0,
"ventana_min": ventana_min, "mensaje": "Sin recepciones en la ventana de tiempo"}
examenes_map: dict[str, list] = {}