feat(pacientes): sync de pacientes Firebird → WhatsApp Lab

- Nuevo servicio whatsapp_sync.py: mapeo de campos RIPS→lab_pacientes
  y cliente HTTP para /api/lab/ingest_paciente.php
- Nueva ruta /pacientes con sync masiva por rango de fechas o todos
- Hook en /terceros/send y /automation/run: sync silencioso a WhatsApp
  después de cada envío a TNS
- Config: campos whatsapp_url y whatsapp_api_key + botón probar conexión

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-09 10:49:00 -05:00
co-authored by Claude Sonnet 4.6
parent b4288ac899
commit e7c6bc794a
9 changed files with 525 additions and 1 deletions
+13
View File
@@ -13,6 +13,7 @@ from app.services.json_generator import (
agrupar_por_recepcion,
)
from app.services.api_client import get_tns_token, TNS_BASE
from app.services.whatsapp_sync import sync_paciente
router = APIRouter(prefix="/automation", tags=["automation"])
@@ -259,6 +260,18 @@ async def run_automation(
_guardar_envio(user["user_id"], "terceros", fecha, tercero_json, msg, ok)
# ── Sync paralelo a WhatsApp Lab (silencioso) ─────────────────────────────
wa_url = configs.get("whatsapp_url", "").rstrip("/")
wa_key = configs.get("whatsapp_api_key", "")
if wa_url and wa_key and rows_pac:
ingest_url = f"{wa_url}/api/lab/ingest_paciente.php"
try:
async with httpx.AsyncClient(timeout=timeout) as wa_client:
for row in rows_pac:
await sync_paciente(row, ingest_url, wa_key, wa_client)
except Exception:
pass
# ── PASO 2: Enviar RDA Paciente ───────────────────────────────────────────
grupos = agrupar_por_recepcion(rows_rda)
endpoint = f"{TNS_BASE}/v2/rda/RdaPaciente/Insertar?codigosucursal={api_sucursal or '00'}"
+2
View File
@@ -27,6 +27,8 @@ DEFAULT_KEYS = [
("especialidad_default", ""),
("remisionante_default", "00"),
("prefijo_tns_default", "00"),
("whatsapp_url", ""),
("whatsapp_api_key", "rips-lab-sync-2026"),
]
+128
View File
@@ -0,0 +1,128 @@
from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import JSONResponse
from app.auth import get_current_user
from app.database import get_connection
from app.services.firebird_service import get_firebird_from_config
from app.services.whatsapp_sync import sync_todos
router = APIRouter(prefix="/pacientes", tags=["pacientes"])
# Trae todos los pacientes distintos en un rango de fechas de recepción.
# Reutiliza la misma query de automation para no duplicar lógica.
_SQL_TODOS = """
SELECT DISTINCT
p.CODIGO,
p.TIPOIDENT,
p.DOCIDENT,
p.NOMBRES,
p.APELLIDOS,
p.DIRECCION,
p.CIUDAD AS COD_CIUDAD,
c.NOMBRE AS NOM_CIUDAD,
p.TELEFONOS,
p.EMAIL,
p.F_NACIMIENTO,
p.SEXO,
p.TIPORES,
p.CODETNIA
FROM PACIENTE p
LEFT JOIN CIUDAD c ON c.CODIGO = p.CIUDAD
LEFT JOIN RECEPCION r ON r.COD_PACIENTE = p.CODIGO
WHERE (:fecha_ini IS NULL OR r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin)
AND r.NUM_FACTURA > 0
"""
_SQL_SIN_FILTRO = """
SELECT DISTINCT
p.CODIGO,
p.TIPOIDENT,
p.DOCIDENT,
p.NOMBRES,
p.APELLIDOS,
p.DIRECCION,
p.CIUDAD AS COD_CIUDAD,
c.NOMBRE AS NOM_CIUDAD,
p.TELEFONOS,
p.EMAIL,
p.F_NACIMIENTO,
p.SEXO,
p.TIPORES,
p.CODETNIA
FROM PACIENTE p
LEFT JOIN CIUDAD c ON c.CODIGO = p.CIUDAD
WHERE p.DOCIDENT IS NOT NULL AND p.NOMBRES IS NOT NULL
"""
@router.get("")
async def pacientes_page(request: Request, user: dict = Depends(get_current_user)):
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", "")
wa_key = configs.get("whatsapp_api_key", "")
return request.app.state.templates.TemplateResponse("pacientes.html", {
"request": request,
"user": user,
"wa_configurado": bool(wa_url and wa_key),
"wa_url": wa_url,
})
@router.post("/sync-all")
async def sync_all(
request: Request,
user: dict = Depends(get_current_user),
fecha_ini: str = Form(""),
fecha_fin: str = Form(""),
todos: str = Form(""),
):
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({
"success": False,
"message": "Configura la URL y API Key de WhatsApp Lab antes de sincronizar.",
})
ingest_url = f"{wa_url}/api/lab/ingest_paciente.php"
fb, ok, msg = get_firebird_from_config(configs)
if not ok:
return JSONResponse({"success": False, "message": f"Error Firebird: {msg}"})
if todos == "1" or (not fecha_ini and not fecha_fin):
ok_q, err_q, rows = fb.execute_query(_SQL_SIN_FILTRO, None)
else:
if not fecha_ini or not fecha_fin:
fb.disconnect()
return JSONResponse({"success": False, "message": "Indica fecha inicio y fecha fin."})
params = {
"fecha_ini": f"{fecha_ini} 00:00:00",
"fecha_fin": f"{fecha_fin} 23:59:59",
}
ok_q, err_q, rows = fb.execute_query(_SQL_TODOS, params)
fb.disconnect()
if not ok_q:
return JSONResponse({"success": False, "message": f"Error al consultar Firebird: {err_q}"})
if not rows:
return JSONResponse({"success": False, "message": "No se encontraron pacientes con esos criterios."})
timeout = int(configs.get("api_timeout", 30))
resultado = await sync_todos(rows, ingest_url, wa_key, timeout)
resultado["success"] = True
resultado["message"] = (
f"{resultado['total']} pacientes procesados — "
f"{resultado['created']} creados, "
f"{resultado['updated']} actualizados, "
f"{resultado['errores']} errores."
)
return JSONResponse(resultado)
+14
View File
@@ -8,6 +8,7 @@ from app.auth import get_current_user
from app.services.firebird_service import get_firebird_from_config
from app.services.json_generator import generar_tercero_api
from app.services.api_client import get_tns_token, TNS_BASE
from app.services.whatsapp_sync import sync_paciente
router = APIRouter(prefix="/terceros", tags=["terceros"])
@@ -183,9 +184,22 @@ async def send_terceros(
conn.commit()
conn.close()
# ── Sync silencioso a WhatsApp Lab ───────────────────────────────────────
wa_url = configs.get("whatsapp_url", "").rstrip("/")
wa_key = configs.get("whatsapp_api_key", "")
wa_sync = None
if wa_url and wa_key and rows:
ingest_url = f"{wa_url}/api/lab/ingest_paciente.php"
try:
wa_result = await sync_paciente(rows[0], ingest_url, wa_key)
wa_sync = {"ok": wa_result["ok"], "action": wa_result["action"]}
except Exception:
wa_sync = {"ok": False, "action": "error"}
return JSONResponse({
"success": resp_ok,
"status_code": resp_code,
"message": "Envío exitoso" if resp_ok else f"Error: {resp_text}",
"cuv": resp_text[:200] if resp_ok else None,
"wa_sync": wa_sync,
})