1 # -*- coding: utf-8 -*-
3 from optparse import make_option
5 from django.core.management.base import BaseCommand
6 from django.conf import settings
7 from wtem.management.commands import send_mail
8 from django.utils import translation
9 from django.template.loader import render_to_string
11 from contact.models import Contact
12 from wtem.models import Submission
15 def get_submissions():
16 return sorted(Submission.objects.exclude(answers = None).all(), key=lambda s: -s.final_result)
20 class Command(BaseCommand):
23 option_list = BaseCommand.option_list + (
24 make_option('--to-teachers',
28 help='Send emails to teachers'),
29 make_option('--to-students',
33 help='Send emails to students'),
34 make_option('--only-to',
38 help='Send emails to students'),
41 def handle(self, csv_filename, *args, **options):
42 translation.activate('pl')
43 self.results = [line.decode('utf-8').strip('\n').split(',') for line in open(csv_filename)]
44 for target in ['to_teachers', 'to_students']:
48 getattr(self, 'handle_' + target)(*args, **options)
50 def handle_to_students(self, *args, **options):
51 self.stdout.write('>>> Sending results to students')
52 subject = 'Wyniki I etapu Wielkiego Turnieju Edukacji Medialnej'
54 for result in self.results:
55 if options['only_to'] and result[1] != options['only_to']:
57 final_result = result[4]
58 if result[5] != 'TAK':
59 template = 'results_student_failed.txt'
61 template = 'results_student_passed.txt'
62 message = render_to_string('wtem/' + template, dict(final_result=final_result))
63 self.send_message(message, subject, result[1])
67 def handle_to_teachers(self, *args, **options):
68 self.stdout.write('>>> Sending results to teachers')
69 subject = 'Wyniki I etapu Wielkiego Turnieju Edukacji Medialnej'
72 submissions_by_contact = dict()
74 from decimal import Decimal, InvalidOperation
78 except InvalidOperation:
81 for result in sorted(self.results, key=lambda r: dec_or_0(r[4]), reverse=True):
82 if options['only_to'] and result[3] != options['only_to']:
84 submissions_by_contact.setdefault(result[3], []).append({
85 'first_name': result[0].split()[0],
86 'last_name': result[0].split()[1],
87 'final_result': result[4],
90 for email, submissions in submissions_by_contact.items():
91 # contact = Contact.objects.get(id=contact_id)
92 message = render_to_string('wtem/results_teacher.txt', dict(submissions = submissions))
93 self.send_message(message, subject, email)
98 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
100 def send_message(self, message, subject, email):
101 self.stdout.write('>>> sending results to %s' % email)
108 except BaseException, e:
110 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
113 self.stdout.write('message sent to: ' + email)