update notify teachers (notify after deadline)
[edumed.git] / wtem / management / commands / notify_teachers.py
1 # -*- coding: utf-8 -*-
2 from datetime import timedelta
3 from django.core.management.base import BaseCommand
4 from django.template.loader import render_to_string
5 from django.utils import timezone
6
7 from contact.models import Contact
8 from wtem.management.commands import send_mail
9 from wtem.models import Confirmation
10
11
12 THRESHOLD = 0
13
14 AFTER_DEADLINE = True
15
16
17 class Command(BaseCommand):
18     def handle(self, *args, **options):
19         sent = 0
20         failed = 0
21
22         query = Contact.objects.filter(form_tag='olimpiada').order_by('contact').distinct('contact')
23         template_name = 'notify_unconfirmed'
24         message_template = 'wtem/' + template_name + ('_after' if AFTER_DEADLINE else '') + '.txt'
25         subject = render_to_string('wtem/' + template_name + '_subject.txt')
26
27         threshold = timezone.now() - timedelta(THRESHOLD)
28
29         for contact in query:
30             unconfirmed = []
31             contacts = []
32             for similar_contact in Contact.objects.filter(contact=contact.contact, form_tag=contact.form_tag):
33                 contact_emails = [s['email'] for s in similar_contact.body.get('student', [])]
34                 new_unconfirmed = list(Confirmation.objects.filter(
35                     contact=similar_contact, confirmed=False, contact__created_at__lt=threshold,
36                     email__in=contact_emails))
37                 unconfirmed += new_unconfirmed
38                 if new_unconfirmed:
39                     contacts.append(similar_contact)
40             if not unconfirmed:
41                 continue
42             message = render_to_string(message_template, {'unconfirmed': unconfirmed, 'contacts': contacts})
43             try:
44                 self.send_message(message, subject, contact.contact)
45             except Exception as e:
46                 failed += 1
47                 self.stdout.write('failed sending to: ' + contact.contact + ' - ' + str(e))
48             else:
49                 sent += 1
50                 self.stdout.write('message sent to: ' + contact.contact)
51
52         self.stdout.write('sent: %s, failed: %s' % (sent, failed))
53
54     def send_message(self, message, subject, email):
55         self.stdout.write('>>> sending to %s' % email)
56         send_mail(subject=subject, body=message, to=[email])