27e19122ea5913e0bf0a7b538f5056a8d1cefaa7
[edumed.git] / wtem / models.py
1 import random
2 import string
3 import os
4
5 from django.db import models
6 from django.contrib.auth.models import User
7 from django.core.exceptions import ValidationError
8 from django.utils import simplejson
9 from django.utils.translation import ugettext as _
10 from jsonfield import JSONField
11
12 from contact.models import Contact
13
14 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
15 exercises = simplejson.loads(f.read())
16 f.close()
17
18 DEBUG_KEY = '12345'
19
20 class Submission(models.Model):
21     contact = models.ForeignKey(Contact, null = True)
22     key = models.CharField(max_length = 30, unique = True)
23     first_name = models.CharField(max_length = 100)
24     last_name = models.CharField(max_length = 100)
25     email = models.EmailField(max_length = 100, unique = True)
26     answers = models.CharField(max_length = 65536, null = True, blank = True)
27     key_sent = models.BooleanField(default = False)
28     marks = JSONField()
29     examiners = models.ManyToManyField(User, null = True, blank = True)
30
31     def __unicode__(self):
32         return ', '.join((self.last_name, self.first_name, self.email))
33
34     @classmethod
35     def generate_key(cls):
36         key = ''
37         while not key or key in [record['key'] for record in cls.objects.values('key')]:
38             key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
39         return key
40
41     @classmethod
42     def create(cls, first_name, last_name, email, key = None, contact = None):
43         submission = cls(
44             contact = contact,
45             key = key if key else Submission.generate_key(),
46             first_name = first_name,
47             last_name = last_name,
48             email = email
49         )
50
51         submission.save()
52         return submission
53
54     def get_mark(self, user_id, exercise_id):
55         mark = None
56         user_id = str(user_id)
57         exercise_id = str(exercise_id)
58         if self.marks and user_id in self.marks:
59             mark = self.marks[user_id].get(exercise_id, None)
60         return mark
61
62     def set_mark(self, user_id, exercise_id, mark):
63         user_id = str(user_id)
64         exercise_id = str(exercise_id)
65         if not self.marks:
66             self.marks = dict()
67         
68         self.marks.setdefault(user_id, {})[exercise_id] = mark
69         if mark == 'None':
70             del self.marks[user_id][exercise_id]
71
72
73     def get_exercise_marks_by_examiner(self, exercise_id):
74         marks = dict()
75         for examiner_id, examiner_marks in self.marks.items():
76             mark = examiner_marks.get(exercise_id, None)
77             if mark is not None:
78                 marks[examiner_id] = mark
79         return marks
80
81     def get_final_exercise_mark(self, exercise_id):
82         exercise = exercises[int(exercise_id)-1]
83         if exercise_checked_manually(exercise):
84             marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
85             if len(marks_by_examiner):
86                 return max(map(int, marks_by_examiner.values()))
87             else:
88                 return None
89         else:
90             if not self.answers:
91                 return None
92             answer = simplejson.loads(self.answers)[exercise_id]['closed_part']
93             t = exercise['type']
94             if t == 'edumed_uporzadkuj':
95                 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
96             if t == 'edumed_przyporzadkuj':
97                 toret = 0
98                 for bucket_id, items in answer.items():
99                     for item_id in items:
100                         is_corect = False
101                         if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
102                             is_correct = int(bucket_id) in exercise['answer'].get(item_id)
103                         else:
104                             is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
105                         if is_correct:
106                             toret += exercise['points_per_hit']
107                 return toret
108             if t == 'edumed_wybor':
109                 if len(exercise['answer']) == 1:
110                     if len(answer) and int(answer[0]) == exercise['answer'][0]:
111                         return exercise['points']
112                     else:
113                         return 0
114                 else:
115                     toret = 0
116                     if exercise.get('answer_mode', None) == 'all_or_nothing':
117                         toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
118                     else:
119                         for id in map(int, answer):
120                             if id in exercise['answer']:
121                                 toret += exercise['points_per_hit']
122                     return toret
123             if t == 'edumed_prawdafalsz':
124                 toret = 0
125                 for idx, statement in enumerate(exercise['statements']):
126                     if answer[idx] == 'true':
127                         given = True
128                     elif answer[idx] == 'false':
129                         given = False
130                     else:
131                         given = None
132                     if given == statement[1]:
133                         toret += exercise['points_per_hit']
134                 return toret
135             raise NotImplementedError
136
137     @property
138     def final_result(self):
139         final = 0
140         for exercise_id in map(str,range(1, len(exercises) + 1)):
141             mark = self.get_final_exercise_mark(exercise_id)
142             if mark is not None:
143                 final += mark
144         return final
145
146     @property
147     def final_result_as_string(self):
148         return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
149
150 class Attachment(models.Model):
151     submission = models.ForeignKey(Submission)
152     exercise_id = models.IntegerField()
153     file = models.FileField(upload_to = 'wtem/attachment')
154
155
156 class Assignment(models.Model):
157     user = models.ForeignKey(User, unique = True)
158     exercises = JSONField()
159
160     def clean(self):
161         if not isinstance(self.exercises, list):
162             raise ValidationError(_('Assigned exercises must be declared in a list format'))
163         for exercise in self.exercises:
164             if not isinstance(exercise, int) or exercise < 1:
165                 raise ValidationError(_('Invalid exercise id: %s' % exercise))
166
167     def __unicode__(self):
168         return self.user.username + ': ' + ','.join(map(str,self.exercises))
169
170
171 def exercise_checked_manually(exercise):
172     return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise