140 lines
4.2 KiB
Python
140 lines
4.2 KiB
Python
"""
|
|
Gestión de recordatorios de cobranza automática.
|
|
|
|
Storage: Redis (persistente, una sola key con JSON list).
|
|
Tokens admin: Redis con TTL 30 min, asociados a un número de WhatsApp.
|
|
|
|
Estructura de cada recordatorio:
|
|
{
|
|
"id": str (uuid4),
|
|
"numero": str (10 dígitos, ej "2222127552"),
|
|
"nombre": str (ej "Paulino"),
|
|
"tipo": str ("diario" | "semanal" | "mensual"),
|
|
"hora": str (ej "08:30"),
|
|
"dias": list[int] (0=lunes...6=domingo),
|
|
"activo": bool,
|
|
"creado": str (ISO datetime),
|
|
}
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
import uuid
|
|
from datetime import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from src.services.session import get_client
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
KEY_ALL = "recordatorios:all"
|
|
ADMIN_TOKEN_TTL = 1800 # 30 minutos
|
|
MEXICO = ZoneInfo("America/Mexico_City")
|
|
|
|
|
|
async def get_recordatorios() -> list[dict]:
|
|
"""Devuelve TODOS los recordatorios. [] si Redis no responde o vacío."""
|
|
try:
|
|
r = get_client()
|
|
data = await r.get(KEY_ALL)
|
|
if not data:
|
|
return []
|
|
return json.loads(data)
|
|
except Exception:
|
|
logger.exception("Error leyendo recordatorios de Redis")
|
|
return []
|
|
|
|
|
|
async def _save_all(recordatorios: list[dict]) -> None:
|
|
try:
|
|
r = get_client()
|
|
await r.set(KEY_ALL, json.dumps(recordatorios, ensure_ascii=False))
|
|
except Exception:
|
|
logger.exception("Error guardando recordatorios en Redis")
|
|
raise
|
|
|
|
|
|
async def get_recordatorios_by_numero(numero: str) -> list[dict]:
|
|
"""Filtra por el número (10 dígitos) del owner."""
|
|
todos = await get_recordatorios()
|
|
return [r for r in todos if r.get("numero") == numero]
|
|
|
|
|
|
async def crear_recordatorio(data: dict) -> dict:
|
|
"""Crea un recordatorio nuevo. data debe traer: numero, tipo, hora, dias."""
|
|
nuevo = {
|
|
"id": str(uuid.uuid4()),
|
|
"numero": data["numero"],
|
|
"nombre": data.get("nombre", ""),
|
|
"tipo": data.get("tipo", "diario"),
|
|
"hora": data.get("hora", "08:00"),
|
|
"dias": data.get("dias", [0, 1, 2, 3, 4]),
|
|
"activo": bool(data.get("activo", True)),
|
|
"creado": datetime.now(MEXICO).isoformat(),
|
|
}
|
|
todos = await get_recordatorios()
|
|
todos.append(nuevo)
|
|
await _save_all(todos)
|
|
return nuevo
|
|
|
|
|
|
async def actualizar_recordatorio(id: str, data: dict) -> dict | None:
|
|
"""Actualiza solo los campos editables (tipo, hora, dias, activo, nombre)."""
|
|
todos = await get_recordatorios()
|
|
for i, r in enumerate(todos):
|
|
if r.get("id") == id:
|
|
for key in ("nombre", "tipo", "hora", "dias", "activo"):
|
|
if key in data and data[key] is not None:
|
|
r[key] = data[key]
|
|
todos[i] = r
|
|
await _save_all(todos)
|
|
return r
|
|
return None
|
|
|
|
|
|
async def eliminar_recordatorio(id: str) -> bool:
|
|
todos = await get_recordatorios()
|
|
nuevos = [r for r in todos if r.get("id") != id]
|
|
if len(nuevos) == len(todos):
|
|
return False
|
|
await _save_all(nuevos)
|
|
return True
|
|
|
|
|
|
async def toggle_activo(id: str) -> dict | None:
|
|
todos = await get_recordatorios()
|
|
for i, r in enumerate(todos):
|
|
if r.get("id") == id:
|
|
r["activo"] = not bool(r.get("activo", False))
|
|
todos[i] = r
|
|
await _save_all(todos)
|
|
return r
|
|
return None
|
|
|
|
|
|
# ── Tokens de administración ──────────────────────────────────────
|
|
|
|
async def crear_token_admin(numero: str) -> str:
|
|
"""Genera un token UUID4 asociado al número, TTL 30 min."""
|
|
token = str(uuid.uuid4())
|
|
try:
|
|
r = get_client()
|
|
await r.setex(f"admin_token:{token}", ADMIN_TOKEN_TTL, numero)
|
|
except Exception:
|
|
logger.exception("Error creando token admin")
|
|
raise
|
|
return token
|
|
|
|
|
|
async def validar_token_admin(token: str) -> str | None:
|
|
"""Devuelve el número asociado al token, o None si inválido/expirado."""
|
|
if not token:
|
|
return None
|
|
try:
|
|
r = get_client()
|
|
numero = await r.get(f"admin_token:{token}")
|
|
return numero if numero else None
|
|
except Exception:
|
|
logger.exception("Error validando token admin")
|
|
return None
|