"""Background scheduler that scans alerts and dispatches reminder emails.""" import logging from datetime import date, timezone from apscheduler.schedulers.background import BackgroundScheduler from .models import Alert, User, db from .mailer import send_mail logger = logging.getLogger(__name__) _scheduler: BackgroundScheduler | None = None def _check_and_send(app): """Iterate active alerts; for each reminder threshold reached, email all users.""" with app.app_context(): today = date.today() active_alerts = Alert.query.filter_by(is_active=True).all() recipients = [u.email for u in User.query.filter_by(is_active=True).all() if u.email] if not recipients: logger.info("Scheduler tick: no recipients.") return for alert in active_alerts: days_left = (alert.expiration_date - today).days already_sent = set(alert.reminders_sent) newly_sent = [] for threshold in alert.reminder_days: if days_left <= threshold and threshold not in already_sent: subject = f"[AlertHub] Reminder: {alert.title} expires in {days_left} day(s)" body_text = ( f"Alert: {alert.title}\n" f"Category: {alert.category or '—'}\n" f"Expiration date: {alert.expiration_date.isoformat()}\n" f"Days remaining: {days_left}\n\n" f"{alert.description or ''}\n" ) body_html = f"""
Category: {alert.category or '—'}
Expiration date: {alert.expiration_date.isoformat()}
Days remaining: {days_left}
{alert.description or ''}