models.py 17.9 KB
Newer Older
1
import logging
2
import operator
3
import os
4
import uuid
5
from PIL import Image
6
from datetime import timedelta
7
from django.conf import settings
8
from django.contrib.auth.models import User, UserManager
9
from django.core import validators
10
from django.core.exceptions import ValidationError
11
from django.db import models
12
from django.db.models import Q
13
from django.urls import reverse
14
from django.utils import timezone
15
from django.utils.translation import ugettext_lazy as _
16
from functools import reduce
17
18
19
from localflavor.generic.countries.sepa import IBAN_SEPA_COUNTRIES
from localflavor.generic.models import IBANField

20
from activemembers.models import Committee, CommitteeMembership
21

Thom Wiggers's avatar
Thom Wiggers committed
22
23
24
logger = logging.getLogger(__name__)


25
26
27
28
29
30
31
32
class MemberManager(UserManager):
    """Get all members, i.e. all users with a profile."""

    def get_queryset(self):
        return super().get_queryset().exclude(profile=None)


class ActiveMemberManager(MemberManager):
33
    """Get all active members"""
34

35
36
37
38
39
40
41
42
43
44
45
46
47
    def get_queryset(self):
        active_memberships = (CommitteeMembership
                              .active_memberships
                              .exclude(committee__board__is_board=True))

        return (super().get_queryset()
                .filter(committeemembership__in=active_memberships)
                .distinct())


class CurrentMemberManager(MemberManager):
    """Get all members with an active membership"""

48
49
    def get_queryset(self):
        return (super().get_queryset()
50
51
52
                .exclude(membership=None)
                .filter(Q(membership__until__isnull=True) |
                        Q(membership__until__gt=timezone.now().date()))
53
                .distinct())
54

55
    def with_birthdays_in_range(self, from_date, to_date):
56
57
        queryset = (self.get_queryset()
                        .filter(profile__birthday__lte=to_date))
58
59
60
61
62
63
64
65
66

        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 = [
67
68
            {"profile__birthday__month": d.month,
             "profile__birthday__day": d.day}
69
70
71
72
73
74
75
            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)

76

77
78
79
80
class Member(User):
    class Meta:
        proxy = True
        ordering = ('first_name', 'last_name')
81

82
    objects = MemberManager()
83
    current_members = CurrentMemberManager()
84
85
    active_members = ActiveMemberManager()

86
87
    def __str__(self):
        return '{} ({})'.format(self.get_full_name(), self.username)
88

89
90
91
92
93
94
    @property
    def current_membership(self):
        membership = self.latest_membership
        if membership and not membership.is_active():
            return None
        return membership
95

96
97
98
99
100
101
    @property
    def latest_membership(self):
        if not self.membership_set.exists():
            return None
        return self.membership_set.latest('since')

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

108
109
110
111
112
113
    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

114
    def has_active_membership(self):
115
116
117
118
119
        """Is this member currently active

        Tested by checking if the expiration date has passed.
        """
        return self.current_membership is not None
120

121
    # Special properties for admin site
122
123
124
    has_active_membership.boolean = True
    has_active_membership.short_description = \
        _('Is this user currently active')
125

126
    @classmethod
127
128
    def all_with_membership(cls, membership_type):
        return [x for x in cls.objects.all()
129
130
                if x.current_membership and
                x.current_membership.type == membership_type]
131

132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    @property
    def can_attend_events(self):
        if not self.profile:
            return False

        return ((self.profile.event_permissions == 'all' or
                self.profile.event_permissions == 'no_drinks') and
                self.current_membership is not None)

    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)

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


class Profile(models.Model):
    """This class holds extra information about a member"""

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

    # Preferably this would have been a foreign key to Member instead,
    # but the UserAdmin requires that this is a foreign key to User.
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    # ----- Registration information -----

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

    student_number = models.CharField(
        verbose_name=_('Student number'),
        max_length=8,
        validators=[validators.RegexValidator(
            regex=r'(s\d{7}|[ezu]\d{6,7})',
            message=_('Enter a valid student- or e/z/u-number.'))],
        blank=True,
        null=True,
    )

    starting_year = models.IntegerField(
        verbose_name=_('Starting year'),
        help_text=_('The year this member started studying.'),
        blank=True,
        null=True,
    )

195
196
197
198
199
    # ---- Address information -----

    address_street = models.CharField(
        max_length=100,
        validators=[validators.RegexValidator(
Thom Wiggers's avatar
Thom Wiggers committed
200
            regex=r'^.+ \d+.*',
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
            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
227
        max_length=20,
228
229
230
231
        verbose_name=_('Phone number'),
        help_text=_('Enter a phone number so Thalia may reach you'),
        validators=[validators.RegexValidator(
            regex=r'^\+?\d+$',
232
            message=_('Please enter a valid phone number'),
233
234
235
236
237
        )],
        null=True,
        blank=True,
    )

238
    # ---- Emergency contact ----
239

240
241
242
243
    emergency_contact = models.CharField(
        max_length=255,
        verbose_name=_('Emergency contact name'),
        help_text=_('Who should we contact in case of emergencies'),
244
245
246
247
        null=True,
        blank=True,
    )

248
    emergency_contact_phone_number = models.CharField(
Thom Wiggers's avatar
Thom Wiggers committed
249
        max_length=20,
250
251
        verbose_name=_('Emergency contact phone number'),
        help_text=_('The phone number for the emergency contact'),
252
253
        validators=[validators.RegexValidator(
            regex=r'^\+?\d+$',
254
            message=_('Please enter a valid phone number'),
255
256
257
258
259
260
261
262
263
264
265
266
        )],
        null=True,
        blank=True,
    )

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

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

267
268
269
    show_birthday = models.BooleanField(
        verbose_name=_('Display birthday'),
        help_text=_(
270
            'Show your birthday to other members on your profile page and '
271
272
273
274
            'in the birthday calendar'),
        default=True,
    )

275
276
277
278
279
280
281
282
283
284
285
    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'),
286
        blank=True,
287
        null=True,
288
        max_length=4096,
289
290
291
292
293
294
295
    )

    initials = models.CharField(
        max_length=20,
        verbose_name=_('Initials'),
        blank=True,
        null=True,
296
297
298
299
300
301
302
303
304
    )

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

305
306
307
308
309
    display_name_preference = models.CharField(
        max_length=10,
        verbose_name=_('How to display name'),
        choices=(('full', _('Show full name')),
                 ('nickname', _('Show only nickname')),
310
                 ('firstname', _('Show only first name')),
311
312
313
314
315
316
                 ('initials', _('Show initials and last name')),
                 ('fullnick', _("Show name like \"John 'nickname' Doe\"")),
                 ('nicklast', _("Show nickname and last name"))),
        default='full',
    )

317
    photo = models.ImageField(
318
        verbose_name=_('Photo'),
319
320
321
322
323
        upload_to='public/avatars/',
        null=True,
        blank=True,
    )

324
325
326
327
328
329
330
331
332
333
    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',
    )

334
335
336
337
    # --- Communication preference ----

    language = models.CharField(
        verbose_name=_('Preferred language'),
338
        help_text=_('Preferred language for e.g. newsletters'),
339
340
341
342
343
344
345
346
347
348
349
350
        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
351
352
353
354
355
356
    receive_newsletter = models.BooleanField(
        verbose_name=_('Receive newsletter'),
        help_text=_("Receive the Thalia Newsletter"),
        default=True,
    )

357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    # --- 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'),
372
373
374
        help_text=_('Bank account for direct debit'),
        include_countries=IBAN_SEPA_COUNTRIES,
        blank=True,
375
    )
376
377
378

    def display_name(self):
        pref = self.display_name_preference
379
        if pref == 'nickname' and self.nickname is not None:
380
            return self.nickname
381
        elif pref == 'firstname':
382
            return self.user.first_name
383
        elif pref == 'initials':
384
385
386
387
            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:
388
389
390
            return "{} '{}' {}".format(self.user.first_name,
                                       self.nickname,
                                       self.user.last_name)
391
        elif pref == 'nicklast' and self.nickname is not None:
392
393
394
            return "'{}' {}".format(self.nickname,
                                    self.user.last_name)
        else:
395
            return self.user.get_full_name() or self.user.username
396
    display_name.short_description = _('Display name')
397

398
399
    def short_display_name(self):
        pref = self.display_name_preference
400
401
        if (self.nickname is not None and
                (pref == 'nickname' or pref == 'nicklast')):
402
403
            return self.nickname
        elif pref == 'initials':
