1 # -*- coding: utf-8 -*-
2 from collections import defaultdict
3 from optparse import make_option
5 from django.core.management.base import BaseCommand
6 from wtem.management.commands import send_mail
7 from django.utils import translation
8 from django.template.loader import render_to_string
10 from stage2.models import Participant
13 def get_participants():
14 return sorted(Participant.objects.filter(complete_set=True), key=lambda s: -s.score())
19 class Command(BaseCommand):
21 option_list = BaseCommand.option_list + (
27 help='Send emails to teachers'),
33 help='Send emails to students'),
39 help='Send email only to one address'),
43 super(Command, self).__init__()
44 self.sent = self.failed = None
46 def handle(self, *args, **options):
47 translation.activate('pl')
48 for target in ['to_teachers', 'to_students']:
52 getattr(self, 'handle_' + target)(*args, **options)
54 def handle_to_students(self, *args, **options):
55 self.stdout.write('>>> Sending results to students')
56 subject = 'Wyniki II etapu Olimpiady Cyfrowej'
58 for participant in get_participants():
59 if options['only_to'] and participant.email != options['only_to']:
61 final_result = participant.score()
62 if final_result < minimum:
63 template = 'results_student_failed.txt'
65 template = 'results_student_passed.txt'
66 message = render_to_string('stage2/' + template, dict(final_result=final_result))
67 self.send_message(message, subject, participant.email)
71 def handle_to_teachers(self, *args, **options):
72 self.stdout.write('>>> Sending results to teachers')
73 subject = 'Wyniki II etapu Olimpiady Cyfrowej'
75 participants_by_contact = defaultdict(list)
77 for participant in get_participants():
78 if options['only_to'] and participant.contact.contact != options['only_to']:
80 participants_by_contact[participant.contact.contact].append(participant)
82 for contact_email, participants in participants_by_contact.items():
83 message = render_to_string('stage2/results_teacher.txt', dict(participants=participants))
84 self.send_message(message, subject, contact_email)
89 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
91 def send_message(self, message, subject, email):
92 self.stdout.write('>>> sending results to %s' % email)
94 send_mail(subject=subject, body=message, to=[email])
95 except BaseException, e:
97 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
100 self.stdout.write('message sent to: ' + email)