models.py 10.1 KB
Newer Older
1
2
3
import uuid

from django.contrib.auth import get_user_model
Thom Wiggers's avatar
Thom Wiggers committed
4
from django.core import validators
5
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
from thaliawebsite.settings import settings
Thom Wiggers's avatar
Thom Wiggers committed
12
13
from . import emails

14
15
16
17
18
19
20
21
22
23
24

class Entry(models.Model):
    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'
25
    STATUS_COMPLETED = 'completed'
26
27
28
29
30
31

    STATUS_TYPE = (
        (STATUS_CONFIRM, _('Awaiting email confirmation')),
        (STATUS_REVIEW, _('Ready for review')),
        (STATUS_REJECTED, _('Rejected')),
        (STATUS_ACCEPTED, _('Accepted')),
32
        (STATUS_COMPLETED, _('Completed')),
33
34
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
    )

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

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    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,
    )

87
88
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
117
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
    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):
    # ---- 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)
226
        return full_name.strip()
227
228
229
230
231
232
233

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

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

        if (self.student_number is not None and (
239
240
            Profile.objects.filter(
                student_number=self.student_number).exists()
241
            or
242
            Registration.objects.filter(student_number=self.student_number)
243
244
245
                .exclude(pk=self.pk).exists())):
            errors.update({
                'student_number':
246
247
248
                    _('A user with that student number already exists. '
                      'Login using the existing account and renew the '
                      'membership by visiting the account settings.')})
249
250
251
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

        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):
    member = models.ForeignKey(
        'members.Member',
Thom Wiggers's avatar
Thom Wiggers committed
285
        on_delete=models.CASCADE,
286
287
288
289
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
        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')