2020-12-07 18:02:46 -05:00
|
|
|
from itertools import groupby
|
2020-12-03 12:31:39 -05:00
|
|
|
|
2020-12-08 16:02:08 -05:00
|
|
|
from django.core.mail import send_mail
|
2020-12-03 12:31:39 -05:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
2020-12-08 16:02:08 -05:00
|
|
|
from django.template import loader
|
|
|
|
|
2020-12-07 18:02:46 -05:00
|
|
|
from tasks.models import Tool, Task, Event, Reminder
|
2020-12-03 12:31:39 -05:00
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
help = 'Sends any notifications for upcoming and overdue tasks'
|
|
|
|
|
2020-12-07 18:02:46 -05:00
|
|
|
def _active_reminders(self):
|
|
|
|
for reminder in Reminder.objects.all():
|
|
|
|
if reminder.should_remind:
|
|
|
|
yield reminder
|
|
|
|
|
2020-12-03 12:31:39 -05:00
|
|
|
def handle(self, *args, **options):
|
2020-12-08 16:02:08 -05:00
|
|
|
template = loader.get_template('tasks/notificationEmail.txt')
|
|
|
|
|
2020-12-07 18:02:46 -05:00
|
|
|
reminders_per_user = {
|
|
|
|
user: sorted(reminders, key=lambda r: r.task.next_recurrence)
|
|
|
|
for user, reminders in groupby(self._active_reminders(), lambda r: r.user)
|
|
|
|
}
|
|
|
|
|
|
|
|
for user, reminders in reminders_per_user.items():
|
2020-12-08 16:03:19 -05:00
|
|
|
if not user.email:
|
|
|
|
self.stdout.write(self.style.ERROR(
|
|
|
|
f"Can't send email, user '{user}' is missing an email address"))
|
|
|
|
continue
|
|
|
|
|
2020-12-07 18:02:46 -05:00
|
|
|
self.stdout.write(self.style.SUCCESS(
|
|
|
|
f'Sending notification for {len(reminders)} task(s) to {user}'))
|
|
|
|
|
2020-12-08 16:03:19 -05:00
|
|
|
try:
|
|
|
|
send_mail(
|
|
|
|
subject=f'[CMS Tool Maintenance] {len(reminders)} tasks are upcoming or overdue!',
|
|
|
|
message=template.render({'reminders': reminders}).strip(),
|
|
|
|
from_email='adam@adamgoldsmith.name',
|
|
|
|
recipient_list=[user.email],
|
|
|
|
fail_silently=False
|
|
|
|
)
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
self.stdout.write(self.style.ERROR(
|
|
|
|
f"Failed to send mail for user '{user}': {type(e).__name__}: {e}"))
|