models.py 10.3 KB
Newer Older
1
"""The models defined by the registrations package"""
2
3
4
import uuid

from django.contrib.auth import get_user_model
Thom Wiggers's avatar
Thom Wiggers committed
5
from django.core import validators
6
7
8
9
10
11
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from members.models import Membership, Profile
12
from thaliawebsite import settings
Thom Wiggers's avatar
Thom Wiggers committed
13
14
from . import emails

15
16

class Entry(models.Model):
17
    """Describes a registration entry"""
18
19
20
21
22
23
24
25
26
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    created_at = models.DateTimeField(_('created at'), default=timezone.now)
    updated_at = models.DateTimeField(_('updated at'), default=timezone.now)

    STATUS_CONFIRM = 'confirm'
    STATUS_REVIEW = 'review'
    STATUS_REJECTED = 'rejected'
    STATUS_ACCEPTED = 'accepted'
27
    STATUS_COMPLETED = 'completed'
28
29
30
31
32
33

    STATUS_TYPE = (
        (STATUS_CONFIRM, _('Awaiting email confirmation')),
        (STATUS_REVIEW, _('Ready for review')),
        (STATUS_REJECTED, _('Rejected')),
        (STATUS_ACCEPTED, _('Accepted')),
34
        (STATUS_COMPLETED, _('Completed')),
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    )

    status = models.CharField(
        verbose_name=_('status'),
        choices=STATUS_TYPE,
        max_length=20,
        default='confirm',
    )

    MEMBERSHIP_YEAR = 'year'
    MEMBERSHIP_STUDY = 'study'

    MEMBERSHIP_LENGTHS = (
        (MEMBERSHIP_YEAR, _('One year')),
        (MEMBERSHIP_STUDY, _('Until graduation')),
    )

    length = models.CharField(
        verbose_name=_('membership length'),
        choices=MEMBERSHIP_LENGTHS,
        max_length=20,
    )

    MEMBERSHIP_TYPES = [m for m in Membership.MEMBERSHIP_TYPES
                        if m[0] != Membership.HONORARY]

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

    remarks = models.TextField(
        _('remarks'),
        blank=True,
        null=True,
    )

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    payment = models.OneToOneField(
        'payments.Payment',
        related_name='registrations_entry',
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
    )

    membership = models.OneToOneField(
        'members.Membership',
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
    )

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if (self.status != self.STATUS_ACCEPTED and
                self.status != self.STATUS_REJECTED):
            self.updated_at = timezone.now()

        super().save(force_insert, force_update, using, update_fields)

    def __str__(self):
        try:
            return self.registration.__str__()
        except Registration.DoesNotExist:
            pass
        try:
            return self.renewal.__str__()
        except Renewal.DoesNotExist:
            pass
        return super().__str__()

    class Meta:
        verbose_name = _('entry')
        verbose_name_plural = _('entries')
        permissions = (
            ('review_entries', _("Review registration and renewal entries")),
        )


class Registration(Entry):
117
    """Describes a new registration for the association"""
118
119
120
121
122
123
124
125
126
127
128
129
130
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
195
196
197
198
199
200
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
227
228
    # ---- Personal information -----

    username = models.CharField(
        _('Username'),
        max_length=150,
        blank=True,
        null=True,
        help_text=_('Enter value to override the auto-generated username '
                    '(e.g. if it is not unique)')
    )

    first_name = models.CharField(
        _('First name'),
        max_length=30,
        blank=False,
    )

    last_name = models.CharField(
        _('Last name'),
        max_length=200,
        blank=False,
    )

    birthday = models.DateField(
        verbose_name=_('birthday'),
        blank=False,
    )

    language = models.CharField(
        verbose_name=_('language'),
        max_length=5,
        choices=settings.LANGUAGES,
        default='nl',
    )

    # ---- Contact information -----

    email = models.EmailField(
        _('Email address'),
        blank=False,
    )

    phone_number = models.CharField(
        max_length=20,
        verbose_name=_('phone number'),
        validators=[validators.RegexValidator(
            regex=r'^\+?\d+$',
            message=_('please enter a valid phone number'),
        )],
        blank=False,
    )

    # ---- University information -----

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

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

    starting_year = models.IntegerField(
        verbose_name=_('starting year'),
        blank=True,
        null=True,
    )

    # ---- Address information -----

    address_street = models.CharField(
        max_length=100,
        validators=[validators.RegexValidator(
            regex=r'^.+ \d+.*',
            message=_('include the house number'),
        )],
        verbose_name=_('street and house number'),
        blank=False,
    )

    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'),
        blank=False,
    )

    address_city = models.CharField(
        max_length=40,
        verbose_name=_('city'),
        blank=False,
    )

    def get_full_name(self):
        full_name = '{} {}'.format(self.first_name, self.last_name)
