1 # -*- coding: utf-8 -*-
6 from django.conf import settings
7 from django.core.urlresolvers import reverse
8 from django.db import models
9 from django.db.models.signals import post_save
10 from django.dispatch import receiver
11 from django.utils.translation import ugettext_lazy as _
12 from django.utils import timezone
13 from jsonfield import JSONField
15 from contact.models import Contact
18 class Participant(models.Model):
19 contact = models.ForeignKey(Contact, verbose_name=_('contact'), null=True)
20 key = models.CharField(_('key'), max_length=30, unique=True)
21 first_name = models.CharField(_('first name'), max_length=100)
22 last_name = models.CharField(_('last_name'), max_length=100)
23 email = models.EmailField(_('email'), max_length=100, unique=True)
24 key_sent = models.BooleanField(_('key sent'), default=False)
25 complete_set = models.BooleanField(default=False)
28 verbose_name = _('participant')
29 verbose_name_plural = _('participants')
31 def __unicode__(self):
32 return ', '.join((self.last_name, self.first_name, self.email))
34 # copy-paste from wtem
36 def generate_key(cls):
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)
43 # copy-paste from wtem
45 def create(cls, first_name, last_name, email, key=None, contact=None):
46 return cls.objects.create(
48 key=key if key else cls.generate_key(),
49 first_name=first_name,
54 return key == self.key
57 return sum(answer.score() for answer in self.answer_set.all())
60 class Assignment(models.Model):
61 title = models.CharField(_('title'), max_length=128)
62 content = models.TextField(_('content'))
63 content_url = models.URLField(_('URL'))
64 deadline = models.DateTimeField(_('deadline'))
65 max_points = models.IntegerField(_('max points'))
66 experts = models.ManyToManyField(
67 settings.AUTH_USER_MODEL, verbose_name=_('experts'), related_name='stage2_assignments')
68 arbiters = models.ManyToManyField(
69 settings.AUTH_USER_MODEL, blank=True, verbose_name=_('arbiters'), related_name='stage2_arbitrated')
70 supervisors = models.ManyToManyField(
71 settings.AUTH_USER_MODEL, verbose_name=_('supervisors'), related_name='stage2_supervised')
72 file_descriptions = JSONField(_('file descriptions'), default=[], blank=True)
73 field_descriptions = JSONField(_('field descriptions'), default=[], blank=True)
76 ordering = ['deadline', 'title']
77 verbose_name = _('assignment')
78 verbose_name_plural = _('assignments')
80 def __unicode__(self):
83 def available_answers(self, expert):
84 answers = self.answer_set.exclude(mark__expert=expert)
85 answers = answers.extra(where=[
86 "field_values::text ~ ': *\"[^\"]+\"' "
87 "OR EXISTS (SELECT id FROM stage2_attachment WHERE answer_id = stage2_answer.id) "
88 "OR EXISTS (SELECT id FROM stage2_fieldoption WHERE answer_id = stage2_answer.id)"])
89 if expert not in self.supervisors.all():
90 answers = answers.exclude(complete=True).filter(participant__complete_set=True)
91 if expert in self.arbiters.all():
92 answers = answers.filter(need_arbiter=True)
96 return self.deadline >= timezone.now()
99 class Answer(models.Model):
100 participant = models.ForeignKey(Participant)
101 assignment = models.ForeignKey(Assignment)
102 field_values = JSONField(_('field values'), default={})
104 complete = models.BooleanField(default=False)
105 need_arbiter = models.BooleanField(default=False)
108 unique_together = ['participant', 'assignment']
111 for field_desc in self.assignment.field_descriptions:
112 field_name, params = field_desc
113 if params['type'] == 'text':
114 yield (field_name, self.field_values.get(field_name, ''))
116 option = self.fieldoption_set.filter(set__name=params['option_set'])
117 yield (field_name, option.get().value if option else '--------')
119 def update_complete(self):
120 marks = self.mark_set.all()
124 elif len(marks) == 2:
126 complete = abs(mark1.points - mark2.points) < 0.2 * self.assignment.max_points
127 need_arbiter = not complete
131 self.complete = complete
132 self.need_arbiter = need_arbiter
136 marks = self.mark_set.all()
139 return self.mark_set.aggregate(avg=models.Avg('points'))['avg']
142 class FieldOptionSet(models.Model):
143 name = models.CharField(verbose_name=_('nazwa'), max_length=32, db_index=True)
146 verbose_name = _('option set')
147 verbose_name_plural = _('option sets')
149 def __unicode__(self):
152 def choices(self, answer):
153 return [('', '--------')] + [
154 (option.id, option.value)
155 for option in self.fieldoption_set.extra(
156 where=['answer_id is null or answer_id = %s'],
160 class FieldOption(models.Model):
161 set = models.ForeignKey(FieldOptionSet, verbose_name=_('zestaw'))
162 value = models.CharField(verbose_name=_('value'), max_length=255)
163 answer = models.ForeignKey(Answer, verbose_name=_('answer'), null=True, blank=True)
166 ordering = ['set', 'value']
167 verbose_name = _('option')
168 verbose_name_plural = _('options')
170 def __unicode__(self):
174 def attachment_path(instance, filename):
175 answer = instance.answer
176 return 'stage2/attachment/%s/%s/%s/%s' % (answer.participant_id, answer.assignment_id, instance.file_no, filename)
179 class Attachment(models.Model):
180 answer = models.ForeignKey(Answer)
181 file_no = models.IntegerField()
182 file = models.FileField(upload_to=attachment_path)
185 ordering = ['file_no']
188 return os.path.basename(self.file.name)
190 def download_url(self):
192 'stage2_participant_file',
193 args=(self.answer.assignment_id, self.file_no,
194 self.answer.participant_id, self.answer.participant.key))
196 def expert_download_url(self):
197 return reverse('stage2_expert_download', args=[self.id])
200 class Mark(models.Model):
201 expert = models.ForeignKey(settings.AUTH_USER_MODEL)
202 answer = models.ForeignKey(Answer)
203 points = models.DecimalField(verbose_name=_('points'), max_digits=3, decimal_places=1)
206 unique_together = ['expert', 'answer']
209 @receiver(post_save, sender=Mark, dispatch_uid='update_answer')
210 def update_answer(sender, **kwargs):
211 mark = kwargs['instance']
212 mark.answer.update_complete()