972376a96af8ad4ca6bee2168851f34f7e4a1890
[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.translation import ugettext_lazy as _
12 from django.utils import timezone
13 from jsonfield import JSONField
14
15 from contact.models import Contact
16
17
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)
26
27     class Meta:
28         verbose_name = _('participant')
29         verbose_name_plural = _('participants')
30
31     def __unicode__(self):
32         return ', '.join((self.last_name, self.first_name, self.email))
33
34     # copy-paste from wtem
35     @classmethod
36     def generate_key(cls):
37         key = ''
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)
40                           for i in range(30))
41         return key
42
43     # copy-paste from wtem
44     @classmethod
45     def create(cls, first_name, last_name, email, key=None, contact=None):
46         return cls.objects.create(
47             contact=contact,
48             key=key if key else cls.generate_key(),
49             first_name=first_name,
50             last_name=last_name,
51             email=email)
52
53     def check(self, key):
54         return key == self.key
55
56     def score(self):
57         return sum(answer.score() for answer in self.answer_set.all())
58
59
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'))
73
74     class Meta:
75         ordering = ['deadline', 'title']
76         verbose_name = _('assignment')
77         verbose_name_plural = _('assignments')
78
79     def __unicode__(self):
80         return self.title
81
82     def available_answers(self, expert):
83         answers = self.answer_set.exclude(mark__expert=expert).filter(participant__complete_set=True)
84         if expert not in self.supervisors.all():
85             answers = answers.exclude(complete=True)
86         if expert in self.arbiters.all():
87             answers = answers.filter(need_arbiter=True)
88         return answers
89
90     def is_active(self):
91         return self.deadline >= timezone.now()
92
93
94 class Answer(models.Model):
95     participant = models.ForeignKey(Participant)
96     assignment = models.ForeignKey(Assignment)
97     # useful redundancy
98     complete = models.BooleanField(default=False)
99     need_arbiter = models.BooleanField(default=False)
100
101     class Meta:
102         unique_together = ['participant', 'assignment']
103
104     def update_complete(self):
105         marks = self.mark_set.all()
106         if len(marks) < 2:
107             complete = False
108             need_arbiter = False
109         elif len(marks) == 2:
110             mark1, mark2 = marks
111             complete = abs(mark1.points - mark2.points) < 0.2 * self.assignment.max_points
112             need_arbiter = not complete
113         else:
114             complete = True
115             need_arbiter = False
116         self.complete = complete
117         self.need_arbiter = need_arbiter
118         self.save()
119
120     def score(self):
121         marks = self.mark_set.all()
122         if len(marks) < 2:
123             return None
124         return self.mark_set.aggregate(models.Avg('points'))
125
126
127 def attachment_path(instance, filename):
128     answer = instance.answer
129     return 'stage2/attachment/%s/%s/%s/%s' % (answer.participant_id, answer.assignment_id, instance.file_no, filename)
130
131
132 class Attachment(models.Model):
133     answer = models.ForeignKey(Answer)
134     file_no = models.IntegerField()
135     file = models.FileField(upload_to=attachment_path)
136
137     class Meta:
138         ordering = ['file_no']
139
140     def filename(self):
141         return os.path.basename(self.file.name)
142
143     def download_url(self):
144         return reverse(
145             'stage2_participant_file',
146             args=(self.answer.assignment_id, self.file_no,
147                   self.answer.participant_id, self.answer.participant.key))
148
149     def expert_download_url(self):
150         return reverse('stage2_expert_download', args=[self.id])
151
152
153 class Mark(models.Model):
154     expert = models.ForeignKey(settings.AUTH_USER_MODEL)
155     answer = models.ForeignKey(Answer)
156     points = models.DecimalField(verbose_name=_('points'), max_digits=3, decimal_places=1)
157
158     class Meta:
159         unique_together = ['expert', 'answer']
160
161
162 @receiver(post_save, sender=Mark, dispatch_uid='update_answer')
163 def update_answer(sender, **kwargs):
164     mark = kwargs['instance']
165     mark.answer.update_complete()