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