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
22 from contact.models import Contact
24 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
25 exercises = json.loads(f.read())
28 DEBUG_KEY = 'smerfetka159'
30 tz = pytz.timezone(settings.TIME_ZONE)
33 def get_exercise_by_id(exercise_id):
34 return [e for e in exercises if str(e['id']) == str(exercise_id)][0]
39 random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
40 for i in range(length))
43 def tuple2dt(time_tuple):
44 return tz.localize(datetime(*time_tuple))
47 class CompetitionState(models.Model):
53 (BEFORE, u'przed rozpoczęciem'),
54 (DURING, u'w trakcie'),
55 (AFTER, u'po zakończeniu'),
57 state = models.CharField(choices=STATE_CHOICES, max_length=16)
59 start = tuple2dt(settings.OLIMPIADA_START)
60 end = tuple2dt(settings.OLIMPIADA_END)
71 # return cls.objects.get().state
74 class Submission(models.Model):
75 contact = models.ForeignKey(Contact, null=True)
76 key = models.CharField(max_length=30, unique=True)
77 first_name = models.CharField(max_length=100)
78 last_name = models.CharField(max_length=100)
79 email = models.EmailField(max_length=100, unique=True)
80 answers = models.CharField(max_length=65536, null=True, blank=True)
81 key_sent = models.BooleanField(default=False)
82 opened_link = models.BooleanField(default=False)
83 marks = JSONField(default={})
84 examiners = models.ManyToManyField(User, null=True, blank=True)
85 end_time = models.CharField(max_length=5, null=True, blank=True)
86 random_seed = models.IntegerField()
88 def __unicode__(self):
89 return ', '.join((self.last_name, self.first_name, self.email))
92 def generate_key(cls):
94 while not key or key in [record['key'] for record in cls.objects.values('key')]:
99 def create(cls, first_name, last_name, email, key=None, contact=None):
102 key=key if key else Submission.generate_key(),
103 first_name=first_name,
106 random_seed=random.randint(-2147483648, 2147483647)
112 def competition_link(self):
113 return reverse('form_single', kwargs={'submission_id': self.id, 'key': self.key})
115 def get_answers(self):
116 return json.loads(self.answers) if self.answers else {}
118 def shuffled_exercise_ids(self):
119 exercise_ids = [e['id'] for e in exercises]
120 seeded_random = random.Random(self.random_seed)
121 seeded_random.shuffle(exercise_ids)
124 def current_exercise(self):
125 answers = self.get_answers()
126 for i, id in enumerate(self.shuffled_exercise_ids(), 1):
127 if str(id) not in answers:
128 return i, get_exercise_by_id(id)
131 def get_mark(self, user_id, exercise_id):
133 user_id = str(user_id)
134 exercise_id = str(exercise_id)
135 if self.marks and user_id in self.marks:
136 mark = self.marks[user_id].get(exercise_id, None)
139 def set_mark(self, user_id, exercise_id, mark):
140 user_id = str(user_id)
141 exercise_id = str(exercise_id)
145 self.marks.setdefault(user_id, {})[exercise_id] = mark
147 del self.marks[user_id][exercise_id]
149 def get_exercise_marks_by_examiner(self, exercise_id):
151 for examiner_id, examiner_marks in self.marks.items():
152 mark = examiner_marks.get(exercise_id, None)
154 marks[examiner_id] = mark
157 def get_final_exercise_mark(self, exercise_id):
158 exercise = get_exercise_by_id(exercise_id)
159 if exercise_checked_manually(exercise):
160 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
161 if len(marks_by_examiner):
162 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
168 answers = json.loads(self.answers)
169 if exercise_id not in answers:
172 answer = answers[exercise_id]['closed_part']
174 if t == 'edumed_uporzadkuj':
175 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
176 elif t == 'edumed_przyporzadkuj':
178 for bucket_id, items in answer.items():
179 for item_id in items:
180 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
181 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
183 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
185 toret += exercise['points_per_hit']
187 elif t == 'edumed_wybor':
188 if exercise.get('answer_mode', None) == 'multi':
191 # return exercise['points'] if map(int, answer) == exercise['answer'] else 0
193 for i in xrange(1, len(exercise['options']) + 1):
194 if (str(i) in answer) == (i in exercise['answer']):
196 points1 = exercise['points'] * correct/len(exercise['options'])
197 points2 = exercise['points'] if map(int, answer) == exercise['answer'] else 0
198 return points1 + points2
199 elif len(exercise['answer']) == 1:
200 if len(answer) and int(answer[0]) == exercise['answer'][0]:
201 return exercise['points']
206 if exercise.get('answer_mode', None) == 'all_or_nothing':
207 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
210 for answer_id in map(int, answer):
211 if answer_id in exercise['answer']:
212 toret += exercise['points_per_hit']
214 elif t == 'edumed_prawdafalsz':
216 for idx, statement in enumerate(exercise['statements']):
217 if statement[1] == 'ignore':
219 if answer[idx] == 'true':
221 elif answer[idx] == 'false':
225 if given == statement[1]:
226 toret += exercise['points_per_hit']
229 raise NotImplementedError
232 def final_result(self):
234 # for exercise_id in map(str,range(1, len(exercises) + 1)):
235 for exercise_id in [str(x['id']) for x in exercises]:
236 mark = self.get_final_exercise_mark(exercise_id)
239 return round(final, 2)
242 def final_result_as_string(self):
243 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
246 class Attachment(models.Model):
247 submission = models.ForeignKey(Submission)
248 exercise_id = models.IntegerField()
249 tag = models.CharField(max_length=128, null=True, blank=True)
250 file = models.FileField(upload_to='wtem/attachment')
253 class Assignment(models.Model):
254 user = models.ForeignKey(User, unique=True)
255 exercises = JSONField()
258 if not isinstance(self.exercises, list):
259 raise ValidationError(_('Assigned exercises must be declared in a list format'))
260 # for exercise in self.exercises:
261 # if not isinstance(exercise, int) or exercise < 1:
262 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
264 def __unicode__(self):
265 return self.user.username + ': ' + ','.join(map(str, self.exercises))
268 class Confirmation(models.Model):
269 first_name = models.CharField(max_length=100)
270 last_name = models.CharField(max_length=100)
271 email = models.EmailField(max_length=100, unique=True)
272 contact = models.ForeignKey(Contact, null=True)
273 key = models.CharField(max_length=30)
274 confirmed = models.BooleanField(default=False)
277 ordering = ['contact__contact']
280 def create(cls, first_name, last_name, email, contact=None, key=None):
283 key=key if key else make_key(30),
284 first_name=first_name,
292 def absolute_url(self):
293 return reverse('student_confirmation', args=(self.id, self.key))
295 def readable_contact(self):
296 return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
298 def school_phone(self):
299 return '%s, tel. %s' % (self.contact.body.get('school'), self.contact.body.get('school_phone'))
302 return timezone.now() - self.contact.created_at
304 def readable_age(self):
306 return '%s dni, %s godzin' % (td.days, td.seconds/3600)
309 mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
310 mail_body = render_to_string(
311 'contact/olimpiada/student_mail_body.html', {'confirmation': self})
313 validate_email(self.email)
314 except ValidationError:
317 send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
321 def exercise_checked_manually(exercise):
322 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise