cmsmanage/tasks/management/commands/sendNotifications.py

50 lines
1.7 KiB
Python

import smtplib
from email.message import EmailMessage
from itertools import groupby
from django.core.management.base import BaseCommand, CommandError
from tasks.models import Tool, Task, Event, Reminder
class Command(BaseCommand):
help = 'Sends any notifications for upcoming and overdue tasks'
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}"
def handle(self, *args, **options):
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)