update email subject (key for stage 2)
[edumed.git] / stage2 / management / commands / stage2_send_keys.py
1 # -*- coding: utf-8 -*-
2
3 from optparse import make_option
4
5 from django.core.management.base import BaseCommand
6 from wtem.management.commands import send_mail
7 from django.template.loader import render_to_string
8
9 from stage2.models import Participant
10
11
12 class Command(BaseCommand):
13     help = 'Sends personalized links to WTEM contestants'
14     args = '<email_address1>, <email_address2>, ...'
15
16     option_list = BaseCommand.option_list + (
17         make_option(
18             '--all',
19             action='store_true',
20             dest='all',
21             default=False,
22             help='Use all available participants'),
23         make_option(
24             '--force',
25             action='store_true',
26             dest='force',
27             default=False,
28             help='Force sending key even if one was already sent')
29         )
30
31     def handle(self, *args, **options):
32         if len(args) or options['all']:
33             return self.send_keys(*args, **options)
34         self.stdout.write('No participants selected')
35
36     def send_keys(self, *args, **options):
37         sent = 0
38         failed = 0
39
40         participants = Participant.objects.all()
41         if not options['force']:
42             participants = participants.filter(key_sent=False)
43         if len(args):
44             participants = participants.filter(email__in=args)
45
46         for participant in participants:
47             assert len(participant.key) == 30
48
49             try:
50                 self.send_key(participant)
51             except Exception as e:
52                 failed += 1
53                 self.stdout.write('failed sending to: ' + participant.email + ' - ' + str(e))
54             else:
55                 participant.key_sent = True
56                 participant.save()
57                 sent += 1
58                 self.stdout.write('key sent to: ' + participant.email)
59
60         self.stdout.write('sent: ' + str(sent))
61
62     def send_key(self, participant):
63         self.stdout.write('>>> sending to ' + participant.email)
64         send_mail(
65             subject=u"II etap Olimpiady Cyfrowej – link do panelu",
66             body=render_to_string('stage2/email_key.txt', {'participant': participant}),
67             to=[participant.email])