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 answer = json.loads(self.answers)[exercise_id]['closed_part']
170 if t == 'edumed_uporzadkuj':
171 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
172 if t == 'edumed_przyporzadkuj':
174 for bucket_id, items in answer.items():
175 for item_id in items:
177 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
178 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
180 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
182 toret += exercise['points_per_hit']
184 if t == 'edumed_wybor':
185 if len(exercise['answer']) == 1:
186 if len(answer) and int(answer[0]) == exercise['answer'][0]:
187 return exercise['points']
192 if exercise.get('answer_mode', None) == 'all_or_nothing':
193 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
195 for answer_id in map(int, answer):
196 if answer_id in exercise['answer']:
197 toret += exercise['points_per_hit']
199 if t == 'edumed_prawdafalsz':
201 for idx, statement in enumerate(exercise['statements']):
202 if statement[1] == 'ignore':
204 if answer[idx] == 'true':
206 elif answer[idx] == 'false':
210 if given == statement[1]:
211 toret += exercise['points_per_hit']
213 raise NotImplementedError
216 def final_result(self):
218 # for exercise_id in map(str,range(1, len(exercises) + 1)):
219 for exercise_id in [str(x['id']) for x in exercises]:
220 mark = self.get_final_exercise_mark(exercise_id)
226 def final_result_as_string(self):
227 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
230 class Attachment(models.Model):
231 submission = models.ForeignKey(Submission)
232 exercise_id = models.IntegerField()
233 tag = models.CharField(max_length=128, null=True, blank=True)
234 file = models.FileField(upload_to='wtem/attachment')
237 class Assignment(models.Model):
238 user = models.ForeignKey(User, unique=True)
239 exercises = JSONField()
242 if not isinstance(self.exercises, list):
243 raise ValidationError(_('Assigned exercises must be declared in a list format'))
244 # for exercise in self.exercises:
245 # if not isinstance(exercise, int) or exercise < 1:
246 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
248 def __unicode__(self):
249 return self.user.username + ': ' + ','.join(map(str, self.exercises))
252 class Confirmation(models.Model):
253 first_name = models.CharField(max_length=100)
254 last_name = models.CharField(max_length=100)
255 email = models.EmailField(max_length=100, unique=True)
256 contact = models.ForeignKey(Contact, null=True)
257 key = models.CharField(max_length=30)
258 confirmed = models.BooleanField(default=False)
261 ordering = ['contact__contact']
264 def create(cls, first_name, last_name, email, contact=None, key=None):
267 key=key if key else make_key(30),
268 first_name=first_name,
276 def absolute_url(self):
277 return reverse('student_confirmation', args=(self.id, self.key))
279 def readable_contact(self):
280 return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
282 def school_phone(self):
283 return '%s, tel. %s' % (self.contact.body.get('school'), self.contact.body.get('school_phone'))
286 return timezone.now() - self.contact.created_at
288 def readable_age(self):
290 return '%s dni, %s godzin' % (td.days, td.seconds/3600)
293 mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
294 mail_body = render_to_string(
295 'contact/olimpiada/student_mail_body.html', {'confirmation': self})
297 validate_email(self.email)
298 except ValidationError:
301 send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
305 def exercise_checked_manually(exercise):
306 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise