From c58ecc17575af664482488c6c268ec39038bf120 Mon Sep 17 00:00:00 2001 From: Lizandro Guarnizo <77708265+lizandrogd@users.noreply.github.com> Date: Tue, 28 Jul 2026 15:05:09 -0500 Subject: [PATCH] fix: defensive grouping filter in preview and run ventas endpoints Replace dict comprehension with explicit loop so that non-list or empty grupo values are safely skipped, preventing KeyError: 0 on v[0]. Co-Authored-By: Claude Sonnet 4.6 --- app/routes/automation.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/app/routes/automation.py b/app/routes/automation.py index 412b435..72da592 100644 --- a/app/routes/automation.py +++ b/app/routes/automation.py @@ -455,9 +455,15 @@ async def preview_automation( ] grupos_vta_all = agrupar_por_factura(rows_vta) - grupos_vta = {k: v for k, v in grupos_vta_all.items() - if str(v[0].get("CODCONTRATO") or "").strip() not in excluded_ventas - and int(v[0].get("NUM_FACTURA") or 0) != 0} + grupos_vta = {} + for k, v in grupos_vta_all.items(): + if not isinstance(v, list) or not v: + continue + if int(v[0].get("NUM_FACTURA") or 0) == 0: + continue + if str(v[0].get("CODCONTRATO") or "").strip() in excluded_ventas: + continue + grupos_vta[k] = v ventas_preview = [] for num_fac_key, grupo_rows in grupos_vta.items(): @@ -734,9 +740,15 @@ async def run_automation( # ── PASO 4: Enviar Facturas Venta ───────────────────────────────────────── excluded_ventas = load_excluded_ventas_set() grupos_vta_all = agrupar_por_factura(rows_vta) - grupos_vta = {k: v for k, v in grupos_vta_all.items() - if str(v[0].get("CODCONTRATO") or "").strip() not in excluded_ventas - and int(v[0].get("NUM_FACTURA") or 0) != 0} + grupos_vta = {} + for k, v in grupos_vta_all.items(): + if not isinstance(v, list) or not v: + continue + if int(v[0].get("NUM_FACTURA") or 0) == 0: + continue + if str(v[0].get("CODCONTRATO") or "").strip() in excluded_ventas: + continue + grupos_vta[k] = v resultado["paso4_ventas"]["excluidos"] = len(grupos_vta_all) - len(grupos_vta) endpoint_venta = f"{TNS_BASE}/v2/facturacion/Ventas/Crear?codigosucursal={api_sucursal or '00'}"