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