models.py 15.9 KB
Newer Older
1
2
3
4
5
6
import operator
from datetime import date, timedelta
from functools import reduce

from django.conf import settings
from django.core import validators
7
from django.core.exceptions import ValidationError
8
from django.db import models
9
from django.db.models import Q
10
from django.urls import reverse
11
from django.utils import timezone
12
from django.utils.translation import ugettext_lazy as _
13
14
15
from localflavor.generic.countries.sepa import IBAN_SEPA_COUNTRIES
from localflavor.generic.models import IBANField

16
from activemembers.models import Committee
tvbussel's avatar
tvbussel committed
17
from utils.snippets import datetime_to_lectureyear
18
19
from utils.validators import validate_file_extension

20
21
from PIL import Image

22

23
24
25
26
class ActiveMemberManager(models.Manager):
    """Get all active members"""
    def get_queryset(self):
        return (super().get_queryset()
27
                .exclude(user__membership=None)
28
                .filter(Q(user__membership__until__isnull=True) |
29
30
                        Q(user__membership__until__gt=timezone.now().date()))
                .distinct())
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    def with_birthdays_in_range(self, from_date, to_date):
        queryset = self.get_queryset().filter(birthday__lte=to_date)

        if (to_date - from_date).days >= 366:
            # 366 is important to also account for leap years
            # Everyone that's born before to_date has a birthday
            return queryset

        delta = to_date - from_date
        dates = [from_date + timedelta(days=i) for i in range(delta.days + 1)]
        monthdays = [
            {"birthday__month": d.month, "birthday__day": d.day}
            for d in dates
        ]
        # Don't get me started (basically, we are making a giant OR query with
        # all days and months that are in the range)
        query = reduce(operator.or_, [Q(**d) for d in monthdays])
        return queryset.filter(query)

51

52
53
54
class Member(models.Model):
    """This class describes a member"""

55
56
57
    objects = models.Manager()
    active_members = ActiveMemberManager()

58
59
60
61
    # No longer yearly membership as a type, use expiration date instead.
    PROGRAMME_CHOICES = (
        ('computingscience', _('Computing Science')),
        ('informationscience', _('Information Sciences')))
62

63
    user = models.OneToOneField(
64
65
66
67
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

68
69
70
71
72
73
74
75
76
77
78
    # ----- Registration information -----

    programme = models.CharField(
        max_length=20,
        choices=PROGRAMME_CHOICES,
        verbose_name=_('Study programme'),
        blank=True,
        null=True,
    )

    student_number = models.CharField(
79
        verbose_name=_('Student number'),
80
81
82
        max_length=8,
        validators=[validators.RegexValidator(
            regex=r'(s\d{7}|[ezu]\d{6,7})',
WKuipers's avatar
WKuipers committed
83
            message=_('Enter a valid student- or e/z/u-number.'))],
84
85
86
87
        blank=True,
        null=True,
    )

88
89
90
91
92
    starting_year = models.IntegerField(
        verbose_name=_('Starting year'),
        help_text=_('The year this member started studying.'),
        blank=True,
        null=True,
93
94
    )

95
96
97
98
99
100
    @property
    def current_membership(self):
        membership = self.latest_membership
        if membership and not membership.is_active():
            return None
        return membership
101

102
103
104
105
106
107
    @property
    def latest_membership(self):
        if not self.membership_set.exists():
            return None
        return self.membership_set.latest('since')

108
109
110
111
112
113
    @property
    def earliest_membership(self):
        if not self.membership_set.exists():
            return None
        return self.membership_set.earliest('since')

114
115
116
117
    @property
    def membership_set(self):
        return self.user.membership_set

118
119
120
121
122
123
    def has_been_member(self):
        return self.membership_set.filter(type='member').count() > 0

    def has_been_honorary_member(self):
        return self.membership_set.filter(type='honorary').count() > 0

124
125
126
127
128
129
130
131
132
    def is_active(self):
        """Is this member currently active

        Tested by checking if the expiration date has passed.
        """
        return self.current_membership is not None
    # Special properties for admin site
    is_active.boolean = True
    is_active.short_description = _('Is this user currently active')
133

134
135
136
    @classmethod
    def all_with_membership(cls, membership_type, prefetch=None):
        return [x for x in cls.objects.all().prefetch_related(prefetch)
137
138
                if x.current_membership and
                x.current_membership.type == membership_type]
139

140
141
142
143
144
    # ---- Address information -----

    address_street = models.CharField(
        max_length=100,
        validators=[validators.RegexValidator(
Thom Wiggers's avatar
Thom Wiggers committed
145
            regex=r'^.+ \d+.*',
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
            message=_('Include the house number'),
        )],
        verbose_name=_('Street and house number'),
        null=True,
    )

    address_street2 = models.CharField(
        max_length=100,
        verbose_name=_('Second address line'),
        blank=True,
        null=True,
    )

    address_postal_code = models.CharField(
        max_length=10,
        verbose_name=_('Postal code'),
        null=True,
    )

    address_city = models.CharField(
        max_length=40,
        verbose_name=_('City'),
        null=True,
    )

    phone_number = models.CharField(
Thom Wiggers's avatar
Thom Wiggers committed
172
        max_length=20,
173
174
175
176
        verbose_name=_('Phone number'),
        help_text=_('Enter a phone number so Thalia may reach you'),
        validators=[validators.RegexValidator(
            regex=r'^\+?\d+$',
177
            message=_('Please enter a valid phone number'),
178
179
180
181
182
        )],
        null=True,
        blank=True,
    )

183
    # ---- Emergency contact ----
184

185
186
187
188
    emergency_contact = models.CharField(
        max_length=255,
        verbose_name=_('Emergency contact name'),
        help_text=_('Who should we contact in case of emergencies'),
189
190
191
192
        null=True,
        blank=True,
    )

193
    emergency_contact_phone_number = models.CharField(
Thom Wiggers's avatar
Thom Wiggers committed
194
        max_length=20,
195
196
        verbose_name=_('Emergency contact phone number'),
        help_text=_('The phone number for the emergency contact'),
197
198
        validators=[validators.RegexValidator(
            regex=r'^\+?\d+$',
199
            message=_('Please enter a valid phone number'),
200
201
202
203
204
205
206
207
208
209
210
211
        )],
        null=True,
        blank=True,
    )

    # ---- Personal information ------

    birthday = models.DateField(
        verbose_name=_('Birthday'),
        null=True
    )

212
213
214
    show_birthday = models.BooleanField(
        verbose_name=_('Display birthday'),
        help_text=_(
215
            'Show your birthday to other members on your profile page and '
216
217
218
219
            'in the birthday calendar'),
        default=True,
    )

220
221
222
223
224
225
226
227
228
229
230
    website = models.URLField(
        max_length=200,
        verbose_name=_('Website'),
        help_text=_('Website to display on your profile page'),
        blank=True,
        null=True
    )

    profile_description = models.TextField(
        verbose_name=_('Profile text'),
        help_text=_('Text to display on your profile'),
231
        blank=True,
232
233
234
235
236
237
238
239
        null=True,
    )

    initials = models.CharField(
        max_length=20,
        verbose_name=_('Initials'),
        blank=True,
        null=True,
240
241
242
243
244
245
246
247
248
    )

    nickname = models.CharField(
        max_length=30,
        verbose_name=_('Nickname'),
        blank=True,
        null=True,
    )

249
250
251
252
253
    display_name_preference = models.CharField(
        max_length=10,
        verbose_name=_('How to display name'),
        choices=(('full', _('Show full name')),
                 ('nickname', _('Show only nickname')),
254
                 ('firstname', _('Show only first name')),
255
256
257
258
259
260
                 ('initials', _('Show initials and last name')),
                 ('fullnick', _("Show name like \"John 'nickname' Doe\"")),
                 ('nicklast', _("Show nickname and last name"))),
        default='full',
    )

261
    photo = models.ImageField(
262
        verbose_name=_('Photo'),
263
264
265
266
267
        upload_to='public/avatars/',
        null=True,
        blank=True,
    )

268
269
270
271
272
273
274
275
276
277
278
279
    event_permissions = models.CharField(
        max_length=9,
        verbose_name=_('Which events can this member attend'),
        choices=(('all', _('All events')),
                 ('no_events', _('User may not attend events')),
                 ('no_drinks', _('User may not attend drinks')),
                 ('nothing', _('User may not attend anything'))),
        default='all',
    )

    @property
    def can_attend_events(self):
280
281
282
        return ((self.event_permissions == 'all' or
                self.event_permissions == 'no_drinks') and
                self.current_membership is not None)
283

284
285
286
287
    # --- Communication preference ----

    language = models.CharField(
        verbose_name=_('Preferred language'),
288
        help_text=_('Preferred language for e.g. newsletters'),
289
290
291
292
293
294
295
296
297
298
299
300
        max_length=5,
        choices=settings.LANGUAGES,
        default='nl',
    )

    receive_optin = models.BooleanField(
        verbose_name=_('Receive opt-in mailings'),
        help_text=_("Receive mailings about vacancies and events from Thalia's"
                    " sponsors."),
        default=True,
    )

Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
301
302
303
304
305
306
    receive_newsletter = models.BooleanField(
        verbose_name=_('Receive newsletter'),
        help_text=_("Receive the Thalia Newsletter"),
        default=True,
    )

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
    # --- Direct debit information ----

    direct_debit_authorized = models.BooleanField(
        choices=((True, _('Yes, I want Thalia to take the membership fees '
                          'from my bank account through direct debit for '
                          'each year.')),
                 (False, _('No, I will pay the contribution myself'))),
        verbose_name=_('Direct debit'),
        help_text=_('Each year, have Thalia take the membership fees from my '
                    'bank account'),
        default=False,
    )

    bank_account = IBANField(
        verbose_name=_('Bank account'),
322
323
324
        help_text=_('Bank account for direct debit'),
        include_countries=IBAN_SEPA_COUNTRIES,
        blank=True,
325
    )
326

327
328
329
    class Meta:
        ordering = ('user__first_name', 'user__last_name')

330
331
    def display_name(self):
        pref = self.display_name_preference
332
        if pref == 'nickname' and self.nickname is not None:
333
            return self.nickname
334
335
        if pref == 'firstname':
            return self.user.first_name
336
        elif pref == 'initials':
337
338
339
340
            if self.initials:
                return '{} {}'.format(self.initials, self.user.last_name)
            return self.user.last_name
        elif pref == 'fullnick' and self.nickname is not None:
341
342
343
344
345
346
347
            return "{} '{}' {}".format(self.user.first_name,
                                       self.nickname,
                                       self.user.last_name)
        elif pref == 'nicklast':
            return "'{}' {}".format(self.nickname,
                                    self.user.last_name)
        else:
Thom Wiggers's avatar
Thom Wiggers committed
348
            return self.get_full_name() or self.user.username
349
    display_name.short_description = _('Display name')
350

351
352
    def short_display_name(self):
        pref = self.display_name_preference
353
354
        if (self.nickname is not None and
                (pref == 'nickname' or pref == 'nicklast')):
355
356
            return self.nickname
        elif pref == 'initials':
357
358
359
            if self.initials:
                return '{} {}'.format(self.initials, self.user.last_name)
            return self.user.last_name
360
361
362
363
        else:
            return self.user.first_name
        return

Thom Wiggers's avatar
Thom Wiggers committed
364
365
366
    def get_full_name(self):
        return self.user.get_full_name()

367
368
369
370
371
372
373
374
    def get_committees(self):
        return Committee.unfiltered_objects.filter(
            Q(committeemembership__member=self) &
            (
                Q(committeemembership__until=None) |
                Q(committeemembership__until__gt=timezone.now())
            )).exclude(active=False)

375
    def get_absolute_url(self):
376
        return reverse('members:profile', args=[str(self.user.pk)])
377

378
379
380
381
382
383
384
    def __init__(self, *args, **kwargs):
        super(Member, self).__init__(*args, **kwargs)
        if self.photo:
            self._orig_image = self.photo.path
        else:
            self._orig_image = ""

385
386
387
388
389
390
391
392
393
394
395
    def clean(self):
        super().clean()
        errors = {}
        if self.display_name_preference in ('nickname', 'fullnick',
                                            'nicklast'):
            if not self.nickname:
                errors.update(
                    {'nickname': _('You need to enter a nickname to use it as '
                                   'display name')})
        raise ValidationError(errors)

396
397
398
399
400
401
402
403
404
405
    def save(self, *args, **kwargs):
        super(Member, self).save(args, kwargs)
        if self.photo and self._orig_image != self.photo.path:
            image_path = self.photo.path
            image = Image.open(image_path)
            # Image.thumbnail does not upscale an image that is smaller
            image.thumbnail(settings.PHOTO_UPLOAD_SIZE, Image.ANTIALIAS)
            image.save(image_path, "JPEG")
            self._orig_image = self.photo.path

406
    def __str__(self):
Thom Wiggers's avatar
Thom Wiggers committed
407
        return '{} ({})'.format(self.get_full_name(), self.user.username)
408
409


410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
class Membership(models.Model):

    MEMBERSHIP_TYPES = (
        ('member', _('Member')),
        ('supporter', _('Supporter')),
        ('honorary', _('Honorary Member')))

    type = models.CharField(
        max_length=40,
        choices=MEMBERSHIP_TYPES,
        verbose_name=_('Membership type'),
    )

    # Preferably this would have been a foreign key to Member instead,
    # but Django currently does not support nested inlines in the Admin UI.
    # This is necessary to create an inline in the User form.
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        verbose_name=_('User'),
    )

    since = models.DateField(
        verbose_name=_("Membership since"),
        help_text=_("The date the member started holding this membership."),
        default=timezone.now
    )

    until = models.DateField(
        verbose_name=_("Membership until"),
        help_text=_("The date the member stops holding this membership."),
        blank=True,
        null=True,
    )

    @property
    def member(self):
        return self.user.member

    def is_active(self):
450
        return not self.until or self.until > timezone.now().date()
451
452


453
454
455
456
457
458
459
460
461
class BecomeAMemberDocument(models.Model):
    name = models.CharField(max_length=200)
    file = models.FileField(
        upload_to='members/',
        validators=[validate_file_extension],
    )

    def __str__(self):
        return self.name
Thom Wiggers's avatar
Thom Wiggers committed
462
463
464
465
466


def gen_stats_member_type(member_types):
    total = dict()
    for member_type in member_types:
467
468
469
470
471
472
        total[member_type] = (Membership
                              .objects
                              .filter(since__lte=date.today())
                              .filter(Q(until__isnull=True) |
                                      Q(until__gt=date.today()))
                              .filter(type=member_type)
Thom Wiggers's avatar
Thom Wiggers committed
473
474
475
476
477
478
479
480
481
482
483
                              .count())
    return total


def gen_stats_year(member_types):
    """
    Generate list with 6 entries, where each entry represents the total amount
    of Thalia members in a year. The sixth element contains all the multi-year
    students.
    """
    stats_year = []
tvbussel's avatar
tvbussel committed
484
    current_year = datetime_to_lectureyear(date.today())
Thom Wiggers's avatar
Thom Wiggers committed
485
486
487
488

    for i in range(5):
        new = dict()
        for member_type in member_types:
489
490
491
492
493
494
495
496
497
            new[member_type] = (
                Membership
                .objects
                .filter(user__member__starting_year=current_year - i)
                .filter(since__lte=date.today())
                .filter(Q(until__isnull=True) |
                        Q(until__gt=date.today()))
                .filter(type=member_type)
                .count())
Thom Wiggers's avatar
Thom Wiggers committed
498
499
500
501
502
        stats_year.append(new)

    # Add multi year members
    new = dict()
    for member_type in member_types:
503
504
505
506
507
508
509
510
511
        new[member_type] = (
            Membership
            .objects
            .filter(user__member__starting_year__lt=current_year - 4)
            .filter(since__lte=date.today())
            .filter(Q(until__isnull=True) |
                    Q(until__gt=date.today()))
            .filter(type=member_type)
            .count())
Thom Wiggers's avatar
Thom Wiggers committed
512
513
514
    stats_year.append(new)

    return stats_year