wtem prepared for the wlem exam
[edumed.git] / wtem / management / commands / wtem_send_results_csv.py
1 # -*- coding: utf-8 -*-
2
3 from optparse import make_option
4
5 from django.core.management.base import BaseCommand
6 from django.template.loader import render_to_string
7 from django.utils import translation
8
9 from wtem.management.commands import send_mail
10 from wtem.models import Submission
11
12
13 def get_submissions():
14     return sorted(Submission.objects.exclude(answers=None).all(), key=lambda s: -s.final_result)
15
16 minimum = 52
17
18
19 class Command(BaseCommand):
20     args = 'csv_filename'
21
22     option_list = BaseCommand.option_list + (
23         make_option(
24             '--to-teachers',
25             action='store_true',
26             dest='to_teachers',
27             default=False,
28             help='Send emails to teachers'),
29         make_option(
30             '--to-students',
31             action='store_true',
32             dest='to_students',
33             default=False,
34             help='Send emails to students'),
35         make_option(
36             '--only-to',
37             action='store',
38             dest='only_to',
39             default=None,
40             help='Send emails only to listed addresses'),
41     )
42
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']:
47             if options[target]:
48                 self.sent = 0
49                 self.failed = 0
50                 getattr(self, 'handle_' + target)(*args, **options)
51
52     def handle_to_students(self, *args, **options):
53         self.stdout.write('>>> Sending results to students')
54         subject = 'Wyniki II etapu Wielkiego Turnieju Edukacji Medialnej'
55
56         for email, last_name, first_name, final_result in self.results:
57             if options['only_to'] and email != options['only_to']:
58                 continue
59             if final_result == 'dyskwalifikacja':
60                 template = 'results_student_disqualified.txt'
61             elif float(final_result) < minimum:
62                 template = 'results_student_failed.txt'
63             else:
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)
67
68         self.sum_up()
69
70     def handle_to_teachers(self, *args, **options):
71         self.stdout.write('>>> Sending results to teachers')
72         subject = 'Wyniki II etapu Wielkiego Turnieju Edukacji Medialnej'
73
74         submissions_by_contact = dict()
75
76         from decimal import Decimal, InvalidOperation
77
78         def dec_or_0(s):
79             try:
80                 return Decimal(s)
81             except InvalidOperation:
82                 return Decimal(0)
83
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']:
89                 continue
90             submissions_by_contact.setdefault(teacher_email, []).append({
91                 'first_name': first_name,
92                 'last_name': last_name,
93                 'final_result': final_result,
94             })
95
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)
100
101         self.sum_up()
102
103     def sum_up(self):        
104         self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
105
106     def send_message(self, message, subject, email):
107         self.stdout.write('>>> sending results to %s' % email)
108         try:
109             send_mail(subject=subject, body=message, to=[email])
110         except BaseException, e:
111             self.failed += 1
112             self.stdout.write('failed sending to: ' + email + ': ' + str(e))
113         else:
114             self.sent += 1
115             self.stdout.write('message sent to: ' + email)