models.py 7.6 KB
Newer Older
Thom Wiggers's avatar
Thom Wiggers committed
1
import datetime
2
import logging
Thom Wiggers's avatar
Thom Wiggers committed
3
4
5
6

from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
from django.contrib.auth.models import Permission
from django.db import models
Thom Wiggers's avatar
Thom Wiggers committed
7
from django.urls import reverse
8
from django.utils import timezone
Thom Wiggers's avatar
Thom Wiggers committed
9
10
11
12
13
from django.utils.translation import ugettext_lazy as _

from members.models import Member


14
15
16
logger = logging.getLogger(__name__)


Thom Wiggers's avatar
Thom Wiggers committed
17
18
19
20
21
22
23
24
class CommitteeManager(models.Manager):
    """Returns committees only"""
    def get_queryset(self):
        return (super().get_queryset()
                .exclude(board__is_board=True))


class ActiveCommitteeManager(models.Manager):
Thom Wiggers's avatar
Thom Wiggers committed
25
26
    """Returns active committees only"""
    def get_queryset(self):
Thom Wiggers's avatar
Thom Wiggers committed
27
        return (super().get_queryset()
28
                .exclude(board__is_board=True)
Thom Wiggers's avatar
Thom Wiggers committed
29
                .exclude(until__lt=timezone.now().date()))
Thom Wiggers's avatar
Thom Wiggers committed
30
31


Thom Wiggers's avatar
Thom Wiggers committed
32
33
34
class Committee(models.Model):
    """A committee"""

Thom Wiggers's avatar
Thom Wiggers committed
35
36
    active_committees = ActiveCommitteeManager()
    objects = CommitteeManager()
Thom Wiggers's avatar
Thom Wiggers committed
37

Thom Wiggers's avatar
Thom Wiggers committed
38
39
40
41
42
43
44
45
46
47
48
49
    name = models.CharField(
        max_length=40,
        verbose_name=_('Committee name'),
        unique=True,
    )

    description = models.TextField(
        verbose_name=_('Description'),
    )

    photo = models.ImageField(
        verbose_name=_('Image'),
Thom Wiggers's avatar
Thom Wiggers committed
50
        upload_to='public/committeephotos/',
Thom Wiggers's avatar
Thom Wiggers committed
51
52
        null=True,
        blank=True,
Thom Wiggers's avatar
Thom Wiggers committed
53
54
55
56
57
58
59
60
61
62
63
64
65
    )

    members = models.ManyToManyField(
        Member,
        through='CommitteeMembership'
    )

    permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('permissions'),
        blank=True,
    )

Thom Wiggers's avatar
Thom Wiggers committed
66
67
68
69
70
    since = models.DateField(
        _('founded in'),
        null=True,
        blank=True,
    )
Thom Wiggers's avatar
Thom Wiggers committed
71

Thom Wiggers's avatar
Thom Wiggers committed
72
73
74
75
76
    until = models.DateField(
        _('existed until'),
        null=True,
        blank=True,
    )
Thom Wiggers's avatar
Thom Wiggers committed
77
78
79

    contact_email = models.EmailField(_('contact email address'))

Thom Wiggers's avatar
Thom Wiggers committed
80
81
82
    def __str__(self):
        return self.name

Thom Wiggers's avatar
Thom Wiggers committed
83
84
85
    def get_absolute_url(self):
        return reverse('committees:details', args=[str(self.pk)])

Thom Wiggers's avatar
Thom Wiggers committed
86
87
88
89
90
    class Meta:
        verbose_name = _('committee')
        verbose_name_plural = _('committees')


Thom Wiggers's avatar
Thom Wiggers committed
91
92
93
94
95
96
97
98
99
100
101
102
103
class BoardManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_board=True)


class Board(Committee):
    objects = BoardManager()

    is_board = models.BooleanField(
        verbose_name=_('Is this a board'),
        default=True,
    )

Thom Wiggers's avatar
Thom Wiggers committed
104
105
106
    def get_absolute_url(self):
        return '/committee/boards/{}'.format(self.name.lower())

Thom Wiggers's avatar
Thom Wiggers committed
107

Thom Wiggers's avatar
Thom Wiggers committed
108
109
110
111
class ActiveMembershipManager(models.Manager):
    """Get only active memberships"""
    def get_queryset(self):
        """Get the currently active committee memberships"""
112
        return super().get_queryset().exclude(until__lt=timezone.now().date())
Thom Wiggers's avatar
Thom Wiggers committed
113
114
115
116


class CommitteeMembership(models.Model):
    objects = models.Manager()
Thom Wiggers's avatar
Thom Wiggers committed
117
    active_memberships = ActiveMembershipManager()
