1 # -*- coding: utf-8 -*-
7 from datetime import datetime
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
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):
28 if exercise['type'] == 'edumed_wybor' and exercise['answer_mode'] == 'multi':
30 for j, option in enumerate(exercise['options'], 1):
34 exercise['answer'] = answer
39 exercises = prepare_exercises()
41 DEBUG_KEY = 'smerfetka159'
43 tz = pytz.timezone(settings.TIME_ZONE)
46 def get_exercise_by_id(exercise_id):
47 return [e for e in exercises if str(e['id']) == str(exercise_id)][0]
52 random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
53 for i in range(length))
56 def tuple2dt(time_tuple):
57 return tz.localize(datetime(*time_tuple))
60 class CompetitionState(models.Model):
66 (BEFORE, u'przed rozpoczęciem'),
67 (DURING, u'w trakcie'),
68 (AFTER, u'po zakończeniu'),
70 state = models.CharField(choices=STATE_CHOICES, max_length=16)
72 start = tuple2dt(settings.OLIMPIADA_START)
73 end = tuple2dt(settings.OLIMPIADA_END)
84 # return cls.objects.get().state
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()
101 def __unicode__(self):
102 return ', '.join((self.last_name, self.first_name, self.email))
105 def generate_key(cls):
107 while not key or key in [record['key'] for record in cls.objects.values('key')]:
112 def create(cls, first_name, last_name, email, key=None, contact=None):
115 key=key if key else Submission.generate_key(),
116 first_name=first_name,
119 random_seed=random.randint(-2147483648, 2147483647)
125 def competition_link(self):
126 return reverse('form_single', kwargs={'submission_id': self.id, 'key': self.key})
128 def get_answers(self):
129 return json.loads(self.answers) if self.answers else {}
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)
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)
144 def get_mark(self, user_id, exercise_id):
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)
152 def set_mark(self, user_id, exercise_id, mark):
153 user_id = str(user_id)
154 exercise_id = str(exercise_id)
158 self.marks.setdefault(user_id, {})[exercise_id] = mark
160 del self.marks[user_id][exercise_id]
162 def get_exercise_marks_by_examiner(self, exercise_id):
164 for examiner_id, examiner_marks in self.marks.items():
165 mark = examiner_marks.get(exercise_id, None)
167 marks[examiner_id] = mark
170 def get_final_exercise_mark(self, exercise_id):
171 exercise = get_exercise_by_id(exercise_id)
172 if exercise.get('excluded'):
174 if exercise_checked_manually(exercise):
175 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
176 if len(marks_by_examiner):
177 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
183 answers = json.loads(self.answers)
184 if exercise_id not in answers:
187 answer = answers[exercise_id]['closed_part']
189 if t == 'edumed_uporzadkuj':
190 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
191 elif t == 'edumed_przyporzadkuj':
193 for bucket_id, items in answer.items():
194 for item_id in items:
195 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
196 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
198 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
200 toret += exercise['points_per_hit']
202 elif t == 'edumed_wybor':
203 if exercise.get('answer_mode', None) == 'multi':
206 # return exercise['points'] if map(int, answer) == exercise['answer'] else 0
208 for i in xrange(1, len(exercise['options']) + 1):
209 if (str(i) in answer) == (i in exercise['answer']):
211 points1 = exercise['points'] * correct/len(exercise['options'])
212 points2 = exercise['points'] if map(int, answer) == exercise['answer'] else 0
213 return points1 + points2
214 elif len(exercise['answer']) == 1:
215 if len(answer) and int(answer[0]) == exercise['answer'][0]:
216 return exercise['points']
221 if exercise.get('answer_mode', None) == 'all_or_nothing':
222 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
225 for answer_id in map(int, answer):
226 if answer_id in exercise['answer']:
227 toret += exercise['points_per_hit']
229 elif t == 'edumed_prawdafalsz':
231 for idx, statement in enumerate(exercise['statements']):
232 if statement[1] == 'ignore':
234 if answer[idx] == 'true':
236 elif answer[idx] == 'false':
240 if given == statement[1]:
241 toret += exercise['points_per_hit']
244 raise NotImplementedError
247 def final_result(self):
249 # for exercise_id in map(str,range(1, len(exercises) + 1)):
250 for exercise_id in [str(x['id']) for x in exercises]:
251 mark = self.get_final_exercise_mark(exercise_id)
254 return round(final, 2)
257 def final_result_as_string(self):
258 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
261 class Attachment(models.Model):
262 submission = models.ForeignKey(Submission)
263 exercise_id = models.IntegerField()
264 tag = models.CharField(max_length=128, null=True, blank=True)
265 file = models.FileField(upload_to='wtem/attachment')
268 class Assignment(models.Model):
269 user = models.ForeignKey(User, unique=True)
270 exercises = JSONField()
273 if not isinstance(self.exercises, list):
274 raise ValidationError(_('Assigned exercises must be declared in a list format'))
275 # for exercise in self.exercises:
276 # if not isinstance(exercise, int) or exercise < 1:
277 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
279 def __unicode__(self):
280 return self.user.username + ': ' + ','.join(map(str, self.exercises))
283 class AbstractConfirmation(models.Model):
284 contact = models.ForeignKey('contact.Contact', null=True)
285 key = models.CharField(max_length=30)
286 confirmed = models.BooleanField(default=False)
291 def readable_contact(self):
292 return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
294 def school_phone(self):
295 return '%s, tel. %s' % (self.contact.body.get('school'), self.contact.body.get('school_phone'))
298 return timezone.now() - self.contact.created_at
300 def readable_age(self):
302 return '%s dni, %s godzin' % (td.days, td.seconds/3600)
305 class Confirmation(AbstractConfirmation):
306 first_name = models.CharField(max_length=100)
307 last_name = models.CharField(max_length=100)
308 email = models.EmailField(max_length=100, unique=True)
311 ordering = ['contact__contact']
314 def create(cls, first_name, last_name, email, contact=None, key=None):
317 key=key if key else make_key(30),
318 first_name=first_name,
326 def absolute_url(self):
327 return reverse('student_confirmation', args=(self.id, self.key))
330 mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
331 mail_body = render_to_string(
332 'contact/olimpiada/student_mail_body.html', {'confirmation': self})
334 validate_email(self.email)
335 except ValidationError:
338 send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
342 class TeacherConfirmation(AbstractConfirmation):
345 ordering = ['contact__contact']
348 def create(cls, contact=None, key=None):
351 key=key if key else make_key(30),
356 def absolute_url(self):
357 return reverse('teacher_confirmation', args=(self.id, self.key))
360 def exercise_checked_manually(exercise):
361 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise