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 to students'),
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 result in self.results:
57 if options['only_to'] and result[1] != options['only_to']:
59 final_result = result[4]
60 if result[5] != 'TAK':
61 template = 'results_student_failed.txt'
63 template = 'results_student_passed.txt'
64 message = render_to_string('wtem/' + template, dict(final_result=final_result))
65 self.send_message(message, subject, result[1])
69 def handle_to_teachers(self, *args, **options):
70 self.stdout.write('>>> Sending results to teachers')
71 subject = 'Wyniki I etapu Wielkiego Turnieju Edukacji Medialnej'
73 submissions_by_contact = dict()
75 from decimal import Decimal, InvalidOperation
80 except InvalidOperation:
83 for result in sorted(self.results, key=lambda r: dec_or_0(r[4]), reverse=True):
84 if options['only_to'] and result[3] != options['only_to']:
86 submissions_by_contact.setdefault(result[3], []).append({
87 'first_name': result[0].split()[0],
88 'last_name': result[0].split()[1],
89 'final_result': result[4],
92 for email, submissions in submissions_by_contact.items():
93 # contact = Contact.objects.get(id=contact_id)
94 message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions))
95 self.send_message(message, subject, email)
100 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
102 def send_message(self, message, subject, email):
103 self.stdout.write('>>> sending results to %s' % email)
105 send_mail(subject=subject, body=message, to=[email])
106 except BaseException, e:
108 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
111 self.stdout.write('message sent to: ' + email)