models.py 9.64 KB
Newer Older
Sli's avatar
Sli committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# -*- coding:utf-8 -*
#
# Copyright 2019
# - Sli <antoine@bartuccio.fr>
#
# Ce fichier fait partie du site de l'Association des Étudiants de l'UTBM,
# http://ae.utbm.fr.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License a published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.
#
#

from django.db import models
26
from django.utils.translation import ugettext_lazy as _
27
from django.utils import timezone
28 29
from django.core import validators
from django.conf import settings
30
from django.utils.functional import cached_property
Sli's avatar
Sli committed
31 32 33
from django.core.urlresolvers import reverse

from rest_framework import serializers
34 35

from core.models import User
Sli's avatar
Sli committed
36 37 38 39 40 41 42 43 44

# Create your models here.


class UV(models.Model):
    """
    Contains infos about an UV (course)
    """

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    code = models.CharField(
        _("code"),
        max_length=10,
        unique=True,
        validators=[
            validators.RegexValidator(
                regex="([A-Z0-9]+)",
                message=_(
                    "The code of an UV must only contains uppercase characters without accent and numbers"
                ),
            )
        ],
    )
    author = models.ForeignKey(
        User,
60
        related_name="uv_created",
Sli's avatar
Sli committed
61
        verbose_name=_("author"),
62 63 64 65 66 67 68 69 70 71 72 73
        null=False,
        blank=False,
    )
    credit_type = models.CharField(
        _("credit type"),
        max_length=10,
        choices=settings.SITH_PEDAGOGY_UV_TYPE,
        default=settings.SITH_PEDAGOGY_UV_TYPE[0][0],
    )
    manager = models.CharField(_("uv manager"), max_length=300)
    semester = models.CharField(
        _("semester"),
Sli's avatar
Sli committed
74
        max_length=20,
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        choices=settings.SITH_PEDAGOGY_UV_SEMESTER,
        default=settings.SITH_PEDAGOGY_UV_SEMESTER[0][0],
    )
    language = models.CharField(
        _("language"),
        max_length=10,
        choices=settings.SITH_PEDAGOGY_UV_LANGUAGE,
        default=settings.SITH_PEDAGOGY_UV_LANGUAGE[0][0],
    )
    credits = models.IntegerField(
        _("credits"),
        validators=[validators.MinValueValidator(0)],
        blank=False,
        null=False,
    )
    # Double star type not implemented yet
91 92 93 94 95 96 97

    department = models.CharField(
        _("departmenmt"),
        max_length=10,
        choices=settings.SITH_PROFILE_DEPARTMENTS,
        default=settings.SITH_PROFILE_DEPARTMENTS[-1][0],
    )
98 99 100 101 102 103 104

    # All texts about the UV
    title = models.CharField(_("title"), max_length=300)
    manager = models.CharField(_("uv manager"), max_length=300)
    objectives = models.TextField(_("objectives"))
    program = models.TextField(_("program"))
    skills = models.TextField(_("skills"))
Sli's avatar
Sli committed
105
    key_concepts = models.TextField(_("key concepts"))
106 107 108 109 110 111 112 113

    # Hours types CM, TD, TP, THE and TE
    # Kind of dirty but I have nothing else in mind for now
    hours_CM = models.IntegerField(
        _("hours CM"),
        validators=[validators.MinValueValidator(0)],
        blank=False,
        null=False,
Sli's avatar
Sli committed
114
        default=0,
115 116 117 118 119 120
    )
    hours_TD = models.IntegerField(
        _("hours TD"),
        validators=[validators.MinValueValidator(0)],
        blank=False,
        null=False,
Sli's avatar
Sli committed
121
        default=0,
122 123 124 125 126 127
    )
    hours_TP = models.IntegerField(
        _("hours TP"),
        validators=[validators.MinValueValidator(0)],
        blank=False,
        null=False,
Sli's avatar
Sli committed
128
        default=0,
129 130 131 132 133 134
    )
    hours_THE = models.IntegerField(
        _("hours THE"),
        validators=[validators.MinValueValidator(0)],
        blank=False,
        null=False,
Sli's avatar
Sli committed
135
        default=0,
136 137 138 139 140 141
    )
    hours_TE = models.IntegerField(
        _("hours TE"),
        validators=[validators.MinValueValidator(0)],
        blank=False,
        null=False,
Sli's avatar
Sli committed
142
        default=0,
143
    )
Sli's avatar
Sli committed
144

145 146
    def is_owned_by(self, user):
        """
147
        Can be created by superuser, root or pedagogy admin user
148
        """
149
        return user.is_in_group(settings.SITH_GROUP_PEDAGOGY_ADMIN_ID)
150

151
    def can_be_viewed_by(self, user):
152
        """
153
        Only visible by subscribers
154
        """
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        return user.is_subscribed

    def __grade_average_generic(self, field):
        comments = self.comments.filter(**{field + "__gte": 0})
        if not comments.exists():
            return -1

        return int(sum(comments.values_list(field, flat=True)) / comments.count())

    def get_absolute_url(self):
        return reverse("pedagogy:uv_detail", kwargs={"uv_id": self.id})

    @cached_property
    def grade_global_average(self):
        return self.__grade_average_generic("grade_global")

    @cached_property
    def grade_utility_average(self):
        return self.__grade_average_generic("grade_utility")

    @cached_property
    def grade_interest_average(self):
        return self.__grade_average_generic("grade_interest")

    @cached_property
    def grade_teaching_average(self):
        return self.__grade_average_generic("grade_teaching")

    @cached_property
    def grade_work_load_average(self):
        return self.__grade_average_generic("grade_work_load")
186

187
    def __str__(self):
188 189 190 191 192 193 194
        return self.code


class UVComment(models.Model):
    """
    A comment about an UV
    """
195

196 197 198 199 200 201 202
    author = models.ForeignKey(
        User,
        related_name="uv_comments",
        verbose_name=_("author"),
        null=False,
        blank=False,
    )
203
    uv = models.ForeignKey(UV, related_name="comments", verbose_name=_("uv"))
204
    comment = models.TextField(_("comment"), blank=True)
205 206
    grade_global = models.IntegerField(
        _("global grade"),
Sli's avatar
Sli committed
207
        validators=[validators.MinValueValidator(-1), validators.MaxValueValidator(4)],
208 209 210 211 212 213
        blank=False,
        null=False,
        default=-1,
    )
    grade_utility = models.IntegerField(
        _("utility grade"),
Sli's avatar
Sli committed
214
        validators=[validators.MinValueValidator(-1), validators.MaxValueValidator(4)],
215 216 217 218 219 220
        blank=False,
        null=False,
        default=-1,
    )
    grade_interest = models.IntegerField(
        _("interest grade"),
Sli's avatar
Sli committed
221
        validators=[validators.MinValueValidator(-1), validators.MaxValueValidator(4)],
222 223 224 225 226 227
        blank=False,
        null=False,
        default=-1,
    )
    grade_teaching = models.IntegerField(
        _("teaching grade"),
Sli's avatar
Sli committed
228
        validators=[validators.MinValueValidator(-1), validators.MaxValueValidator(4)],
229 230 231 232 233 234
        blank=False,
        null=False,
        default=-1,
    )
    grade_work_load = models.IntegerField(
        _("work load grade"),
Sli's avatar
Sli committed
235
        validators=[validators.MinValueValidator(-1), validators.MaxValueValidator(4)],
236 237 238 239
        blank=False,
        null=False,
        default=-1,
    )
240 241
    publish_date = models.DateTimeField(_("publish date"), blank=True)

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    def is_owned_by(self, user):
        """
        Is owned by a pedagogy admin, a superuser or the author himself
        """
        return self.author == user or user.is_owner(self.uv)

    @cached_property
    def is_reported(self):
        """
        Return True if someone reported this UV
        """
        return self.reports.exists()

    def __str__(self):
        return "%s - %s" % (self.uv, self.author)

258 259 260 261
    def save(self, *args, **kwargs):
        if self.publish_date is None:
            self.publish_date = timezone.now()
        super(UVComment, self).save(*args, **kwargs)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287


class UVResult(models.Model):
    """
    Results got to an UV
    Views will be implemented after the first release
    Will list every UV done by an user
    Linked to user
              uv
    Contains a grade settings.SITH_PEDAGOGY_UV_RESULT_GRADE
             a semester (P/A)20xx
    """

    uv = models.ForeignKey(UV, related_name="results", verbose_name=_("uv"))
    user = models.ForeignKey(User, related_name="uv_results", verbose_name=("user"))
    grade = models.CharField(
        _("grade"),
        max_length=10,
        choices=settings.SITH_PEDAGOGY_UV_RESULT_GRADE,
        default=settings.SITH_PEDAGOGY_UV_RESULT_GRADE[0][0],
    )
    semester = models.CharField(
        _("semester"),
        max_length=5,
        validators=[validators.RegexValidator("[AP][0-9]{3}")],
    )
Sli's avatar
Sli committed
288 289 290 291 292 293 294


class UVCommentReport(models.Model):
    """
    Report an inapropriate comment
    """

295 296 297 298 299 300 301 302 303 304
    comment = models.ForeignKey(
        UVComment,
        related_name="reports",
        verbose_name=_("report"),
        on_delete=models.CASCADE,
    )
    reporter = models.ForeignKey(
        User, related_name="reported_uv_comment", verbose_name=_("reporter")
    )
    reason = models.TextField(_("reason"))
Sli's avatar
Sli committed
305

306 307 308 309 310 311
    def is_owned_by(self, user):
        """
        Can be created by a pedagogy admin, a superuser or a subscriber
        """
        return user.is_subscribed or user.is_owner(self.comment.uv)

Sli's avatar
Sli committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

# Custom serializers


class UVSerializer(serializers.ModelSerializer):
    """
    Custom seralizer for UVs
    Allow adding more informations like absolute_url
    """

    class Meta:
        model = UV
        fields = "__all__"

    absolute_url = serializers.SerializerMethodField()
    update_url = serializers.SerializerMethodField()
    delete_url = serializers.SerializerMethodField()

    def get_absolute_url(self, obj):
        return obj.get_absolute_url()

    def get_update_url(self, obj):
        return reverse("pedagogy:uv_update", kwargs={"uv_id": obj.id})

    def get_delete_url(self, obj):
        return reverse("pedagogy:uv_delete", kwargs={"uv_id": obj.id})