zmiana w menu na katalog.edukacjamedialna
[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(default={})
29     examiners = models.ManyToManyField(User, null = True, blank = True)
30     end_time = models.CharField(max_length = 5, null = True, blank = True)
31
32     def __unicode__(self):
33         return ', '.join((self.last_name, self.first_name, self.email))
34
35     @classmethod
36     def generate_key(cls):
37         key = ''
38         while not key or key in [record['key'] for record in cls.objects.values('key')]:
39             key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
40         return key
41
42     @classmethod
43     def create(cls, first_name, last_name, email, key = None, contact = None):
44         submission = cls(
45             contact = contact,
46             key = key if key else Submission.generate_key(),
47             first_name = first_name,
48             last_name = last_name,
49             email = email
50         )
51
52         submission.save()
53         return submission
54
55     def get_mark(self, user_id, exercise_id):
56         mark = None
57         user_id = str(user_id)
58         exercise_id = str(exercise_id)
59         if self.marks and user_id in self.marks:
60             mark = self.marks[user_id].get(exercise_id, None)
61         return mark
62
63     def set_mark(self, user_id, exercise_id, mark):
64         user_id = str(user_id)
65         exercise_id = str(exercise_id)
66         if not self.marks:
67             self.marks = dict()
68         
69         self.marks.setdefault(user_id, {})[exercise_id] = mark
70         if mark == 'None':
71             del self.marks[user_id][exercise_id]
72
73
74     def get_exercise_marks_by_examiner(self, exercise_id):
75         marks = dict()
76         for examiner_id, examiner_marks in self.marks.items():
77             mark = examiner_marks.get(exercise_id, None)
78             if mark is not None:
79                 marks[examiner_id] = mark
80         return marks
81
82     def get_final_exercise_mark(self, exercise_id):
83         #exercise = exercises[int(exercise_id)-1]
84         exercise = [e for e in exercises if str(e['id']) == str(exercise_id)][0]
85         if exercise_checked_manually(exercise):
86             marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
87             if len(marks_by_examiner):
88                 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
89             else:
90                 return None
91         else:
92             if not self.answers:
93                 return None
94             answer = simplejson.loads(self.answers)[exercise_id]['closed_part']
95             t = exercise['type']
96             if t == 'edumed_uporzadkuj':
97                 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
98             if t == 'edumed_przyporzadkuj':
99                 toret = 0
100                 for bucket_id, items in answer.items():
101                     for item_id in items:
102                         is_corect = False
103                         if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
104                             is_correct = int(bucket_id) in exercise['answer'].get(item_id)
105                         else:
106                             is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
107                         if is_correct:
108                             toret += exercise['points_per_hit']
109                 return toret
110             if t == 'edumed_wybor':
111                 if len(exercise['answer']) == 1:
112                     if len(answer) and int(answer[0]) == exercise['answer'][0]:
113                         return exercise['points']
114                     else:
115                         return 0
116                 else:
117                     toret = 0
118                     if exercise.get('answer_mode', None) == 'all_or_nothing':
119                         toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
120                     else:
121                         for id in map(int, answer):
122                             if id in exercise['answer']:
123                                 toret += exercise['points_per_hit']
124                     return toret
125             if t == 'edumed_prawdafalsz':
126                 toret = 0
127                 for idx, statement in enumerate(exercise['statements']):
128                     if answer[idx] == 'true':
129                         given = True
130                     elif answer[idx] == 'false':
131                         given = False
132                     else:
133                         given = None
134                     if given == statement[1]:
135                         toret += exercise['points_per_hit']
136                 return toret
137             raise NotImplementedError
138
139     @property
140     def final_result(self):
141         final = 0
142         #for exercise_id in map(str,range(1, len(exercises) + 1)):
143         for exercise_id in [str(x['id']) for x in exercises]:
144             mark = self.get_final_exercise_mark(exercise_id)
145             if mark is not None:
146                 final += mark
147         return final
148
149     @property
150     def final_result_as_string(self):
151         return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
152
153 class Attachment(models.Model):
154     submission = models.ForeignKey(Submission)
155     exercise_id = models.IntegerField()
156     tag = models.CharField(max_length=128, null=True, blank=True)
157     file = models.FileField(upload_to = 'wtem/attachment')
158
159
160 class Assignment(models.Model):
161     user = models.ForeignKey(User, unique = True)
162     exercises = JSONField()
163
164     def clean(self):
165         if not isinstance(self.exercises, list):
166             raise ValidationError(_('Assigned exercises must be declared in a list format'))
167         #for exercise in self.exercises:
168         #    if not isinstance(exercise, int) or exercise < 1:
169         #        raise ValidationError(_('Invalid exercise id: %s' % exercise))
170
171     def __unicode__(self):
172         return self.user.username + ': ' + ','.join(map(str,self.exercises))
173
174
175 def exercise_checked_manually(exercise):
176     return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise