From 9bffe4209f078a6893d6900f9bc863d86a7d23b0 Mon Sep 17 00:00:00 2001 From: Lizandro Guarnizo <77708265+lizandrogd@users.noreply.github.com> Date: Wed, 22 Jul 2026 23:12:32 -0500 Subject: [PATCH] fix(automation): parsear respuesta TNS correctamente, tratar 'ya existe' como OK MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _parse_tns_resp() centraliza parsing: lee status/data.success del body JSON - "ya esta registrado", "ya existe autorización" → ok=True (no bloquea RDA) - Aplica en los 4 pasos; terceros_fallidos solo acumula errores reales - Elimina script tmp buscar_paciente.py Co-Authored-By: Claude Sonnet 4.6 --- app/routes/automation.py | 42 ++++++++++++++++++++++++++-------------- buscar_paciente.py | 20 ------------------- 2 files changed, 28 insertions(+), 34 deletions(-) delete mode 100644 buscar_paciente.py diff --git a/app/routes/automation.py b/app/routes/automation.py index 84ec34b..b734be9 100644 --- a/app/routes/automation.py +++ b/app/routes/automation.py @@ -587,8 +587,12 @@ async def run_automation( f"{TNS_BASE}/v2/tablas/Tercero/Crear", json=tercero_json, headers=headers, ) - ok = resp.is_success - msg = resp.json().get("message", "") if ok else resp.text[:200] + body = resp.json() + ok = bool(body.get("status")) or bool((body.get("data") or {}).get("success")) + msg = body.get("message") or (body.get("data") or {}).get("response") or resp.text[:200] + # "ya registrado" no es error real — el tercero existe en TNS + if not ok and msg and any(s in msg.lower() for s in ("ya esta registrado", "ya existe", "already exist")): + ok = True except Exception as e: ok = False msg = str(e) @@ -652,11 +656,9 @@ async def run_automation( factura = num_override or str(id_recepcion) try: resp = await client.post(endpoint, json=rda_json, headers=headers) - ok = resp.is_success - msg = resp.json().get("message", "") if ok else resp.text[:200] + ok, msg = _parse_tns_resp(resp) except Exception as e: - ok = False - msg = str(e) + ok, msg = False, str(e) if ok: resultado["paso2_rda"]["enviados"] += 1 @@ -708,11 +710,9 @@ async def run_automation( factura_ps = f"{ps_prefijo}-{ps_numero.zfill(5)}" try: resp = await client.post(endpoint, json=rda_json, headers=headers) - ok = resp.is_success - msg = resp.json().get("message", "") if ok else resp.text[:200] + ok, msg = _parse_tns_resp(resp) except Exception as e: - ok = False - msg = str(e) + ok, msg = False, str(e) if ok: resultado["paso3_preserv"]["enviados"] += 1 @@ -752,11 +752,9 @@ async def run_automation( contrato_vta = str(grupo_rows[0].get("CODCONTRATO") or "").strip() try: resp = await client.post(endpoint_venta, json=venta_json, headers=headers) - ok = resp.is_success - msg = resp.json().get("message", "") if ok else resp.text[:200] + ok, msg = _parse_tns_resp(resp) except Exception as e: - ok = False - msg = str(e) + ok, msg = False, str(e) if ok: resultado["paso4_ventas"]["enviados"] += 1 @@ -789,6 +787,22 @@ async def run_automation( return JSONResponse({"success": True, "resultado": resultado}) +_YA_EXISTE = ("ya esta registrado", "ya existe", "already exist", "ya existe una autorización") + +def _parse_tns_resp(resp) -> tuple[bool, str]: + """Parsea respuesta TNS: retorna (ok, msg). Trata 'ya existe' como OK.""" + try: + body = resp.json() + ok = bool(body.get("status")) or bool((body.get("data") or {}).get("success")) + msg = body.get("message") or (body.get("data") or {}).get("response") or resp.text[:200] + except Exception: + ok = resp.is_success + msg = resp.text[:200] + if not ok and msg and any(s in str(msg).lower() for s in _YA_EXISTE): + ok = True + return ok, str(msg or "") + + def _guardar_envio(user_id, tipo, factura, json_data, respuesta, ok, fecha_inicio=None, fecha_fin=None, servicios=0, idrecepcion=None, contrato=None, cedula=None): diff --git a/buscar_paciente.py b/buscar_paciente.py deleted file mode 100644 index 5005d7b..0000000 --- a/buscar_paciente.py +++ /dev/null @@ -1,20 +0,0 @@ -import sqlite3 - -conn = sqlite3.connect("rips_manager.db") -conn.row_factory = sqlite3.Row - -rows = conn.execute(""" - SELECT id, tipo, factura, status, mensaje_tns, respuesta_api, contrato, created_at - FROM envios - WHERE json_enviado LIKE '%88272630%' - ORDER BY created_at DESC - LIMIT 20 -""").fetchall() - -for r in rows: - print(f"--- id={r['id']} tipo={r['tipo']} factura={r['factura']} status={r['status']} fecha={r['created_at']}") - print(f" mensaje_tns: {r['mensaje_tns']}") - print(f" respuesta_api:{r['respuesta_api']}") - print() - -conn.close()