1 # -*- coding: utf-8 -*-
3 from optparse import make_option
5 from django.core.management.base import BaseCommand
6 from django.template.loader import render_to_string
7 from django.utils import translation
9 from wtem.management.commands import send_mail
10 from wtem.models import Submission
13 def get_submissions():
14 return sorted(Submission.objects.exclude(answers=None).all(), key=lambda s: -s.final_result)
19 class Command(BaseCommand):
22 option_list = BaseCommand.option_list + (
28 help='Send emails to teachers'),
34 help='Send emails to students'),
40 help='Send emails only to listed addresses'),
43 def handle(self, csv_filename, *args, **options):
44 translation.activate('pl')
45 self.results = [line.decode('utf-8').strip('\n').split(',') for line in open(csv_filename)]
46 for target in ['to_teachers', 'to_students']:
50 getattr(self, 'handle_' + target)(*args, **options)
52 def handle_to_students(self, *args, **options):
53 self.stdout.write('>>> Sending results to students')
54 subject = 'Wyniki I etapu Wielkiego Turnieju Edukacji Medialnej'
56 for email, last_name, first_name, final_result in self.results:
57 if options['only_to'] and email != options['only_to']:
59 if final_result == 'dyskwalifikacja':
60 template = 'results_student_disqualified.txt'
61 elif float(final_result) < minimum:
62 template = 'results_student_failed.txt'
64 template = 'results_student_passed.txt'
65 message = render_to_string('wtem/' + template, dict(final_result=final_result))
66 self.send_message(message, subject, email)
70 def handle_to_teachers(self, *args, **options):
71 self.stdout.write('>>> Sending results to teachers')
72 subject = 'Wyniki I etapu Wielkiego Turnieju Edukacji Medialnej'
74 submissions_by_contact = dict()
76 from decimal import Decimal, InvalidOperation
81 except InvalidOperation:
84 sorted_results = sorted(self.results, key=lambda r: dec_or_0(r[3]), reverse=True)
85 for email, last_name, first_name, final_result in sorted_results:
86 submission = Submission.objects.get(email=email)
87 teacher_email = submission.contact.contact
88 if options['only_to'] and teacher_email != options['only_to']:
90 submissions_by_contact.setdefault(teacher_email, []).append({
91 'first_name': first_name,
92 'last_name': last_name,
93 'final_result': final_result,
96 for email, submissions in submissions_by_contact.items():
97 # contact = Contact.objects.get(id=contact_id)
98 message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions))
99 self.send_message(message, subject, email)
104 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
106 def send_message(self, message, subject, email):
107 self.stdout.write('>>> sending results to %s' % email)
109 send_mail(subject=subject, body=message, to=[email])
110 except BaseException, e:
112 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
115 self.stdout.write('message sent to: ' + email)