updates for stage 2
[edumed.git] / wtem / models.py
1 # -*- coding: utf-8 -*-
2 import random
3 import string
4 import os
5 import json
6
7 from datetime import datetime
8
9 import pytz as pytz
10 from django.conf import settings
11 from django.core.validators import validate_email
12 from django.db import models
13 from django.contrib.auth.models import User
14 from django.core.exceptions import ValidationError
15 from django.core.mail import send_mail
16 from django.core.urlresolvers import reverse
17 from django.template.loader import render_to_string
18 from django.utils import timezone
19 from django.utils.translation import ugettext as _
20 from jsonfield import JSONField
21
22
23 def prepare_exercises():
24     f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
25     exercises = json.loads(f.read())
26     for i, exercise in enumerate(exercises, 1):
27         exercise['id'] = i
28         if exercise['type'] == 'edumed_wybor' and exercise['answer_mode'] == 'multi':
29             answer = []
30             for j, option in enumerate(exercise['options'], 1):
31                 option['id'] = j
32                 if option['answer']:
33                     answer.append(j)
34             exercise['answer'] = answer
35     f.close()
36     return exercises
37
38
39 exercises = prepare_exercises()
40
41 DEBUG_KEY = 'smerfetka159'
42
43 tz = pytz.timezone(settings.TIME_ZONE)
44
45
46 def get_exercise_by_id(exercise_id):
47     return [e for e in exercises if str(e['id']) == str(exercise_id)][0]
48
49
50 def make_key(length):
51     return ''.join(
52         random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
53         for i in range(length))
54
55
56 def tuple2dt(time_tuple):
57     return tz.localize(datetime(*time_tuple))
58
59
60 class CompetitionState(models.Model):
61     """singleton"""
62     BEFORE = 'before'
63     DURING = 'during'
64     AFTER = 'after'
65     STATE_CHOICES = (
66         (BEFORE, u'przed rozpoczęciem'),
67         (DURING, u'w trakcie'),
68         (AFTER, u'po zakończeniu'),
69     )
70     state = models.CharField(choices=STATE_CHOICES, max_length=16)
71
72     start = tuple2dt(settings.OLIMPIADA_START)
73     end = tuple2dt(settings.OLIMPIADA_END)
74
75     @classmethod
76     def get_state(cls):
77         now = timezone.now()
78         if now < cls.start:
79             return cls.BEFORE
80         elif now < cls.end:
81             return cls.DURING
82         else:
83             return cls.AFTER
84         # return cls.objects.get().state
85
86
87 class Submission(models.Model):
88     contact = models.ForeignKey('contact.Contact', null=True)
89     key = models.CharField(max_length=30, unique=True)
90     first_name = models.CharField(max_length=100)
91     last_name = models.CharField(max_length=100)
92     email = models.EmailField(max_length=100, unique=True)
93     answers = models.CharField(max_length=65536, null=True, blank=True)
94     key_sent = models.BooleanField(default=False)
95     opened_link = models.BooleanField(default=False)
96     marks = JSONField(default={})
97     examiners = models.ManyToManyField(User, null=True, blank=True)
98     end_time = models.CharField(max_length=5, null=True, blank=True)
99     random_seed = models.IntegerField()
100
101     def __unicode__(self):
102         return ', '.join((self.last_name, self.first_name, self.email))
103
104     @classmethod
105     def generate_key(cls):
106         key = ''
107         while not key or key in [record['key'] for record in cls.objects.values('key')]:
108             key = make_key(30)
109         return key
110
111     @classmethod
112     def create(cls, first_name, last_name, email, key=None, contact=None):
113         submission = cls(
114             contact=contact,
115             key=key if key else Submission.generate_key(),
116             first_name=first_name,
117             last_name=last_name,
118             email=email,
119             random_seed=random.randint(-2147483648, 2147483647)
120         )
121
122         submission.save()
123         return submission
124
125     def competition_link(self):
126         return reverse('form_single', kwargs={'submission_id': self.id, 'key': self.key})
127
128     def get_answers(self):
129         return json.loads(self.answers) if self.answers else {}
130
131     def shuffled_exercise_ids(self):
132         exercise_ids = [e['id'] for e in exercises]
133         seeded_random = random.Random(self.random_seed)
134         seeded_random.shuffle(exercise_ids)
135         return exercise_ids
136
137     def current_exercise(self):
138         answers = self.get_answers()
139         for i, id in enumerate(self.shuffled_exercise_ids(), 1):
140             if str(id) not in answers:
141                 return i, get_exercise_by_id(id)
142         return None, None
143
144     def get_mark(self, user_id, exercise_id):
145         mark = None
146         user_id = str(user_id)
147         exercise_id = str(exercise_id)
148         if self.marks and user_id in self.marks:
149             mark = self.marks[user_id].get(exercise_id, None)
150         return mark
151
152     def set_mark(self, user_id, exercise_id, mark):
153         user_id = str(user_id)
154         exercise_id = str(exercise_id)
155         if not self.marks:
156             self.marks = dict()
157         
158         self.marks.setdefault(user_id, {})[exercise_id] = mark
159         if mark == 'None':
160             del self.marks[user_id][exercise_id]
161
162     def get_exercise_marks_by_examiner(self, exercise_id):
163         marks = dict()
164         for examiner_id, examiner_marks in self.marks.items():
165             mark = examiner_marks.get(exercise_id, None)
166             if mark is not None:
167                 marks[examiner_id] = mark
168         return marks
169
170     def get_final_exercise_mark(self, exercise_id):
171         exercise = get_exercise_by_id(exercise_id)
172         if exercise.get('excluded'):
173             return 0
174         if exercise_checked_manually(exercise):
175             marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
176             if len(marks_by_examiner):
177                 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
178             else:
179                 return None
180         else:
181             if not self.answers:
182                 return None
183             answers = json.loads(self.answers)
184             if exercise_id not in answers:
185                 return None
186             else:
187                 answer = answers[exercise_id]['closed_part']
188                 t = exercise['type']
189                 if t == 'edumed_uporzadkuj':
190                     return exercise['points'] if map(int, answer) == exercise['answer'] else 0
191                 elif t == 'edumed_przyporzadkuj':
192                     toret = 0
193                     for bucket_id, items in answer.items():
194                         for item_id in items:
195                             if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
196                                 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
197                             else:
198                                 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
199                             if is_correct:
200                                 toret += exercise['points_per_hit']
201                     return toret
202                 elif t == 'edumed_wybor':
203                     if exercise.get('answer_mode', None) == 'multi':
204                         if not answer:
205                             return None
206                         # return exercise['points'] if map(int, answer) == exercise['answer'] else 0
207                         correct = 0.
208                         for i in xrange(1, len(exercise['options']) + 1):
209                             if (str(i) in answer) == (i in exercise['answer']):
210                                 correct += 1
211                         points1 = exercise['points'] * correct/len(exercise['options'])
212                         points2 = exercise['points'] if map(int, answer) == exercise['answer'] else 0
213                         return points1 + points2
214                     elif len(exercise['answer']) == 1:
215                         if len(answer) and int(answer[0]) == exercise['answer'][0]:
216                             return exercise['points']
217                         else:
218                             return 0
219                     else:
220                         toret = 0
221                         if exercise.get('answer_mode', None) == 'all_or_nothing':
222                             toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
223                         else:
224                             # głupie i szkodliwe
225                             for answer_id in map(int, answer):
226                                 if answer_id in exercise['answer']:
227                                     toret += exercise['points_per_hit']
228                         return toret
229                 elif t == 'edumed_prawdafalsz':
230                     toret = 0
231                     for idx, statement in enumerate(exercise['statements']):
232                         if statement[1] == 'ignore':
233                             continue
234                         if answer[idx] == 'true':
235                             given = True
236                         elif answer[idx] == 'false':
237                             given = False
238                         else:
239                             given = None
240                         if given == statement[1]:
241                             toret += exercise['points_per_hit']
242                     return toret
243                 else:
244                     raise NotImplementedError
245
246     @property
247     def final_result(self):
248         final = 0
249         # for exercise_id in map(str,range(1, len(exercises) + 1)):
250         for exercise_id in [str(x['id']) for x in exercises]:
251             mark = self.get_final_exercise_mark(exercise_id)
252             if mark is not None:
253                 final += mark
254         return round(final, 2)
255
256     @property
257     def final_result_as_string(self):
258         return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
259
260
261 class Attachment(models.Model):
262     submission = models.ForeignKey(Submission)
263     exercise_id = models.IntegerField()
264     tag = models.CharField(max_length=128, null=True, blank=True)
265     file = models.FileField(upload_to='wtem/attachment')
266
267
268 class Assignment(models.Model):
269     user = models.ForeignKey(User, unique=True)
270     exercises = JSONField()
271
272     def clean(self):
273         if not isinstance(self.exercises, list):
274             raise ValidationError(_('Assigned exercises must be declared in a list format'))
275         # for exercise in self.exercises:
276         #     if not isinstance(exercise, int) or exercise < 1:
277         #         raise ValidationError(_('Invalid exercise id: %s' % exercise))
278
279     def __unicode__(self):
280         return self.user.username + ': ' + ','.join(map(str, self.exercises))
281
282
283 class AbstractConfirmation(models.Model):
284     contact = models.ForeignKey('contact.Contact', null=True)
285     key = models.CharField(max_length=30)
286     confirmed = models.BooleanField(default=False)
287
288     class Meta:
289         abstract = True
290
291     def readable_contact(self):
292         return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
293
294     def school_phone(self):
295         return '%s, tel. %s' % (self.contact.body.get('school'), self.contact.body.get('school_phone'))
296
297     def age(self):
298         return timezone.now() - self.contact.created_at
299
300     def readable_age(self):
301         td = self.age()
302         return '%s dni, %s godzin' % (td.days, td.seconds/3600)
303
304
305 class Confirmation(AbstractConfirmation):
306     first_name = models.CharField(max_length=100)
307     last_name = models.CharField(max_length=100)
308     email = models.EmailField(max_length=100, unique=True)
309
310     class Meta:
311         ordering = ['contact__contact']
312
313     @classmethod
314     def create(cls, first_name, last_name, email, contact=None, key=None):
315         confirmation = cls(
316             contact=contact,
317             key=key if key else make_key(30),
318             first_name=first_name,
319             last_name=last_name,
320             email=email
321         )
322
323         confirmation.save()
324         return confirmation
325
326     def absolute_url(self):
327         return reverse('student_confirmation', args=(self.id, self.key))
328
329     def send_mail(self):
330         mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
331         mail_body = render_to_string(
332             'contact/olimpiada/student_mail_body.html', {'confirmation': self})
333         try:
334             validate_email(self.email)
335         except ValidationError:
336             pass
337         else:
338             send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
339                       fail_silently=True)
340
341
342 class TeacherConfirmation(AbstractConfirmation):
343
344     class Meta:
345         ordering = ['contact__contact']
346
347     @classmethod
348     def create(cls, contact=None, key=None):
349         confirmation = cls(
350             contact=contact,
351             key=key if key else make_key(30),
352         )
353         confirmation.save()
354         return confirmation
355
356     def absolute_url(self):
357         return reverse('teacher_confirmation', args=(self.id, self.key))
358
359
360 def exercise_checked_manually(exercise):
361     return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise