tasks.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from datetime import timedelta
  2. from celery import shared_task
  3. from django.db.models import Count
  4. from django.utils import timezone
  5. from apps.issue_events.models import Issue
  6. from .models import Notification, ProjectAlert
  7. def process_alert(project_alert_id: int, issue_ids: list[int]):
  8. notification = Notification.objects.create(project_alert_id=project_alert_id)
  9. notification.issues.add(*issue_ids)
  10. send_notification.delay(notification.pk)
  11. @shared_task
  12. def process_event_alerts():
  13. """Inspect alerts and determine if new notifications need sent"""
  14. now = timezone.now()
  15. for alert in ProjectAlert.objects.filter(
  16. quantity__isnull=False, timespan_minutes__isnull=False
  17. ):
  18. start_time = now - timedelta(minutes=alert.timespan_minutes)
  19. quantity_in_timespan = alert.quantity
  20. issues = (
  21. Issue.objects.filter(
  22. project_id=alert.project_id,
  23. issueevent__received__gte=start_time,
  24. )
  25. .exclude(notification__project_alert=alert)
  26. .annotate(num_events=Count("issueevent"))
  27. .filter(num_events__gte=quantity_in_timespan)
  28. )
  29. if issues:
  30. notification = alert.notification_set.create()
  31. notification.issues.add(*issues)
  32. send_notification.delay(notification.pk)
  33. @shared_task
  34. def send_notification(notification_id: int):
  35. notification = Notification.objects.get(pk=notification_id)
  36. notification.send_notifications()