Thom Wiggers's avatar
Thom Wiggers committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

    member = models.ForeignKey(
        Member,
        on_delete=models.CASCADE,
        verbose_name=_('Member'),
    )

    committee = models.ForeignKey(
        Committee,
        on_delete=models.CASCADE,
        verbose_name=_('Committee'),
    )

    since = models.DateField(
        verbose_name=_('Committee member since'),
        help_text=_('The date this member joined the committee in this role'),
Thom Wiggers's avatar
Thom Wiggers committed
134
        default=datetime.date.today
Thom Wiggers's avatar
Thom Wiggers committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    )

    until = models.DateField(
        verbose_name=_('Committee member until'),
        help_text=_("A member of this committee until this time "
                    "(can't be in the future)."),
        blank=True,
        null=True,
    )

    chair = models.BooleanField(
        verbose_name=_('Chair of the committee'),
        help_text=_('There can only be one chair at a time!'),
        default=False,
    )

Thom Wiggers's avatar
Thom Wiggers committed
151
152
153
154
155
156
157
158
    role = models.CharField(
        _('role'),
        help_text=_('The role of this member'),
        max_length=255,
        blank=True,
        null=True,
    )

159
160
161
162
163
164
165
166
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if self.pk is None:
            self._was_chair = bool(self.chair)
        else:
            self._was_chair = False

Thom Wiggers's avatar
Thom Wiggers committed
167
168
169
    @property
    def is_active(self):
        """Is this membership currently active"""
170
        return self.until is None or self.until > timezone.now().date()
Thom Wiggers's avatar
Thom Wiggers committed
171
172
173

    def clean(self):
        """Validation"""
174
        if self.until and self.until > timezone.now().date():
Thom Wiggers's avatar
Thom Wiggers committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
            raise ValidationError({
                'until': _("Membership expiration date can't be in the future:"
                           " '{}'").format(self.until)
            })

        if self.until and (not self.since or self.until < self.since):
            raise ValidationError(
                {'until': _("End date can't be before start date")})

    def validate_unique(self, *args, **kwargs):
        """ Check uniqueness"""
        super().validate_unique(*args, **kwargs)
        # Check if a committee has more than one chair
        chairs = (CommitteeMembership.active_memberships
                  .filter(committee=self.committee)
190
                  .exclude(member=self.member)
Thom Wiggers's avatar
Thom Wiggers committed
191
192
193
194
195
196
197
198
                  .filter(chair=True)
                  .count())
        if chairs >= 1 and self.chair:
            raise ValidationError({
                NON_FIELD_ERRORS:
                _('This committee already has a chair')})

        # check if this member is already in the committee
199
        if self.pk is None:
200
201
202
            until = self.until if self.until else timezone.now().date()
            members = (CommitteeMembership.active_memberships
                       .filter(committee=self.committee, member=self.member)
203
                       .count())
204
205
206
207
208
209
210
211
            memberships = (CommitteeMembership.objects.filter(
                           committee=self.committee,
                           member=self.member,
                           since__lte=until,
                           until__gte=self.since)
                           .count())

            if members >= 1 and until >= timezone.now().date():
212
213
                raise ValidationError({
                    'member': _('This member is already in the committee')})
214
215
216
217
            elif memberships > 0:
                raise ValidationError({
                    'member': _('This member is already in the committee for '
                                'this period')})
218
219
220
221
222
223
224
225
226
227
228
229
230
231

    def save(self, *args, **kwargs):
        """Save the instance"""
        # If the chair changed and we're still active, we create a new instance
        # Inactive instances should be handled manually
        if (self.pk is not None and self._was_chair != self.chair and
                not self.until):
            logger.info("Creating new membership instance")
            self.until = timezone.now().date()
            super().save(*args, **kwargs)
            self.pk = None  # forces INSERT
            self.since = self.until  # Set since date to older expiration
            self.until = None
        super().save(*args, **kwargs)
Thom Wiggers's avatar
Thom Wiggers committed
232

233
234
235
236
237
238
239
240
    def delete(self, *args, **kwargs):
        """Deactivates active memberships, deletes inactive ones"""
        if self.is_active:
            self.until = timezone.now().date()
            self.save()
        else:
            super().delete(*args, **kwargs)

Thom Wiggers's avatar
Thom Wiggers committed
241
242
243
244
245
246
247
248
    def __str__(self):
        return "{} membership of {} since {}".format(self.member,
                                                     self.committee,
                                                     self.since)

    class Meta:
        verbose_name = _('committee membership')
        verbose_name_plural = _('committee memberships')
Joost Rijneveld's avatar
Joost Rijneveld committed
249
250


251
class Mentorship(models.Model):
Joost Rijneveld's avatar
Joost Rijneveld committed
252
253
254
255
    members = models.ManyToManyField(Member)
    year = models.IntegerField(unique=True)

    def __str__(self):
256
        return _("Mentor introduction {year}").format(year=self.year)