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