Uecko_ERP_FactuGES_sync/app/utils/last_execution_helper.py

70 lines
1.8 KiB
Python
Raw Normal View History

2025-11-27 19:08:06 +00:00
from __future__ import annotations
2025-11-30 09:43:57 +00:00
2025-08-28 08:51:05 +00:00
from datetime import datetime, timezone
2025-11-30 09:43:57 +00:00
from pathlib import Path
from typing import Optional
2025-08-28 08:51:05 +00:00
2025-11-30 22:44:55 +00:00
# Fecha por defecto si nunca se ha ejecutado
DEFAULT_FALLBACK = datetime(2025, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
FMT = "%Y-%m-%d %H:%M:%S" # Formato persistido
2025-08-28 08:51:05 +00:00
2025-11-27 19:08:06 +00:00
def obtener_fecha_ultima_ejecucion(
2025-11-30 22:44:55 +00:00
path: str | Path,
2025-11-27 19:08:06 +00:00
*,
fallback: Optional[datetime] = None,
) -> datetime:
"""
2025-11-30 22:44:55 +00:00
Lee la última fecha de ejecución almacenada en `path`.
Retorna always-aware UTC.
- Si el archivo no existe fallback
- Si está vacío o el formato es inválido fallback
2025-11-30 09:43:57 +00:00
2025-11-30 22:44:55 +00:00
fallback predeterminado: DEFAULT_FALLBACK (2025-01-01)
2025-11-27 19:08:06 +00:00
"""
2025-11-30 09:43:57 +00:00
effective_fallback = fallback or DEFAULT_FALLBACK
2025-11-30 22:44:55 +00:00
p = Path(path)
2025-11-27 19:08:06 +00:00
2025-08-28 08:51:05 +00:00
try:
2025-11-30 22:44:55 +00:00
text = p.read_text(encoding="utf-8").strip()
2025-11-30 09:43:57 +00:00
if not text:
return effective_fallback
dt_naive = datetime.strptime(text, FMT)
2025-11-27 19:08:06 +00:00
return dt_naive.replace(tzinfo=timezone.utc)
2025-11-30 22:44:55 +00:00
2025-08-28 08:51:05 +00:00
except FileNotFoundError:
2025-11-30 09:43:57 +00:00
return effective_fallback
2025-11-27 19:08:06 +00:00
except ValueError:
2025-11-30 09:43:57 +00:00
return effective_fallback
2025-11-27 19:08:06 +00:00
2025-08-28 08:51:05 +00:00
2025-11-27 19:08:06 +00:00
def actualizar_fecha_ultima_ejecucion(
2025-11-30 22:44:55 +00:00
path: str | Path,
2025-11-27 19:08:06 +00:00
*,
momento: Optional[datetime] = None,
) -> None:
"""
2025-11-30 22:44:55 +00:00
Guarda `momento` (UTC) en `path`, creando directorios si hace falta.
- Si `momento` es None ahora en UTC
- Si `momento` viene naive se asume UTC
- Si trae tz se convierte a UTC
2025-11-27 19:08:06 +00:00
"""
2025-11-30 22:44:55 +00:00
p = Path(path)
2025-11-27 19:08:06 +00:00
if momento is None:
momento = datetime.now(timezone.utc)
else:
if momento.tzinfo is None:
momento = momento.replace(tzinfo=timezone.utc)
else:
momento = momento.astimezone(timezone.utc)
2025-08-28 08:51:05 +00:00
2025-11-30 22:44:55 +00:00
p.parent.mkdir(parents=True, exist_ok=True)
2025-08-28 08:51:05 +00:00
2025-11-30 22:44:55 +00:00
p.write_text(momento.strftime(FMT), encoding="utf-8")