removed @staticmethod's that cause errors
[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 = 55
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 to students'),
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 I etapu Wielkiego Turnieju Edukacji Medialnej'
55
56         for result in self.results:
57             if options['only_to'] and result[1] != options['only_to']:
58                 continue
59             final_result = result[4]
60             if result[5] != 'TAK':
61                 template = 'results_student_failed.txt'
62             else:
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])
66
67         self.sum_up()
68
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'
72
73         submissions_by_contact = dict()
74
75         from decimal import Decimal, InvalidOperation
76
77         def dec_or_0(s):
78             try:
79                 return Decimal(s)
80             except InvalidOperation:
81                 return Decimal(0)
82
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']:
85                 continue
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],
90             })
91
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)
96
97         self.sum_up()
98
99     def sum_up(self):        
100         self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
101
102     def send_message(self, message, subject, email):
103         self.stdout.write('>>> sending results to %s' % email)
104         try:
105             send_mail(subject=subject, body=message, to=[email])
106         except BaseException, e:
107             self.failed += 1
108             self.stdout.write('failed sending to: ' + email + ': ' + str(e))
109         else:
110             self.sent += 1
111             self.stdout.write('message sent to: ' + email)