new test + archived old test
[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_checked_manually(exercise):
173             marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
174             if len(marks_by_examiner):
175                 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
176             else:
177                 return None
178         else:
179             if not self.answers:
180                 return None
181             answers = json.loads(self.answers)
182             if exercise_id not in answers:
183                 return None
184             else:
185                 answer = answers[exercise_id]['closed_part']
186                 t = exercise['type']
187                 if t == 'edumed_uporzadkuj':
188                     return exercise['points'] if map(int, answer) == exercise['answer'] else 0
189                 elif t == 'edumed_przyporzadkuj':
190                     toret = 0
191                     for bucket_id, items in answer.items():
192                         for item_id in items:
193                             if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
194                                 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
195                             else:
196                                 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
197                             if is_correct:
198                                 toret += exercise['points_per_hit']
199                     return toret
200                 elif t == 'edumed_wybor':
201                     if exercise.get('answer_mode', None) == 'multi':
202                         if not answer:
203                             return None
204                         # return exercise['points'] if map(int, answer) == exercise['answer'] else 0
205                         correct = 0.
206                         for i in xrange(1, len(exercise['options']) + 1):
207                             if (str(i) in answer) == (i in exercise['answer']):
208                                 correct += 1
209                         points1 = exercise['points'] * correct/len(exercise['options'])
210                         points2 = exercise['points'] if map(int, answer) == exercise['answer'] else 0
211                         return points1 + points2
212                     elif len(exercise['answer']) == 1:
213                         if len(answer) and int(answer[0]) == exercise['answer'][0]:
214                             return exercise['points']
215                         else:
216                             return 0
217                     else:
218                         toret = 0
219                         if exercise.get('answer_mode', None) == 'all_or_nothing':
220                             toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
221                         else:
222                             # głupie i szkodliwe
223                             for answer_id in map(int, answer):
224                                 if answer_id in exercise['answer']:
225                                     toret += exercise['points_per_hit']
226                         return toret
227                 elif t == 'edumed_prawdafalsz':
228                     toret = 0
229                     for idx, statement in enumerate(exercise['statements']):
230                         if statement[1] == 'ignore':
231                             continue
232                         if answer[idx] == 'true':
233                             given = True
234                         elif answer[idx] == 'false':
235                             given = False
236                         else:
237                             given = None
238                         if given == statement[1]:
239                             toret += exercise['points_per_hit']
240                     return toret
241                 else:
242                     raise NotImplementedError
243
244     @property
245     def final_result(self):
246         final = 0
247         # for exercise_id in map(str,range(1, len(exercises) + 1)):
248         for exercise_id in [str(x['id']) for x in exercises]:
249             mark = self.get_final_exercise_mark(exercise_id)
250             if mark is not None:
251                 final += mark
252         return round(final, 2)
253
254     @property
255     def final_result_as_string(self):
256         return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
257
258
259 class Attachment(models.Model):
260     submission = models.ForeignKey(Submission)
261     exercise_id = models.IntegerField()
262     tag = models.CharField(max_length=128, null=True, blank=True)
263     file = models.FileField(upload_to='wtem/attachment')
264
265
266 class Assignment(models.Model):
267     user = models.ForeignKey(User, unique=True)
268     exercises = JSONField()
269
270     def clean(self):
271         if not isinstance(self.exercises, list):
272             raise ValidationError(_('Assigned exercises must be declared in a list format'))
273         # for exercise in self.exercises:
274         #     if not isinstance(exercise, int) or exercise < 1:
275         #         raise ValidationError(_('Invalid exercise id: %s' % exercise))
276
277     def __unicode__(self):
278         return self.user.username + ': ' + ','.join(map(str, self.exercises))
279
280
281 class AbstractConfirmation(models.Model):
282     contact = models.ForeignKey('contact.Contact', null=True)
283     key = models.CharField(max_length=30)
284     confirmed = models.BooleanField(default=False)
285
286     class Meta:
287         abstract = True
288
289     def readable_contact(self):
290         return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
291
292     def school_phone(self):
293         return '%s, tel. %s' % (self.contact.body.get('school'), self.contact.body.get('school_phone'))
294
295     def age(self):
296         return timezone.now() - self.contact.created_at
297
298     def readable_age(self):
299         td = self.age()
300         return '%s dni, %s godzin' % (td.days, td.seconds/3600)
301
302
303 class Confirmation(AbstractConfirmation):
304     first_name = models.CharField(max_length=100)
305     last_name = models.CharField(max_length=100)
306     email = models.EmailField(max_length=100, unique=True)
307
308     class Meta:
309         ordering = ['contact__contact']
310
311     @classmethod
312     def create(cls, first_name, last_name, email, contact=None, key=None):
313         confirmation = cls(
314             contact=contact,
315             key=key if key else make_key(30),
316             first_name=first_name,
317             last_name=last_name,
318             email=email
319         )
320
321         confirmation.save()
322         return confirmation
323
324     def absolute_url(self):
325         return reverse('student_confirmation', args=(self.id, self.key))
326
327     def send_mail(self):
328         mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
329         mail_body = render_to_string(
330             'contact/olimpiada/student_mail_body.html', {'confirmation': self})
331         try:
332             validate_email(self.email)
333         except ValidationError:
334             pass
335         else:
336             send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
337                       fail_silently=True)
338
339
340 class TeacherConfirmation(AbstractConfirmation):
341
342     class Meta:
343         ordering = ['contact__contact']
344
345     @classmethod
346     def create(cls, contact=None, key=None):
347         confirmation = cls(
348             contact=contact,
349             key=key if key else make_key(30),
350         )
351         confirmation.save()
352         return confirmation
353
354     def absolute_url(self):
355         return reverse('teacher_confirmation', args=(self.id, self.key))
356
357
358 def exercise_checked_manually(exercise):
359     return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise