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)
97 return self.deadline >= timezone.now()
100 class Answer(models.Model):
101 participant = models.ForeignKey(Participant)
102 assignment = models.ForeignKey(Assignment)
103 field_values = JSONField(_('field values'), default={})
105 complete = models.BooleanField(default=False)
106 need_arbiter = models.BooleanField(default=False)
109 unique_together = ['participant', 'assignment']
112 for field_desc in self.assignment.field_descriptions:
113 field_name, params = field_desc
114 if params['type'] == 'options':
115 option = self.fieldoption_set.filter(set__name=params['option_set'])
116 value = option.get().value if option else '--------'
118 value = self.field_values.get(field_name, '')
119 if params['type'] == 'link':
120 value = format_html(u'<a href="{url}">{url}</a>', url=value)
121 yield (field_name, value)
123 def update_complete(self):
124 marks = self.mark_set.all()
128 elif len(marks) == 2:
130 complete = abs(mark1.points - mark2.points) < 0.2 * self.assignment.max_points
131 need_arbiter = not complete
135 self.complete = complete
136 self.need_arbiter = need_arbiter
140 marks = self.mark_set.all()
143 return self.mark_set.aggregate(avg=models.Avg('points'))['avg']
146 class FieldOptionSet(models.Model):
147 name = models.CharField(verbose_name=_('nazwa'), max_length=32, db_index=True)
150 verbose_name = _('option set')
151 verbose_name_plural = _('option sets')
153 def __unicode__(self):
156 def choices(self, answer):
157 return [('', '--------')] + [
158 (option.id, option.value)
159 for option in self.fieldoption_set.extra(
160 where=['answer_id is null or answer_id = %s'],
164 class FieldOption(models.Model):
165 set = models.ForeignKey(FieldOptionSet, verbose_name=_('zestaw'))
166 value = models.CharField(verbose_name=_('value'), max_length=255)
167 answer = models.ForeignKey(Answer, verbose_name=_('answer'), null=True, blank=True)
170 ordering = ['set', 'value']
171 verbose_name = _('option')
172 verbose_name_plural = _('options')
174 def __unicode__(self):
178 def attachment_path(instance, filename):
179 answer = instance.answer
180 return 'stage2/attachment/%s/%s/%s/%s' % (answer.participant_id, answer.assignment_id, instance.file_no, filename)
183 class Attachment(models.Model):
184 answer = models.ForeignKey(Answer)
185 file_no = models.IntegerField()
186 file = models.FileField(upload_to=attachment_path)
189 ordering = ['file_no']
192 return os.path.basename(self.file.name)
194 def download_url(self):
196 'stage2_participant_file',
197 args=(self.answer.assignment_id, self.file_no,
198 self.answer.participant_id, self.answer.participant.key))
200 def expert_download_url(self):
201 return reverse('stage2_expert_download', args=[self.id])
204 class Mark(models.Model):
205 expert = models.ForeignKey(settings.AUTH_USER_MODEL)
206 answer = models.ForeignKey(Answer)
207 points = models.DecimalField(verbose_name=_('points'), max_digits=3, decimal_places=1)
210 unique_together = ['expert', 'answer']
213 @receiver(post_save, sender=Mark, dispatch_uid='update_answer')
214 def update_answer(sender, **kwargs):
215 mark = kwargs['instance']
216 mark.answer.update_complete()