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.

60 lines
1.7 KiB

  1. from datetime import timedelta
  2. import time
  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 add_arguments(self, parser):
  16. parser.add_argument(
  17. '--loop',
  18. action='store_true',
  19. dest='loop',
  20. default=False,
  21. help='Keep running indefinitely in a 300 second wait loop',
  22. )
  23. def handle_one_run(self):
  24. now = timezone.now()
  25. month_before = now - timedelta(days=30)
  26. report_due = Q(next_report_date__lt=now)
  27. report_not_scheduled = Q(next_report_date__isnull=True)
  28. q = Profile.objects.filter(report_due | report_not_scheduled)
  29. q = q.filter(reports_allowed=True)
  30. q = q.filter(user__date_joined__lt=month_before)
  31. sent = 0
  32. for profile in q:
  33. if num_pinged_checks(profile) > 0:
  34. self.stdout.write(self.tmpl % profile.user.email)
  35. profile.send_report()
  36. sent += 1
  37. return sent
  38. def handle(self, *args, **options):
  39. if not options["loop"]:
  40. return "Sent %d reports" % self.handle_one_run()
  41. self.stdout.write("sendreports is now running")
  42. while True:
  43. self.handle_one_run()
  44. formatted = timezone.now().isoformat()
  45. self.stdout.write("-- MARK %s --" % formatted)
  46. time.sleep(300)