404
405
406
            if self.initials:
                return '{} {}'.format(self.initials, self.user.last_name)
            return self.user.last_name
407
408
409
        else:
            return self.user.first_name

410
    def __init__(self, *args, **kwargs):
411
        super().__init__(*args, **kwargs)
412
413
414
415
416
        if self.photo:
            self._orig_image = self.photo.path
        else:
            self._orig_image = ""

417
418
419
    def clean(self):
        super().clean()
        errors = {}
420

421
422
423
424
425
426
        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')})
427
428
429
430
431
432
433

        if self.birthday and self.birthday > timezone.now().date():
            errors.update(
                {'birthday': _('A birthday cannot be in the future.')})

        if errors:
            raise ValidationError(errors)
434

435
    def save(self, *args, **kwargs):
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
436
        super().save(*args, **kwargs)
437
438
439
440
441
442
443
444
445

        if self._orig_image and not self.photo:
            try:
                os.remove(self._orig_image)
            except FileNotFoundError:
                pass
            self._orig_image = ''

        elif self.photo and self._orig_image != self.photo.path:
446
447
            image_path = self.photo.path
            image = Image.open(image_path)
Thom Wiggers's avatar
Thom Wiggers committed
448
449
450
            image_path, _ext = os.path.splitext(image_path)
            image_path = "{}.jpg".format(image_path)

451
            # Image.thumbnail does not upscale an image that is smaller
Thom Wiggers's avatar
Thom Wiggers committed
452
            logger.debug("Converting image %s", image_path)
453
            image.thumbnail(settings.PHOTO_UPLOAD_SIZE, Image.ANTIALIAS)
Thom Wiggers's avatar
Thom Wiggers committed
454
455
456
457
            image.convert("RGB").save(image_path, "JPEG")
            image_name, _ext = os.path.splitext(self.photo.name)
            self.photo.name = "{}.jpg".format(image_name)
            super().save(*args, **kwargs)
458
459

            try:
Thom Wiggers's avatar
Thom Wiggers committed
460
461
462
                if self._orig_image:
                    logger.info("deleting", self._orig_image)
                    os.remove(self._orig_image)
463
464
            except FileNotFoundError:
                pass
465
            self._orig_image = self.photo.path
Thom Wiggers's avatar
Thom Wiggers committed
466
467
        else:
            logging.warning("We already had this image")
468

469
    def __str__(self):
470
        return str(self.user)
471
472


473
474
class Membership(models.Model):

475
476
477
478
    MEMBER = 'member'
    SUPPORTER = 'supporter'
    HONORARY = 'honorary'

479
    MEMBERSHIP_TYPES = (
480
481
482
        (MEMBER, _('Member')),
        (SUPPORTER, _('Supporter')),
        (HONORARY, _('Honorary Member')))
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508

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

    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,
    )

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
    def clean(self):
        super().clean()

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

        if self.since is not None:
            memberships = self.user.membership_set.all()
            for membership in memberships:
                if membership.pk == self.pk:
                    continue
                if ((membership.until is None and (
                    self.until is None or self.until > membership.since)) or
                    (self.until is None and self.since < membership.until) or
                    (self.until and membership.until and
                     self.since < membership.until and
                     self.until > membership.since)):
                    errors.update({
                        'since': _('A membership already '
                                   'exists for that period'),
                        'until': _('A membership already '
                                   'exists for that period')})

        if errors:
            raise ValidationError(errors)

537
    def is_active(self):
538
        return not self.until or self.until > timezone.now().date()
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575


class EmailChange(models.Model):
    created_at = models.DateTimeField(_('created at'), default=timezone.now)

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

    email = models.EmailField(_('email'), max_length=254)

    verify_key = models.UUIDField(unique=True, default=uuid.uuid4,
                                  editable=False)
    confirm_key = models.UUIDField(unique=True, default=uuid.uuid4,
                                   editable=False)

    verified = models.BooleanField(
        _('verified'), default=False,
        help_text=_('the new email address is valid')
    )
    confirmed = models.BooleanField(
        _('confirmed'), default=False,
        help_text=_('the old email address was checked')
    )

    @property
    def completed(self):
        return self.verified and self.confirmed

    def clean(self):
        super().clean()

        if self.email == self.member.email:
            raise ValidationError(
                {'email': _("Please enter a new email address.")})