Uecko_ERP_FactuGES_sync/app/utils/last_execution_helper.py

61 lines
1.9 KiB
Python
Raw Normal View History

2025-11-27 19:08:06 +00:00
from __future__ import annotations
2025-08-28 08:51:05 +00:00
from datetime import datetime, timezone
2025-11-27 19:08:06 +00:00
from typing import Optional
import os
2025-08-28 08:51:05 +00:00
2025-11-27 19:08:06 +00:00
DEFAULT_PATH = "./last_execution.txt"
FMT = "%Y-%m-%d %H:%M:%S"
2025-08-28 08:51:05 +00:00
2025-11-27 19:08:06 +00:00
def obtener_fecha_ultima_ejecucion(
path: str = DEFAULT_PATH,
*,
fallback: Optional[datetime] = None,
) -> datetime:
"""
Lee la última fecha de ejecución desde `path` y la devuelve como aware (UTC).
Si no existe o hay error de parseo, devuelve `fallback` (por defecto 2024-01-01 UTC).
"""
if fallback is None:
fallback = datetime(2024, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
2025-08-28 08:51:05 +00:00
try:
2025-11-27 19:08:06 +00:00
with open(path, "r", encoding="utf8") as f:
2025-08-28 08:51:05 +00:00
fecha_str = f.read().strip()
2025-11-27 19:08:06 +00:00
# Se guarda como texto sin tz; interpretamos como UTC
dt_naive = datetime.strptime(fecha_str, FMT)
return dt_naive.replace(tzinfo=timezone.utc)
2025-08-28 08:51:05 +00:00
except FileNotFoundError:
2025-11-27 19:08:06 +00:00
return fallback
except ValueError:
# Formato inválido en el archivo -> usar fallback
return fallback
2025-08-28 08:51:05 +00:00
2025-11-27 19:08:06 +00:00
def actualizar_fecha_ultima_ejecucion(
path: str = DEFAULT_PATH,
*,
momento: Optional[datetime] = None,
) -> None:
"""
Escribe en `path` la fecha/hora (UTC) en formato YYYY-MM-DD HH:MM:SS.
Si `momento` es None, usa ahora en UTC.
Crea directorios intermedios si no existen.
"""
if momento is None:
momento = datetime.now(timezone.utc)
else:
# Normalizamos a UTC si viene con tz; si es naive, asumimos UTC
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-27 19:08:06 +00:00
# Asegurar carpeta si `path` incluye directorios
folder = os.path.dirname(os.path.abspath(path))
if folder and not os.path.exists(folder):
os.makedirs(folder, exist_ok=True)
2025-08-28 08:51:05 +00:00
2025-11-27 19:08:06 +00:00
with open(path, "w", encoding="utf8") as f:
f.write(momento.strftime(FMT))