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.html import format_html
12 from django.utils.translation import ugettext_lazy as _
13 from django.utils import timezone
14 from jsonfield import JSONField
16 from contact.models import Contact
19 class Participant(models.Model):
20 contact = models.ForeignKey(Contact, verbose_name=_('contact'), null=True)
21 key = models.CharField(_('key'), max_length=30, unique=True)
22 first_name = models.CharField(_('first name'), max_length=100)
23 last_name = models.CharField(_('last_name'), max_length=100)
24 email = models.EmailField(_('email'), max_length=100, unique=True)
25 key_sent = models.BooleanField(_('key sent'), default=False)
26 complete_set = models.BooleanField(default=False)
29 verbose_name = _('participant')
30 verbose_name_plural = _('participants')
32 def __unicode__(self):
33 return ', '.join((self.last_name, self.first_name, self.email))
35 # copy-paste from wtem
37 def generate_key(cls):
39 while not key or key in [record['key'] for record in cls.objects.values('key')]:
40 key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
44 # copy-paste from wtem
46 def create(cls, first_name, last_name, email, key=None, contact=None):
47 return cls.objects.create(
49 key=key if key else cls.generate_key(),
50 first_name=first_name,
55 return key == self.key
58 return sum(answer.score() for answer in self.answer_set.all())
61 class Assignment(models.Model):
62 title = models.CharField(_('title'), max_length=128)
63 content = models.TextField(_('content'))
64 content_url = models.URLField(_('URL'))
65 deadline = models.DateTimeField(_('deadline'))
66 max_points = models.IntegerField(_('max points'))
67 experts = models.ManyToManyField(
68 settings.AUTH_USER_MODEL, verbose_name=_('experts'), related_name='stage2_assignments')
69 arbiters = models.ManyToManyField(
70 settings.AUTH_USER_MODEL, blank=True, verbose_name=_('arbiters'), related_name='stage2_arbitrated')
71 supervisors = models.ManyToManyField(
72 settings.AUTH_USER_MODEL, verbose_name=_('supervisors'), related_name='stage2_supervised')
73 file_descriptions = JSONField(_('file descriptions'), default=[], blank=True)
74 field_descriptions = JSONField(_('field descriptions'), default=[], blank=True)
77 ordering = ['deadline', 'title']
78 verbose_name = _('assignment')
79 verbose_name_plural = _('assignments')
81 def __unicode__(self):
84 def available_answers(self, expert):
85 answers = self.answer_set.exclude(mark__expert=expert)
86 answers = answers.extra(where=[
87 "field_values::text ~ ': *\"[^\"]+\"' "
88 "OR EXISTS (SELECT id FROM stage2_attachment WHERE answer_id = stage2_answer.id) "
89 "OR EXISTS (SELECT id FROM stage2_fieldoption WHERE answer_id = stage2_answer.id)"])
90 if expert not in self.supervisors.all():
91 answers = answers.exclude(complete=True).filter(participant__complete_set=True)
92 if expert in self.arbiters.all():
93 answers = answers.filter(need_arbiter=True)
96 def field_counts(self, answers):
97 for field_desc in self.field_descriptions:
98 field_name, params = field_desc
99 if params['type'] == 'options':
100 field_count = FieldOption.objects.filter(answer__in=list(answers), set__name=params['option_set']).count()
102 field_count = sum(1 for answer in answers if answer.field_values.get(field_name))
103 yield field_name, field_count
106 return self.deadline >= timezone.now()
109 class Answer(models.Model):
110 participant = models.ForeignKey(Participant)
111 assignment = models.ForeignKey(Assignment)
112 field_values = JSONField(_('field values'), default={})
114 complete = models.BooleanField(default=False)
115 need_arbiter = models.BooleanField(default=False)
118 unique_together = ['participant', 'assignment']
121 for field_desc in self.assignment.field_descriptions:
122 field_name, params = field_desc
123 if params['type'] == 'options':
124 option = self.fieldoption_set.filter(set__name=params['option_set'])
125 value = option.get().value if option else '--------'
127 value = self.field_values.get(field_name, '')
128 if params['type'] == 'link':
129 value = format_html(u'<a href="{url}">{url}</a>', url=value)
130 yield field_name, value
132 def update_complete(self):
133 marks = self.mark_set.all()
137 elif len(marks) == 2:
139 complete = abs(mark1.points - mark2.points) < 0.2 * self.assignment.max_points
140 need_arbiter = not complete
144 self.complete = complete
145 self.need_arbiter = need_arbiter
149 marks = self.mark_set.all()
152 return self.mark_set.aggregate(avg=models.Avg('points'))['avg']
155 class FieldOptionSet(models.Model):
156 name = models.CharField(verbose_name=_('nazwa'), max_length=32, db_index=True)
159 verbose_name = _('option set')
160 verbose_name_plural = _('option sets')
162 def __unicode__(self):
165 def choices(self, answer):
166 return [('', '--------')] + [
167 (option.id, option.value)
168 for option in self.fieldoption_set.extra(
169 where=['answer_id is null or answer_id = %s'],
173 class FieldOption(models.Model):
174 set = models.ForeignKey(FieldOptionSet, verbose_name=_('zestaw'))
175 value = models.CharField(verbose_name=_('value'), max_length=255)
176 answer = models.ForeignKey(Answer, verbose_name=_('answer'), null=True, blank=True)
179 ordering = ['set', 'value']
180 verbose_name = _('option')
181 verbose_name_plural = _('options')
183 def __unicode__(self):
187 def attachment_path(instance, filename):
188 answer = instance.answer
189 return 'stage2/attachment/%s/%s/%s/%s' % (answer.participant_id, answer.assignment_id, instance.file_no, filename)
192 class Attachment(models.Model):
193 answer = models.ForeignKey(Answer)
194 file_no = models.IntegerField()
195 file = models.FileField(upload_to=attachment_path)
198 ordering = ['file_no']
201 return os.path.basename(self.file.name)
203 def download_url(self):
205 'stage2_participant_file',
206 args=(self.answer.assignment_id, self.file_no,
207 self.answer.participant_id, self.answer.participant.key))
209 def expert_download_url(self):
210 return reverse('stage2_expert_download', args=[self.id])
213 class Mark(models.Model):
214 expert = models.ForeignKey(settings.AUTH_USER_MODEL)
215 answer = models.ForeignKey(Answer)
216 points = models.DecimalField(verbose_name=_('points'), max_digits=3, decimal_places=1)
219 unique_together = ['expert', 'answer']
222 @receiver(post_save, sender=Mark, dispatch_uid='update_answer')
223 def update_answer(sender, **kwargs):
224 mark = kwargs['instance']
225 mark.answer.update_complete()