tasks.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 issues.models import Issue
  6. from .models import Notification, ProjectAlert
  7. @shared_task
  8. def process_event_alerts():
  9. """Inspect alerts and determine if new notifications need sent"""
  10. now = timezone.now()
  11. for alert in ProjectAlert.objects.filter(
  12. quantity__isnull=False, timespan_minutes__isnull=False
  13. ):
  14. start_time = now - timedelta(minutes=alert.timespan_minutes)
  15. quantity_in_timespan = alert.quantity
  16. issues = (
  17. Issue.objects.filter(
  18. project_id=alert.project_id,
  19. notification__isnull=True,
  20. event__created__gte=start_time,
  21. )
  22. .annotate(num_events=Count("event"))
  23. .filter(num_events__gte=quantity_in_timespan)
  24. )
  25. if issues:
  26. notification = alert.notification_set.create()
  27. notification.issues.add(*issues)
  28. send_notification.delay(notification.pk)
  29. @shared_task
  30. def send_notification(notification_id: int):
  31. notification = Notification.objects.get(pk=notification_id)
  32. notification.send_notifications()