229
        return full_name.strip()
230
231
232
233
234
235
236

    def clean(self):
        super().clean()
        errors = {}

        if get_user_model().objects.filter(email=self.email).exists():
            errors.update({
237
238
239
                'email': _('A user with that email address already exists. '
                           'Login using the existing account and renew the '
                           'membership by visiting the account settings.')})
240
241

        if (self.student_number is not None and (
242
243
            Profile.objects.filter(
                student_number=self.student_number).exists()
244
            or
245
            Registration.objects.filter(student_number=self.student_number)
246
247
248
                .exclude(pk=self.pk).exists())):
            errors.update({
                'student_number':
249
250
251
                    _('A user with that student number already exists. '
                      'Login using the existing account and renew the '
                      'membership by visiting the account settings.')})
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

        if self.username is not None and get_user_model().objects.filter(
                username=self.username).exists():
            errors.update({
                'username': _('A user with that username already exists.')})

        if (self.starting_year is None and
                self.membership_type is not Membership.SUPPORTER):
            errors.update({
                'username': _('This field is required.')})

        if (self.programme is None and
                self.membership_type is not Membership.SUPPORTER):
            errors.update({
                'programme': _('This field is required.')})

        if errors:
            raise ValidationError(errors)

    def save(self, *args, **kwargs):
        send_confirm_email = self.pk is None
        super().save(*args, **kwargs)
        if send_confirm_email:
            emails.send_registration_email_confirmation(self)

    def __str__(self):
        return '{} {} ({})'.format(self.first_name, self.last_name, self.email)

    class Meta:
        verbose_name = _('registation')
        verbose_name_plural = _('registrations')


class Renewal(Entry):
286
    """Describes a renewal for the association membership"""
287
288
    member = models.ForeignKey(
        'members.Member',
Thom Wiggers's avatar
Thom Wiggers committed
289
        on_delete=models.CASCADE,
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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
338
339
340
341
342
343
344
345
346
347
348
349
        verbose_name=_('member'),
        blank=False,
        null=False,
    )

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.pk is None:
            self.status = Entry.STATUS_REVIEW
        super().save(force_insert, force_update, using, update_fields)

    def clean(self):
        super().clean()
        errors = {}

        if Renewal.objects.filter(
                member=self.member, status=Entry.STATUS_REVIEW).exists():
            raise ValidationError(_('You already have a renewal '
                                    'request queued for review.'))

        # Invalid form for study and honorary members
        current_membership = self.member.current_membership
        if (current_membership is not None and
                current_membership.until is None):
            errors.update({
                'length': _('You currently have an active membership.'),
                'membership_type': _('You currently have'
                                     ' an active membership.'),
            })

        latest_membership = self.member.latest_membership
        hide_year_choice = not (latest_membership is not None and
                                latest_membership.until is not None and
                                (latest_membership.until -
                                 timezone.now().date()).days <= 31)

        if (self.length == Entry.MEMBERSHIP_YEAR and
                hide_year_choice):
            errors.update({
                'length': _('You cannot renew your membership at this moment.')
            })

        if (self.membership_type == Membership.SUPPORTER and
                self.length == Entry.MEMBERSHIP_STUDY):
            errors.update({
                'length': _('Supporters cannot have a membership '
                            'that lasts their entire study duration.')
            })

        if errors:
            raise ValidationError(errors)

    def __str__(self):
        return '{} {} ({})'.format(self.member.first_name,
                                   self.member.last_name,
                                   self.member.email)

    class Meta:
        verbose_name = _('renewal')
        verbose_name_plural = _('renewals')