se migran los print de los módulos a logging con nivel explícito
pipeline_utils.log pasa a usar logging (parámetro severity) y los print de pipeline, sapb1_manager, hana_manager, outlook_utilities, email_utilities y main pasan a logger.info/warning/error, de modo que LOG_LEVEL filtre por severidad. El texto del log no cambia. Se mantienen los print de CLI en sunat_schema (__main__), tools/ y tests/. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
80493eaa94
commit
79378a70e1
11 files changed
+109
-79
No files matched your search
+17
-14
@@ -8,6 +8,7 @@ Cada correo se procesa individualmente en un bucle:
|
||||
→ crear draft en SAP (si válido) → notificar → guardar draft JSON
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
@@ -22,21 +23,23 @@ import notificaciones
|
||||
import sapb1_manager
|
||||
from pipeline_utils import log
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# PASO 1: Autenticación Microsoft Graph
|
||||
# ============================================================================
|
||||
def step_authenticate() -> str | None:
|
||||
try:
|
||||
print("Intentando obtener token de acceso...")
|
||||
logger.info("Intentando obtener token de acceso...")
|
||||
token = outlook_utilities.get_access_token()
|
||||
if token:
|
||||
print("✅ Token obtenido exitosamente.")
|
||||
print(f"Token prefix: {token[:25]}...")
|
||||
logger.info("✅ Token obtenido exitosamente.")
|
||||
logger.info(f"Token prefix: {token[:25]}...")
|
||||
return token
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
logger.error(f"❌ Error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
@@ -44,14 +47,14 @@ def step_authenticate() -> str | None:
|
||||
# PASO 2: Descarga de correos
|
||||
# ============================================================================
|
||||
def step_fetch_emails(token: str, email: str, fecha_inicio: str, fecha_fin: str) -> list[dict]:
|
||||
print("\n" + "=" * 60)
|
||||
print(f"[MAIL] {email}")
|
||||
logger.info("=" * 60)
|
||||
logger.info(f"[MAIL] {email}")
|
||||
try:
|
||||
emails = outlook_utilities.get_emails(email, token, fecha_inicio, fecha_fin)
|
||||
print(f"Se encontraron {len(emails)} correos.")
|
||||
logger.info(f"Se encontraron {len(emails)} correos.")
|
||||
return emails
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
logger.error(f"❌ Error: {e}")
|
||||
return []
|
||||
|
||||
|
||||
@@ -95,7 +98,7 @@ def _procesar_un_correo(email: dict, token: str, email_addr: str, download_folde
|
||||
# FLUJO DEL CORREO
|
||||
# ========================================================================
|
||||
|
||||
print(f"\n📬 [{email['fecha']}] {email['subject'][:80]}...")
|
||||
logger.info(f"📬 [{email['fecha']}] {email['subject'][:80]}...")
|
||||
log("📂 Adjuntos:")
|
||||
|
||||
# 1-2. BD: verificar existencia y guardar
|
||||
@@ -178,7 +181,7 @@ def _procesar_un_correo(email: dict, token: str, email_addr: str, download_folde
|
||||
log(f"✅ Draft SAP B1 creado: {serie}-{numero} → DocEntry {doc_entry}")
|
||||
html_body = notificaciones.build_notification_body("created", factura, validation_table, valor_referencial_table, doc_entry=doc_entry)
|
||||
except Exception as ex:
|
||||
log(f"❌ Error creando draft {serie}-{numero}: {ex}")
|
||||
log(f"❌ Error creando draft {serie}-{numero}: {ex}", severity=logging.ERROR)
|
||||
html_body = notificaciones.build_notification_body("error", factura, validation_table, valor_referencial_table, error=ex)
|
||||
else:
|
||||
log(f"⏭️ Draft NO creado: {serie}-{numero} — validación falló")
|
||||
@@ -196,7 +199,7 @@ def _procesar_un_correo(email: dict, token: str, email_addr: str, download_folde
|
||||
cc_recipients=["jlopez@aberio.com.pe", "gcalle@pucp.pe"],
|
||||
)
|
||||
else:
|
||||
log("⚠️ No se pudo determinar el remitente, notificación no enviada")
|
||||
log("⚠️ No se pudo determinar el remitente, notificación no enviada", severity=logging.WARNING)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -211,18 +214,18 @@ def run_pipeline(dias: int, EMAIL: str, DOWNLOAD_FOLDER: str, OUTPUT_FOLDER: str
|
||||
ayer = hoy - timedelta(days=dias)
|
||||
fecha_inicio = ayer.strftime("%Y-%m-%d")
|
||||
fecha_fin = hoy.strftime("%Y-%m-%d")
|
||||
print(f"Rango de búsqueda: {fecha_inicio} al {fecha_fin}")
|
||||
logger.info(f"Rango de búsqueda: {fecha_inicio} al {fecha_fin}")
|
||||
|
||||
# 1. Autenticar
|
||||
token = step_authenticate()
|
||||
if not token:
|
||||
print("❌ No se pudo autenticar. Abortando.")
|
||||
logger.error("❌ No se pudo autenticar. Abortando.")
|
||||
return
|
||||
|
||||
# 2. Descargar correos
|
||||
emails = step_fetch_emails(token, EMAIL, fecha_inicio, fecha_fin)
|
||||
if not emails:
|
||||
print("No se encontraron correos.")
|
||||
logger.info("No se encontraron correos.")
|
||||
return
|
||||
|
||||
# 3. Bucle por cada correo
|
||||
|
||||
Reference in new issue
Block a user