|
| 1 | +import datetime |
| 2 | + |
| 3 | +from django.core.mail import send_mail |
| 4 | +from django.core.management import BaseCommand |
| 5 | +from django.db.models import Count |
| 6 | +from django.conf import settings |
| 7 | +from django.template import loader |
| 8 | + |
| 9 | + |
| 10 | +from jobs.models import Job |
| 11 | + |
| 12 | + |
| 13 | +class Command(BaseCommand): |
| 14 | + def handle(self, **options): |
| 15 | + if datetime.date.today().day != 27: |
| 16 | + # Send only on 27th of each month |
| 17 | + return |
| 18 | + |
| 19 | + current_month = datetime.date.today().month |
| 20 | + current_month_jobs = ( |
| 21 | + Job.objects.filter(created__month=current_month) |
| 22 | + .values("status") |
| 23 | + .annotate(dcount=Count("status")) |
| 24 | + .order_by() |
| 25 | + ) |
| 26 | + current_month_jobs = {x["status"]: x["dcount"] for x in current_month_jobs} |
| 27 | + submissions_current_month = sum(current_month_jobs.values()) |
| 28 | + |
| 29 | + previous_month = ( |
| 30 | + datetime.date.today().replace(day=1) - datetime.timedelta(days=1) |
| 31 | + ).month |
| 32 | + previous_month_jobs = ( |
| 33 | + Job.objects.filter(created__month=previous_month) |
| 34 | + .values("status") |
| 35 | + .annotate(dcount=Count("status")) |
| 36 | + .order_by() |
| 37 | + ) |
| 38 | + previous_month_jobs = {x["status"]: x["dcount"] for x in previous_month_jobs} |
| 39 | + submissions_previous_month = sum(previous_month_jobs.values()) |
| 40 | + |
| 41 | + subject_template = loader.get_template( |
| 42 | + "jobs/email/monthly_jobs_report_subject.txt" |
| 43 | + ) |
| 44 | + message_template = loader.get_template("jobs/email/monthly_jobs_report.txt") |
| 45 | + |
| 46 | + context = { |
| 47 | + "current_month_jobs": current_month_jobs, |
| 48 | + "submissions_current_month": submissions_current_month, |
| 49 | + "previous_month_jobs": previous_month_jobs, |
| 50 | + "submissions_previous_month": submissions_previous_month, |
| 51 | + } |
| 52 | + |
| 53 | + subject = subject_template.render(context).strip() |
| 54 | + message = message_template.render(context) |
| 55 | + send_mail( |
| 56 | + subject, |
| 57 | + message, |
| 58 | + settings.JOB_FROM_EMAIL, |
| 59 | + |
| 60 | + ) |
0 commit comments