add update links in notify teachers
[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 = 3
13
14
15 class Command(BaseCommand):
16     def handle(self, *args, **options):
17         sent = 0
18         failed = 0
19
20         query = Contact.objects.filter(form_tag='olimpiada').order_by('contact').distinct('contact')
21         template_name = 'notify_unconfirmed'
22         message_template = 'wtem/' + template_name + '.txt'
23         subject = render_to_string('wtem/' + template_name + '_subject.txt')
24
25         threshold = timezone.now() - timedelta(THRESHOLD)
26
27         for contact in query:
28             unconfirmed = []
29             contacts = []
30             for similar_contact in Contact.objects.filter(contact=contact.contact, form_tag=contact.form_tag):
31                 new_unconfirmed = list(Confirmation.objects.filter(
32                     contact=similar_contact, confirmed=False, contact__created_at__lt=threshold))
33                 unconfirmed += new_unconfirmed
34                 if new_unconfirmed:
35                     contacts.append(similar_contact)
36             if not unconfirmed:
37                 continue
38             message = render_to_string(message_template, {'unconfirmed': unconfirmed, 'contacts': contacts})
39             try:
40                 self.send_message(message, subject, contact.contact)
41             except Exception as e:
42                 failed += 1
43                 self.stdout.write('failed sending to: ' + contact.contact + ' - ' + str(e))
44             else:
45                 sent += 1
46                 self.stdout.write('message sent to: ' + contact.contact)
47
48         self.stdout.write('sent: %s, failed: %s' % (sent, failed))
49
50     def send_message(self, message, subject, email):
51         self.stdout.write('>>> sending to %s' % email)
52         send_mail(subject=subject, body=message, to=[email])