Fix JSON generation: numero factura, forma pago, tipousuario, hora format

- numero: usar NUM_FACTURA en lugar de cadena vacía
- codFormaPago: CLIP (particular) / INST (EPS) según TNS real
- tipousuario: fallback desde TIPOUSU cuando TIPOUSUSISPRO es NULL
- fechaHoraEgreso: última FECHA_REPORTADO en lugar de FECHA_RECEPCION
- _fmt_datetime: eliminar espacios en tiempo ("06: 08: 29" → "06:08:29")
- especialidad: limpiar valores basura (., -, 0, 00)
- telefono: fallback "0000000" cuando vacío (campo requerido TNS)
- profesional: COALESCE(USUARIO, MEDICO.CODIGO) en queries SQL

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-06-25 20:48:22 -05:00
co-authored by Claude Sonnet 4.6
parent f5cd5a233f
commit 0ec4ae3e66
5 changed files with 341 additions and 14 deletions
+34 -11
View File
@@ -22,7 +22,9 @@ def _fmt_datetime(val) -> str:
return ""
if hasattr(val, "strftime"):
return val.strftime("%d/%m/%Y %H:%M:%S")
# Eliminar espacios dentro de la parte de hora ("06: 08: 29" → "06:08:29")
s = str(val)[:19].replace("T", " ")
s = s.replace(": ", ":").replace(" :", ":")
parts = s.split(" ")
if len(parts) == 2:
dp = parts[0].split("-")
@@ -67,7 +69,7 @@ def generar_tercero_api(row: dict) -> dict:
"zona1": "00",
"clasificacion": "00",
"nomRegTri": nombre_completo,
"telefono": str(row.get("TELEFONOS") or "").strip(),
"telefono": str(row.get("TELEFONOS") or "").strip() or "0000000",
"email": (row.get("EMAIL") or "").strip() or f"{str(row.get('DOCIDENT') or 'paciente').strip()}@sinregistro.co",
"inactivo": False,
"privada": "N",
@@ -101,7 +103,12 @@ def generar_rda_paciente(rows: list) -> dict:
fecha = _fmt_fecha(h.get("FECHA_RECEPCION"))
ingreso = _fmt_datetime(h.get("HORAINICIORECEPCION") or h.get("FECHA_RECEPCION"))
egreso = _fmt_datetime(h.get("FECHA_RECEPCION"))
# Egreso = última fecha de reporte válida entre los exámenes, o fecha de recepción
ultima_fecha = max(
(r.get("FECHA_REPORTADO") for r in rows if str(r.get("FECHA_REPORTADO") or "")[:4] != "1900"),
default=None,
)
egreso = _fmt_datetime(ultima_fecha or h.get("FECHA_RECEPCION"))
detalle_pedido = []
for row in rows:
@@ -120,37 +127,53 @@ def generar_rda_paciente(rows: list) -> dict:
"impConsumo": 0,
"observacion": "",
"profesional": str(h.get("profesional") or "").strip(),
"especialidad": str(row.get("COD_ESPECIALIDAD") or "").strip(),
"especialidad": (lambda e: e if e not in (".", "-", "0", "00") else "")(str(row.get("COD_ESPECIALIDAD") or "").strip()),
"diagnosticoprincipal": str(h.get("DIAG_PPAL") or "").strip(),
"fechaHoraRealizacion": fecha_real or egreso,
})
autorizacion = str(h.get("AUTORIZACION") or "").strip() or None
nit_empresa = str(h.get("NIT_EMPRESA") or "").strip()
es_particular = nit_empresa.upper() in ("PART", "PARTICULAR", "", "0")
# Códigos configurados en TNS para este laboratorio (GET /v2/tablas/FormaPago/ObtenerFormasDePago)
cod_forma_pago = "CLIP" if es_particular else "INST"
# tipousuario: usar TIPOUSUSISPRO; si es NULL derivar de TIPOUSU + NIT_EMPRESA
_TIPOUSU_MAP = {"1": "11", "5": "07"} # EPS→11, Póliza→07
tipoususispro = str(h.get("TIPOUSUSISPRO") or "").strip()
if not tipoususispro:
tipousu = str(h.get("TIPOUSU") or "").strip()
tipoususispro = _TIPOUSU_MAP.get(tipousu, "12" if es_particular else "11")
# viaIngreso y modalidadAtencion no existen en RECEPCION → valores fijos de laboratorio
via_ingreso = "01" # Demanda espontánea (pacientes llegan directo al lab)
modalidad = "01" # Intramural (laboratorio en sede fija)
return {
"codigoPrefijo": str(h.get("PREFIJO") or "00").strip(),
"numero": "",
"numero": str(h.get("NUM_FACTURA") or "").strip(),
"fecha": fecha,
"codTercero": str(h.get("COD_PACIENTE") or "").strip(),
"codVendedor": "00",
"codFormaPago": "CO",
"codFormaPago": cod_forma_pago,
"codBanco": "00",
"codigoCentroCosto": "00",
"tipoIngreso": str(h.get("CLASEPROC") or "1").strip() or "1",
"fechaHoraIngreso": ingreso,
"fechaHoraEgreso": egreso,
"modalidadAtencion": "01",
"numeroContrato": str(h.get("NIT_EMPRESA") or "").strip(),
"modalidadAtencion": modalidad,
"numeroContrato": nit_empresa,
"diagnosticoprincipal": str(h.get("DIAG_PPAL") or "").strip(),
"tipousuario": str(h.get("TIPOUSUSISPRO") or "12").strip(),
"viaIngreso": "01",
"tipousuario": tipoususispro,
"viaIngreso": via_ingreso,
"esTerapia": False,
"esProcedimiento": False,
"numeroAutorizacion": autorizacion,
"detallePedido": detalle_pedido,
"detalleFormaPago": [{
"codigoFormaPago": "CO",
"plazoDias": "0",
"codigoFormaPago": cod_forma_pago,
"plazoDias": "0" if es_particular else "30",
"fechaVencimiento": fecha,
"valor": str(int(float(h.get("VALORTOTAL") or 0))),
}],