2020-12-03 12:31:39 -05:00
|
|
|
import smtplib
|
|
|
|
|
|
|
|
from email.message import EmailMessage
|
2020-12-07 18:02:46 -05:00
|
|
|
from itertools import groupby
|
2020-12-03 12:31:39 -05:00
|
|
|
|
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
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 _send_email(self, to, subject, content):
|
|
|
|
msg = EmailMessage()
|
|
|
|
msg.set_content(content)
|
|
|
|
msg['Subject'] = subject
|
|
|
|
msg['From'] = 'adam@adamgoldsmith.name'
|
|
|
|
msg['To'] = to
|
|
|
|
|
|
|
|
with smtplib.SMTP("localhost") as server:
|
|
|
|
server.send_message(msg)
|
|
|
|
|
|
|
|
def _active_reminders(self):
|
|
|
|
for reminder in Reminder.objects.all():
|
|
|
|
if reminder.should_remind:
|
|
|
|
yield reminder
|
|
|
|
|
|
|
|
def _format_reminder_lines(self, reminders):
|
|
|
|
for reminder in reminders:
|
|
|
|
next_date = reminder.task.next_recurrence.strftime('%Y-%m-%d')
|
|
|
|
yield f" - {reminder.task.name} - {next_date}"
|
|
|
|
|
2020-12-03 12:31:39 -05:00
|
|
|
def handle(self, *args, **options):
|
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():
|
|
|
|
self.stdout.write(self.style.SUCCESS(
|
|
|
|
f'Sending notification for {len(reminders)} task(s) to {user}'))
|
|
|
|
|
|
|
|
contents = "The following tasks are upcoming or overdue:\n\n" + \
|
|
|
|
('\n'.join(self._format_reminder_lines(reminders)))
|
|
|
|
|
|
|
|
self._send_email(
|
|
|
|
user.email,
|
|
|
|
f'[CMS Tool Maintenance] {len(reminders)} tasks are upcoming or overdue!',
|
|
|
|
contents)
|