187 lines
6.3 KiB
Python
187 lines
6.3 KiB
Python
"""
|
|
APScheduler para recordatorios de cobranza.
|
|
|
|
Cada recordatorio activo se traduce en un CronTrigger con día(s) de la
|
|
semana + hora. APScheduler corre en el mismo event loop de FastAPI.
|
|
|
|
Convención día_of_week APScheduler: 0=Lunes ... 6=Domingo (igual que Python).
|
|
"""
|
|
|
|
import logging
|
|
import os
|
|
from datetime import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
|
from apscheduler.triggers.cron import CronTrigger
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
MEXICO = ZoneInfo("America/Mexico_City")
|
|
scheduler = AsyncIOScheduler(timezone=MEXICO)
|
|
|
|
|
|
async def ejecutar_cobranza_automatica(numero_wa: str, tipo: str, instance: str) -> None:
|
|
"""Genera y envía un reporte de cobranza por WhatsApp.
|
|
|
|
numero_wa: '521XXXXXXXXXX@s.whatsapp.net'
|
|
tipo: 'diario' | 'semanal' | 'mensual'
|
|
instance: nombre de la instancia EvolutionAPI
|
|
"""
|
|
# Imports tardíos para evitar ciclos: webhook importa schemas que importan
|
|
# cosas de services, etc.
|
|
from src.services.sheets import generar_reporte_cobros
|
|
from src.api.webhook import (
|
|
_formatear_reporte,
|
|
_formatear_reporte_semanal,
|
|
_formatear_reporte_mensual,
|
|
)
|
|
from src.services import whatsapp
|
|
|
|
try:
|
|
hoy = datetime.now(MEXICO).date()
|
|
reporte = generar_reporte_cobros(
|
|
hoy=hoy,
|
|
semanal=(tipo == "semanal"),
|
|
mensual=(tipo == "mensual"),
|
|
)
|
|
if tipo == "semanal":
|
|
texto = _formatear_reporte_semanal(reporte)
|
|
elif tipo == "mensual":
|
|
texto = _formatear_reporte_mensual(reporte)
|
|
else:
|
|
texto = _formatear_reporte(reporte)
|
|
await whatsapp.enviar_texto(numero_wa, texto, instance)
|
|
logger.info(
|
|
"Recordatorio %s enviado a %s a las %s",
|
|
tipo, numero_wa, datetime.now(MEXICO).isoformat(timespec="seconds"),
|
|
)
|
|
except Exception:
|
|
logger.exception("Error ejecutando cobranza automática (%s → %s)", tipo, numero_wa)
|
|
|
|
|
|
async def sincronizar_jobs() -> None:
|
|
"""Re-registra los jobs en APScheduler según los recordatorios activos.
|
|
|
|
Quita primero todos los jobs con prefijo 'rec_'. Luego registra los
|
|
activos desde Redis. Idempotente: se puede llamar tras cada cambio.
|
|
"""
|
|
from src.services.recordatorios import get_recordatorios
|
|
|
|
instance = os.getenv("EVOLUTION_INSTANCE", "wk-bot")
|
|
|
|
# Limpia jobs viejos
|
|
for job in list(scheduler.get_jobs()):
|
|
if job.id.startswith("rec_"):
|
|
try:
|
|
scheduler.remove_job(job.id)
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
recordatorios = await get_recordatorios()
|
|
except Exception:
|
|
logger.exception("No se pudieron leer recordatorios; sin jobs activos")
|
|
return
|
|
|
|
registrados = 0
|
|
for r in recordatorios:
|
|
if not r.get("activo"):
|
|
continue
|
|
try:
|
|
hora_str = r.get("hora") or "08:00"
|
|
hora, minuto = hora_str.split(":")
|
|
dias = r.get("dias") or []
|
|
if not dias:
|
|
continue
|
|
dias_cron = ",".join(str(d) for d in dias)
|
|
# MX usa prefijo 521 + 10 dígitos para WhatsApp.
|
|
numero_wa = f"521{r['numero']}@s.whatsapp.net"
|
|
scheduler.add_job(
|
|
ejecutar_cobranza_automatica,
|
|
CronTrigger(
|
|
day_of_week=dias_cron,
|
|
hour=int(hora),
|
|
minute=int(minuto),
|
|
timezone=MEXICO,
|
|
),
|
|
args=[numero_wa, r.get("tipo", "diario"), instance],
|
|
id=f"rec_{r['id']}",
|
|
replace_existing=True,
|
|
)
|
|
registrados += 1
|
|
except Exception:
|
|
logger.exception("No se pudo registrar recordatorio %s", r.get("id"))
|
|
|
|
logger.info(
|
|
"Scheduler sincronizado: %d job(s) activo(s)", registrados,
|
|
)
|
|
|
|
|
|
async def acumular_cobranza_global() -> None:
|
|
"""Job 9:30 am: para cada número con cobranza activa, acumula los
|
|
vencimientos del día. Itera las keys `cobranza_acumulada:*` en Redis.
|
|
"""
|
|
from src.services import cobranza_acumulada
|
|
from src.services.session import get_client
|
|
try:
|
|
r = get_client()
|
|
numeros: list[str] = []
|
|
async for key in r.scan_iter(match="cobranza_acumulada:*"):
|
|
num = key.split(":", 1)[1] if ":" in key else key
|
|
if num:
|
|
numeros.append(num)
|
|
except Exception:
|
|
logger.exception("No se pudo escanear keys de cobranza_acumulada")
|
|
return
|
|
|
|
logger.info("acumular_cobranza_global: %d usuarios con cobranza activa", len(numeros))
|
|
for num in numeros:
|
|
try:
|
|
res = await cobranza_acumulada.acumular_dia(num)
|
|
logger.info(
|
|
"Auto-acumulado para %s: +%s renglones (total %s)",
|
|
num, res.get("agregados"), res.get("total"),
|
|
)
|
|
except Exception:
|
|
logger.exception("Error acumulando cobranza para %s", num)
|
|
|
|
|
|
def _registrar_job_cobranza_acumulada() -> None:
|
|
"""Registra el job diario 9:30 am (configurable por env COBRANZA_HORA_ACUMULA)."""
|
|
hora_str = os.getenv("COBRANZA_HORA_ACUMULA", "09:30")
|
|
try:
|
|
hh, mm = hora_str.split(":")
|
|
hh_i, mm_i = int(hh), int(mm)
|
|
except Exception:
|
|
logger.warning("COBRANZA_HORA_ACUMULA inválida %r — usando 09:30", hora_str)
|
|
hh_i, mm_i = 9, 30
|
|
scheduler.add_job(
|
|
acumular_cobranza_global,
|
|
CronTrigger(hour=hh_i, minute=mm_i, timezone=MEXICO),
|
|
id="cobranza_acumulada_diaria",
|
|
replace_existing=True,
|
|
)
|
|
logger.info("Job cobranza_acumulada_diaria registrado a las %02d:%02d MX", hh_i, mm_i)
|
|
|
|
|
|
async def start_scheduler() -> None:
|
|
"""Arranca el scheduler y sincroniza jobs. No crashea si Redis falla."""
|
|
try:
|
|
if not scheduler.running:
|
|
scheduler.start()
|
|
await sincronizar_jobs()
|
|
_registrar_job_cobranza_acumulada()
|
|
logger.info("Scheduler iniciado")
|
|
except Exception:
|
|
logger.exception("Error iniciando scheduler — continuando sin jobs")
|
|
|
|
|
|
async def stop_scheduler() -> None:
|
|
try:
|
|
if scheduler.running:
|
|
scheduler.shutdown(wait=False)
|
|
logger.info("Scheduler detenido")
|
|
except Exception:
|
|
logger.exception("Error deteniendo scheduler")
|