4a5b103d4540313b2434ebf359651934d18106ea
[edumed.git] / stage2 / models.py
1 # -*- coding: utf-8 -*-
2 import os
3 import random
4 import string
5
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
15
16 from contact.models import Contact
17
18
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)
27
28     class Meta:
29         verbose_name = _('participant')
30         verbose_name_plural = _('participants')
31
32     def __unicode__(self):
33         return ', '.join((self.last_name, self.first_name, self.email))
34
35     # copy-paste from wtem
36     @classmethod
37     def generate_key(cls):
38         key = ''
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)
41                           for i in range(30))
42         return key
43
44     # copy-paste from wtem
45     @classmethod
46     def create(cls, first_name, last_name, email, key=None, contact=None):
47         return cls.objects.create(
48             contact=contact,
49             key=key if key else cls.generate_key(),
50             first_name=first_name,
51             last_name=last_name,
52             email=email)
53
54     def check(self, key):
55         return key == self.key
56
57     def score(self):
58         return sum(answer.score() for answer in self.answer_set.all())
59
60
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)
75
76     class Meta:
77         ordering = ['deadline', 'title']
78         verbose_name = _('assignment')
79         verbose_name_plural = _('assignments')
80
81     def __unicode__(self):
82         return self.title
83
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)
94         return answers
95
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()
101             else:  # text, link
102                 field_count = sum(1 for answer in answers if answer.field_values.get(field_name))
103             yield field_name, field_count
104
105     def is_active(self):
106         return self.deadline >= timezone.now()
107
108
109 class Answer(models.Model):
110     participant = models.ForeignKey(Participant)
111     assignment = models.ForeignKey(Assignment)
112     field_values = JSONField(_('field values'), default={})
113     # useful redundancy
114     complete = models.BooleanField(default=False)
115     need_arbiter = models.BooleanField(default=False)
116
117     class Meta:
118         unique_together = ['participant', 'assignment']
119
120     def fields(self):
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 '--------'
126             else:  # text, link
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
131
132     def update_complete(self):
133         marks = self.mark_set.all()
134         if len(marks) < 2:
135             complete = False
136             need_arbiter = False
137         elif len(marks) == 2:
138             mark1, mark2 = marks
139             complete = abs(mark1.points - mark2.points) < 0.2 * self.assignment.max_points
140             need_arbiter = not complete
141         else:
142             complete = True
143             need_arbiter = False
144         self.complete = complete
145         self.need_arbiter = need_arbiter
146         self.save()
147
148     def score(self):
149         marks = self.mark_set.all()
150         if len(marks) < 2:
151             return None
152         return self.mark_set.aggregate(avg=models.Avg('points'))['avg']
153
154
155 class FieldOptionSet(models.Model):
156     name = models.CharField(verbose_name=_('nazwa'), max_length=32, db_index=True)
157
158     class Meta:
159         verbose_name = _('option set')
160         verbose_name_plural = _('option sets')
161
162     def __unicode__(self):
163         return self.name
164
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'],
170                 params=[answer.id])]
171
172
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)
177
178     class Meta:
179         ordering = ['set', 'value']
180         verbose_name = _('option')
181         verbose_name_plural = _('options')
182
183     def __unicode__(self):
184         return self.value
185
186
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)
190
191
192 class Attachment(models.Model):
193     answer = models.ForeignKey(Answer)
194     file_no = models.IntegerField()
195     file = models.FileField(upload_to=attachment_path)
196
197     class Meta:
198         ordering = ['file_no']
199
200     def filename(self):
201         return os.path.basename(self.file.name)
202
203     def download_url(self):
204         return reverse(
205             'stage2_participant_file',
206             args=(self.answer.assignment_id, self.file_no,
207                   self.answer.participant_id, self.answer.participant.key))
208
209     def expert_download_url(self):
210         return reverse('stage2_expert_download', args=[self.id])
211
212
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)
217
218     class Meta:
219         unique_together = ['expert', 'answer']
220
221
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()