se agrega integración con SAP HANA, manejo de errores en el demonio y actualización de documentación

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
GeorgeandClaude Sonnet 5 committed 2026-09-02 07:40:26 -05:00
1 parent fcc80d3c6e
commit e6cde62e72
14 files changed
+1711 -237

No files matched your search

+81 -12
View File
@@ -5,6 +5,7 @@ import os
import json
from typing import Optional, Dict, Any
from dotenv import load_dotenv
import hana_manager
# ============================================================================
@@ -13,7 +14,7 @@ from dotenv import load_dotenv
urllib3.disable_warnings()
load_dotenv(dotenv_path=".env.dev")
load_dotenv(dotenv_path=".env")
SAPB1_URL = os.getenv("SAP_B1_URL", "")
SAPB1_USER = os.getenv("SAP_B1_USER", "")
@@ -206,17 +207,85 @@ def get_purchase_invoice(doc_entry: int) -> dict:
# OBTENER GUIA (GET /DeliveryNotes)
# ============================================================================
def get_delivery_notes(tipo: str, serie: str, numero: str) -> list:
filter_str = (
f"Cancelled eq 'tNO'"
f" and U_BPP_MDSD eq '{tipo}'"
f" and U_BPP_MDTD eq '{serie}'"
f" and contains(U_BPP_MDCD,'{numero}')"
)
resp = forward_to_sapb1("GET", "DeliveryNotes", params={"$filter": filter_str})
result = resp.json()
value = result.get("value", [])
print(f" ├── ✅ DeliveryNotes obtenida ({len(value)} registros)")
return value
"""
Obtiene DeliveryNotes de SAP B1.
Fase 1 — Busca DocEntry/DocNum/CardCode/CardName:
- Primero intenta Service Layer con $select.
- Si no hay resultados, fallback a HANA (consulta ODLN con LIKE).
Fase 2 — Por cada DocEntry obtenido, hace GET /DeliveryNotes({DocEntry})
para recuperar el documento completo.
Returns:
list[dict] — Documentos completos de DeliveryNotes, o [] si no se
encontró nada en ninguna fuente.
"""
codigo = f"{serie}{tipo}-{numero}"
# ── Fase 1: Obtener DocEntries ──────────────────────────────────────
entries = _get_delivery_entries(tipo, serie, numero)
if not entries:
print(f" │ ⚠️ Guía {codigo}: sin registros en SAP (SL + HANA)")
return []
# ── Fase 2: Obtener documento completo por cada DocEntry ─────────────
docs = []
for entry in entries:
doc_entry = entry["DocEntry"]
try:
resp = forward_to_sapb1("GET", f"DeliveryNotes({doc_entry})")
doc = resp.json()
docs.append(doc)
print(f" │ └─ DeliveryNote({doc_entry}) obtenido")
except Exception as e:
print(f" │ ⚠️ Error obteniendo DeliveryNote({doc_entry}): {e}")
return docs
def _get_delivery_entries(tipo: str, serie: str, numero: str) -> list:
"""Fase 1: intenta SL, fallback a HANA. Retorna [{DocEntry, DocNum, CardCode, CardName}, ...]."""
codigo = f"{serie}{tipo}-{numero}"
# ── Intentar Service Layer ───────────────────────────────────────────
try:
filter_str = (
f"Cancelled eq 'tNO'"
f" and U_BPP_MDSD eq '{tipo}'"
f" and U_BPP_MDTD eq '{serie}'"
f" and contains(U_BPP_MDCD,'{numero}')"
)
resp = forward_to_sapb1(
"GET", "DeliveryNotes",
params={
"$filter": filter_str,
"$select": "DocEntry,DocNum,CardCode,CardName",
"$top": "10",
},
)
sl_entries = resp.json().get("value", [])
if sl_entries:
print(f" │ 🔍 Guía {codigo}: SL → {len(sl_entries)} DocEntry encontrados")
return sl_entries
print(f" │ 🔍 Guía {codigo}: SL → 0 resultados. Consultando HANA...")
except Exception as e:
print(f" │ ⚠️ Guía {codigo}: SL falló ({e}). Consultando HANA...")
# ── Fallback a HANA ──────────────────────────────────────────────────
try:
hana_entries = hana_manager.get_delivery(tipo, serie, numero)
if hana_entries:
print(f" │ 🔍 Guía {codigo}: HANA → {len(hana_entries)} DocEntry encontrados")
return hana_entries
print(f" │ 🔍 Guía {codigo}: HANA → 0 registros")
except Exception as e:
print(f" │ ⚠️ Guía {codigo}: HANA falló ({e})")
return []
# ============================================================================
# OBTENER ZONAS (GET /U_IDC_ZONAS)