You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.4 KiB

  1. from datetime import timedelta
  2. from django.contrib.auth.models import User
  3. from django.core.management.base import BaseCommand
  4. from django.db.models import Q
  5. from django.utils import timezone
  6. from hc.accounts.models import Profile
  7. from hc.api.models import Check
  8. def num_pinged_checks(profile):
  9. q = Check.objects.filter(user_id=profile.user.id,)
  10. q = q.filter(last_ping__isnull=False)
  11. return q.count()
  12. class Command(BaseCommand):
  13. help = 'Send due monthly reports'
  14. tmpl = "Sending monthly report to %s"
  15. def handle(self, *args, **options):
  16. # Create any missing profiles
  17. for u in User.objects.filter(profile__isnull=True):
  18. self.stdout.write("Creating profile for %s" % u.email)
  19. Profile.objects.for_user(u)
  20. now = timezone.now()
  21. month_before = now - timedelta(days=30)
  22. report_due = Q(next_report_date__lt=now)
  23. report_not_scheduled = Q(next_report_date__isnull=True)
  24. q = Profile.objects.filter(report_due | report_not_scheduled)
  25. q = q.filter(reports_allowed=True)
  26. q = q.filter(user__date_joined__lt=month_before)
  27. sent = 0
  28. for profile in q:
  29. if num_pinged_checks(profile) > 0:
  30. self.stdout.write(self.tmpl % profile.user.email)
  31. profile.send_report()
  32. sent += 1
  33. return "Sent %d reports" % sent