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_checked_manually(exercise):
173 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
174 if len(marks_by_examiner):
175 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
181 answers = json.loads(self.answers)
182 if exercise_id not in answers:
185 answer = answers[exercise_id]['closed_part']
187 if t == 'edumed_uporzadkuj':
188 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
189 elif t == 'edumed_przyporzadkuj':
191 for bucket_id, items in answer.items():
192 for item_id in items:
193 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
194 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
196 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
198 toret += exercise['points_per_hit']
200 elif t == 'edumed_wybor':
201 if exercise.get('answer_mode', None) == 'multi':
204 # return exercise['points'] if map(int, answer) == exercise['answer'] else 0
206 for i in xrange(1, len(exercise['options']) + 1):
207 if (str(i) in answer) == (i in exercise['answer']):
209 points1 = exercise['points'] * correct/len(exercise['options'])
210 points2 = exercise['points'] if map(int, answer) == exercise['answer'] else 0
211 return points1 + points2
212 elif len(exercise['answer']) == 1:
213 if len(answer) and int(answer[0]) == exercise['answer'][0]:
214 return exercise['points']
219 if exercise.get('answer_mode', None) == 'all_or_nothing':
220 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
223 for answer_id in map(int, answer):
224 if answer_id in exercise['answer']:
225 toret += exercise['points_per_hit']
227 elif t == 'edumed_prawdafalsz':
229 for idx, statement in enumerate(exercise['statements']):
230 if statement[1] == 'ignore':
232 if answer[idx] == 'true':
234 elif answer[idx] == 'false':
238 if given == statement[1]:
239 toret += exercise['points_per_hit']
242 raise NotImplementedError
245 def final_result(self):
247 # for exercise_id in map(str,range(1, len(exercises) + 1)):
248 for exercise_id in [str(x['id']) for x in exercises]:
249 mark = self.get_final_exercise_mark(exercise_id)
252 return round(final, 2)
255 def final_result_as_string(self):
256 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
259 class Attachment(models.Model):
260 submission = models.ForeignKey(Submission)
261 exercise_id = models.IntegerField()
262 tag = models.CharField(max_length=128, null=True, blank=True)
263 file = models.FileField(upload_to='wtem/attachment')
266 class Assignment(models.Model):
267 user = models.ForeignKey(User, unique=True)
268 exercises = JSONField()
271 if not isinstance(self.exercises, list):
272 raise ValidationError(_('Assigned exercises must be declared in a list format'))
273 # for exercise in self.exercises:
274 # if not isinstance(exercise, int) or exercise < 1:
275 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
277 def __unicode__(self):
278 return self.user.username + ': ' + ','.join(map(str, self.exercises))
281 class AbstractConfirmation(models.Model):
282 contact = models.ForeignKey('contact.Contact', null=True)
283 key = models.CharField(max_length=30)
284 confirmed = models.BooleanField(default=False)
289 def readable_contact(self):
290 return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
292 def school_phone(self):
293 return '%s, tel. %s' % (self.contact.body.get('school'), self.contact.body.get('school_phone'))
296 return timezone.now() - self.contact.created_at
298 def readable_age(self):
300 return '%s dni, %s godzin' % (td.days, td.seconds/3600)
303 class Confirmation(AbstractConfirmation):
304 first_name = models.CharField(max_length=100)
305 last_name = models.CharField(max_length=100)
306 email = models.EmailField(max_length=100, unique=True)
309 ordering = ['contact__contact']
312 def create(cls, first_name, last_name, email, contact=None, key=None):
315 key=key if key else make_key(30),
316 first_name=first_name,
324 def absolute_url(self):
325 return reverse('student_confirmation', args=(self.id, self.key))
328 mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
329 mail_body = render_to_string(
330 'contact/olimpiada/student_mail_body.html', {'confirmation': self})
332 validate_email(self.email)
333 except ValidationError:
336 send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
340 class TeacherConfirmation(AbstractConfirmation):
343 ordering = ['contact__contact']
346 def create(cls, contact=None, key=None):
349 key=key if key else make_key(30),
354 def absolute_url(self):
355 return reverse('teacher_confirmation', args=(self.id, self.key))
358 def exercise_checked_manually(exercise):
359 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise