1 # -*- coding: utf-8 -*-
2 from collections import defaultdict
3 from decimal import Decimal
4 from optparse import make_option
6 from django.core.management.base import BaseCommand
7 from wtem.management.commands import send_mail
8 from django.utils import translation
9 from django.template.loader import render_to_string
11 from stage2.models import Participant
14 def get_participants():
15 return sorted(Participant.objects.filter(complete_set=True), key=lambda s: -s.score())
17 minimum = Decimal('73.33')
20 class Command(BaseCommand):
22 option_list = BaseCommand.option_list + (
28 help='Send emails to teachers'),
34 help='Send emails to students'),
40 help='Send email only to one address'),
44 super(Command, self).__init__()
45 self.sent = self.failed = None
47 def handle(self, *args, **options):
48 translation.activate('pl')
49 for target in ['to_teachers', 'to_students']:
53 getattr(self, 'handle_' + target)(*args, **options)
55 def handle_to_students(self, *args, **options):
56 self.stdout.write('>>> Sending results to students')
57 subject = 'Wyniki II etapu Olimpiady Cyfrowej'
59 for participant in get_participants():
60 if options['only_to'] and participant.email != options['only_to']:
62 final_result = participant.score()
63 if final_result < minimum:
64 template = 'results_student_failed.txt'
66 template = 'results_student_passed.txt'
67 message = render_to_string('stage2/' + template, dict(final_result=final_result))
68 self.send_message(message, subject, participant.email)
72 def handle_to_teachers(self, *args, **options):
73 self.stdout.write('>>> Sending results to teachers')
74 subject = 'Wyniki II etapu Olimpiady Cyfrowej'
76 participants_by_contact = defaultdict(list)
78 for participant in get_participants():
79 if options['only_to'] and participant.contact.contact != options['only_to']:
81 participants_by_contact[participant.contact.contact].append(participant)
83 for contact_email, participants in participants_by_contact.items():
84 message = render_to_string('stage2/results_teacher.txt', dict(participants=participants))
85 self.send_message(message, subject, contact_email)
90 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
92 def send_message(self, message, subject, email):
93 self.stdout.write('>>> sending results to %s' % email)
95 send_mail(subject=subject, body=message, to=[email])
96 except BaseException, e:
98 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
101 self.stdout.write('message sent to: ' + email)