from datetime import date, datetime, timedelta, timezone from sqlalchemy.orm import Session from app.config import settings from app.models import AlertDispatch, OutboundClick from app.services.email import send_email TICKET_KINDS = ("bookmyshow", "district") def maybe_notify_click_spike(db: Session) -> None: if not settings.smtp_configured: return since = datetime.now(timezone.utc) - timedelta(hours=24) count = ( db.query(OutboundClick) .filter(OutboundClick.created_at >= since, OutboundClick.link_kind.in_(TICKET_KINDS)) .count() ) if count < settings.alert_click_threshold: return alert_key = f"click_spike_{date.today().isoformat()}" if db.query(AlertDispatch).filter(AlertDispatch.alert_key == alert_key).first(): return send_email( subject=f"Desi Clans — ticket click spike ({count} in 24h)", body=( f"Ticket outbound clicks in the last 24 hours: {count}\n" f"Threshold: {settings.alert_click_threshold}\n" f"City: Bengaluru\n" "Check admin analytics for details." ), ) db.add(AlertDispatch(alert_key=alert_key)) db.commit()