fix(automation): parsear respuesta TNS correctamente, tratar 'ya existe' como OK
- _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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
988ac672e9
commit
9bffe4209f
+28
-14
@@ -587,8 +587,12 @@ async def run_automation(
|
|||||||
f"{TNS_BASE}/v2/tablas/Tercero/Crear",
|
f"{TNS_BASE}/v2/tablas/Tercero/Crear",
|
||||||
json=tercero_json, headers=headers,
|
json=tercero_json, headers=headers,
|
||||||
)
|
)
|
||||||
ok = resp.is_success
|
body = resp.json()
|
||||||
msg = resp.json().get("message", "") if ok else resp.text[:200]
|
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:
|
except Exception as e:
|
||||||
ok = False
|
ok = False
|
||||||
msg = str(e)
|
msg = str(e)
|
||||||
@@ -652,11 +656,9 @@ async def run_automation(
|
|||||||
factura = num_override or str(id_recepcion)
|
factura = num_override or str(id_recepcion)
|
||||||
try:
|
try:
|
||||||
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
||||||
ok = resp.is_success
|
ok, msg = _parse_tns_resp(resp)
|
||||||
msg = resp.json().get("message", "") if ok else resp.text[:200]
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
ok = False
|
ok, msg = False, str(e)
|
||||||
msg = str(e)
|
|
||||||
|
|
||||||
if ok:
|
if ok:
|
||||||
resultado["paso2_rda"]["enviados"] += 1
|
resultado["paso2_rda"]["enviados"] += 1
|
||||||
@@ -708,11 +710,9 @@ async def run_automation(
|
|||||||
factura_ps = f"{ps_prefijo}-{ps_numero.zfill(5)}"
|
factura_ps = f"{ps_prefijo}-{ps_numero.zfill(5)}"
|
||||||
try:
|
try:
|
||||||
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
||||||
ok = resp.is_success
|
ok, msg = _parse_tns_resp(resp)
|
||||||
msg = resp.json().get("message", "") if ok else resp.text[:200]
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
ok = False
|
ok, msg = False, str(e)
|
||||||
msg = str(e)
|
|
||||||
|
|
||||||
if ok:
|
if ok:
|
||||||
resultado["paso3_preserv"]["enviados"] += 1
|
resultado["paso3_preserv"]["enviados"] += 1
|
||||||
@@ -752,11 +752,9 @@ async def run_automation(
|
|||||||
contrato_vta = str(grupo_rows[0].get("CODCONTRATO") or "").strip()
|
contrato_vta = str(grupo_rows[0].get("CODCONTRATO") or "").strip()
|
||||||
try:
|
try:
|
||||||
resp = await client.post(endpoint_venta, json=venta_json, headers=headers)
|
resp = await client.post(endpoint_venta, json=venta_json, headers=headers)
|
||||||
ok = resp.is_success
|
ok, msg = _parse_tns_resp(resp)
|
||||||
msg = resp.json().get("message", "") if ok else resp.text[:200]
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
ok = False
|
ok, msg = False, str(e)
|
||||||
msg = str(e)
|
|
||||||
|
|
||||||
if ok:
|
if ok:
|
||||||
resultado["paso4_ventas"]["enviados"] += 1
|
resultado["paso4_ventas"]["enviados"] += 1
|
||||||
@@ -789,6 +787,22 @@ async def run_automation(
|
|||||||
return JSONResponse({"success": True, "resultado": resultado})
|
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,
|
def _guardar_envio(user_id, tipo, factura, json_data, respuesta, ok,
|
||||||
fecha_inicio=None, fecha_fin=None, servicios=0,
|
fecha_inicio=None, fecha_fin=None, servicios=0,
|
||||||
idrecepcion=None, contrato=None, cedula=None):
|
idrecepcion=None, contrato=None, cedula=None):
|
||||||
|
|||||||
@@ -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()
|
|
||||||
Reference in New Issue
Block a user