services.py 14.6 KB
Newer Older
1
"""The services defined by the registrations package"""
2
3
import string
import unicodedata
4
from typing import Union
5

6
from django.conf import settings
7
8
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.options import get_content_type_for_model
9
from django.contrib.auth import get_user_model
10
from django.db.models import Q, QuerySet
11
12
13
from django.utils import timezone

import members
14
from members.models import Membership, Profile, Member
15
from payments.models import Payment
16
17
from registrations import emails
from registrations.models import Entry, Registration, Renewal
18
from utils.snippets import datetime_to_lectureyear
19
20


21
def _generate_username(registration: Registration) -> str:
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    """
    Create username from first and lastname

    :param registration: Model containing first and last name
    :type registration: Registration
    :return: Created username
    :rtype: str
    """
    username = (registration.first_name[0] +
                registration.last_name).lower()
    username = ''.join(c for c in username if c.isalpha())
    username = ''.join(c for c in unicodedata.normalize('NFKD', username)
                       if c in string.ascii_letters).lower()

    # Limit length to 150 characters since Django doesn't support longer
    if len(username) > 150:
        username = username[:150]

    return username


43
def check_unique_user(entry: Entry) -> bool:
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    """
    Check that the username and email address of the entry are unique.

    :param entry: Registration entry
    :type entry: Entry
    :return: True if unique, False if not unique
    :rtype: boolean
    """
    try:
        registration = entry.registration
        username = _generate_username(registration)
        if (get_user_model().objects.filter(username=username).exists() and
                registration.username is not None):
            username = registration.username

        return not (get_user_model().objects.filter(
            Q(email=registration.email) | Q(username=username)).exists())
    except Registration.DoesNotExist:
        pass
    return True


66
def confirm_entry(queryset: QuerySet) -> int:
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    """
    Confirm all entries in the queryset

    :param queryset: queryset of entries
    :type queryset: Queryset[Entry]
    :return: number of updated rows
    :rtype: integer
    """
    queryset = queryset.filter(status=Entry.STATUS_CONFIRM)
    rows_updated = queryset.update(status=Entry.STATUS_REVIEW,
                                   updated_at=timezone.now())
    return rows_updated


81
def reject_entries(user_id: int, queryset: QuerySet) -> int:
82
83
84
    """
    Reject all entries in the queryset

85
    :param user_id: Id of the user executing this action
86
87
88
89
90
91
92
93
94
95
96
    :param queryset: queryset of entries
    :type queryset: Queryset[Entry]
    :return: number of updated rows
    :rtype: integer
    """
    queryset = queryset.filter(status=Entry.STATUS_REVIEW)
    entries = list(queryset.all())
    rows_updated = queryset.update(status=Entry.STATUS_REJECTED,
                                   updated_at=timezone.now())

    for entry in entries:
97
98
        log_obj = None

99
100
        try:
            emails.send_registration_rejected_message(entry.registration)
101
            log_obj = entry.registration
102
103
104
        except Registration.DoesNotExist:
            try:
                emails.send_renewal_rejected_message(entry.renewal)
105
                log_obj = entry.renewal
106
107
108
            except Renewal.DoesNotExist:
                pass

109
110
111
112
113
114
115
116
117
118
        if log_obj:
            LogEntry.objects.log_action(
                user_id=user_id,
                content_type_id=get_content_type_for_model(log_obj).pk,
                object_id=log_obj.pk,
                object_repr=str(log_obj),
                action_flag=CHANGE,
                change_message='Changed status to rejected',
            )

119
120
121
    return rows_updated


122
def accept_entries(user_id: int, queryset: QuerySet) -> int:
123
124
125
    """
    Accept all entries in the queryset

126
    :param user_id: Id of the user executing this action
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    :param queryset: queryset of entries
    :type queryset: Queryset[Entry]
    :return: number of updated rows
    :rtype: integer
    """
    queryset = queryset.filter(status=Entry.STATUS_REVIEW)
    entries = queryset.all()
    updated_entries = []

    for entry in entries:
        # Check if the user is unique
        if not check_unique_user(entry):
            # User is not unique, do not proceed
            continue

142
143
144
        entry.status = Entry.STATUS_ACCEPTED
        entry.updated_at = timezone.now()
        entry.payment = _create_payment_for_entry(entry)
145

146
147
        log_obj = None

148
149
150
151
152
153
        try:
            if entry.registration.username is None:
                entry.registration.username = _generate_username(
                    entry.registration)
                entry.registration.save()
            emails.send_registration_accepted_message(entry.registration,
154
                                                      entry.payment)
155
            log_obj = entry.registration
156
157
        except Registration.DoesNotExist:
            try:
158
159
                emails.send_renewal_accepted_message(entry.renewal,
                                                     entry.payment)
160
                log_obj = entry.renewal
161
162
163
            except Renewal.DoesNotExist:
                pass

164
165
166
167
168
169
170
171
172
173
        if log_obj:
            LogEntry.objects.log_action(
                user_id=user_id,
                content_type_id=get_content_type_for_model(log_obj).pk,
                object_id=log_obj.pk,
                object_repr=str(log_obj),
                action_flag=CHANGE,
                change_message='Change status to approved',
            )

174
        entry.save()
175
176
        updated_entries.append(entry.pk)

177
    return len(updated_entries)
178
179


180
def revert_entry(user_id: int, entry: Entry) -> None:
181
182
183
    """
    Revert status of entry to review so that it can be corrected

184
    :param user_id: Id of the user executing this action
185
186
187
188
189
    :param entry: Entry that should be reverted
    """
    if not (entry.status in [Entry.STATUS_ACCEPTED, Entry.STATUS_REJECTED]):
        return

190
    payment = entry.payment
191
192
    entry.status = Entry.STATUS_REVIEW
    entry.updated_at = timezone.now()
193
    entry.payment = None
194
    entry.save()
195
196
    if payment is not None:
        payment.delete()
197

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    log_obj = None

    try:
        log_obj = entry.registration
    except Registration.DoesNotExist:
        try:
            log_obj = entry.renewal
        except Renewal.DoesNotExist:
            pass

    if log_obj:
        LogEntry.objects.log_action(
            user_id=user_id,
            content_type_id=get_content_type_for_model(log_obj).pk,
            object_id=log_obj.pk,
            object_repr=str(log_obj),
            action_flag=CHANGE,
            change_message='Revert status to review',
        )

218

219
def _create_payment_for_entry(entry: Entry) -> Payment:
220
221
222
223
224
225
226
227
228
    """
    Create payment model for entry

    :param entry: Registration or Renewal model
    :type entry: Entry
    :return: Payment connected to the entry with the right price
    :rtype: Payment
    """
    amount = settings.MEMBERSHIP_PRICES[entry.length]
229
230
    if entry.contribution and entry.membership_type == Membership.BENEFACTOR:
        amount = entry.contribution
231
    notes = f'Membership registration. {entry.get_membership_type_display()}.'
232
233
234
235

    try:
        renewal = entry.renewal
        membership = renewal.member.latest_membership
236
        notes = f'Membership renewal. {entry.get_membership_type_display()}.'
237
238
239
240
241
242
243
244
245
246
247
248
        # Having a latest membership which has an until date implies that this
        # membership lasts/lasted till the end of the lecture year
        # This means it's possible to renew the 'year' membership
        # to a 'study' membership and the price should be adjusted since
        # it is considered an upgrade without paying twice
        # The rules for this behaviour are taken from the HR

        # Since it is possible for people to renew their membership
        # but processing to occur _after_ the membership ended
        # we're checking if that is the case so that these members
        # still get the discount price
        if (membership is not None and membership.until is not None and
249
            entry.created_at.date() < membership.until and
250
251
252
253
254
255
                renewal.length == Entry.MEMBERSHIP_STUDY):
            amount = (settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY] -
                      settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR])
    except Renewal.DoesNotExist:
        pass

256
    return Payment.objects.create(
257
        amount=amount,
258
        notes=notes
259
260
261
    )


262
def _create_member_from_registration(registration: Registration) -> Member:
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    """
    Create User and Member model from Registration

    :param registration: Registration model
    :type registration: Registration
    :return: Created member object
    :rtype: Member
    """

    # Generate random password for user that we can send to the new user
    password = get_user_model().objects.make_random_password(length=15)

    # Make sure the username and email are unique
    if not check_unique_user(registration):
        raise ValueError('Username or email address of the registration '
                         'are not unique')

    # Create user
    user = get_user_model().objects.create_user(
        username=registration.username,
        email=registration.email,
        password=password,
        first_name=registration.first_name,
        last_name=registration.last_name
    )

    # Add profile to created user
    Profile.objects.create(
        user=user,
        programme=registration.programme,
        student_number=registration.student_number,
        starting_year=registration.starting_year,
        address_street=registration.address_street,
        address_street2=registration.address_street2,
        address_postal_code=registration.address_postal_code,
        address_city=registration.address_city,
299
        address_country=registration.address_country,
300
301
        phone_number=registration.phone_number,
        birthday=registration.birthday,
302
303
304
        language=registration.language,
        show_birthday=registration.optin_birthday,
        receive_optin=registration.optin_mailinglist
305
306
307
308
309
    )

    # Send welcome message to new member
    members.emails.send_welcome_message(user, password, registration.language)

310
    return Member.objects.get(pk=user.pk)
311
312


313
314
def _create_membership_from_entry(
        entry: Entry, member: Member = None) -> Union[Membership, None]:
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
    """
    Create or update Membership model based on Entry model information

    :param entry: Entry model
    :type entry: Entry
    :return: The created or updated membership
    :rtype: Membership
    """
    lecture_year = datetime_to_lectureyear(timezone.now())
    # If it's August we act as if it's the next
    # lecture year already and we start new memberships in September
    since = timezone.now().date()
    if timezone.now().month == 8:
        lecture_year += 1
        since = since.replace(month=9, day=1)
    until = None

    if entry.length == Entry.MEMBERSHIP_YEAR:
        # If entry is Renewal set since to current membership until + 1 day
        # Unless there is no current membership
        try:
            member = entry.renewal.member
            membership = member.current_membership
            if membership is not None:
                if membership.until is None:
                    raise ValueError('This member already has a never ending '
                                     'membership')
342
                since = membership.until
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        except Renewal.DoesNotExist:
            pass
        until = timezone.datetime(year=lecture_year + 1,
                                  month=9, day=1).date()
    elif entry.length == Entry.MEMBERSHIP_STUDY:
        try:
            renewal = entry.renewal
            member = renewal.member
            membership = member.latest_membership
            # Having a latest membership which has an until date implies that
            # this membership last(s/ed) till the end of the lecture year
            # This means it's possible to renew the 'year' membership
            # to a 'study' membership thus the until date should now be None
            # and no new membership is needed.
            # The rules for this behaviour are taken from the HR
            if membership is not None:
                if membership.until is None:
                    raise ValueError('This member already has a never ending '
                                     'membership')
                if entry.created_at.date() < membership.until:
                    membership.until = None
                    membership.save()
                    return membership
        except Renewal.DoesNotExist:
            pass
    else:
        return None

    return Membership.objects.create(
        user=member,
        since=since,
        until=until,
        type=entry.membership_type
    )


379
def process_payment(payment: Payment) -> None:
380
381
382
    """
    Process the payment for the entry and send the right emails

383
384
    :param payment: The payment that should be processed
    :type payment: Payment
385
386
    """

387
388
    if not payment.processed:
        return
389

390
391
392
393
    try:
        entry = payment.registrations_entry
    except Entry.DoesNotExist:
        return
394

395
396
    if entry.status != Entry.STATUS_ACCEPTED:
        return
397

398
    member = None
399

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    try:
        registration = entry.registration
        # Create user and member
        member = _create_member_from_registration(registration)
    except Registration.DoesNotExist:
        try:
            # Get member from renewal
            renewal = entry.renewal
            member = renewal.member
            # Send email of payment confirmation for renewal,
            # not needed for registration since a new member already
            # gets the welcome email
            emails.send_renewal_complete_message(entry.renewal)
        except Renewal.DoesNotExist:
            pass
415

416
417
    # If member was retrieved, then create a new membership
    if member is not None:
418
        Payment.objects.filter(pk=payment.pk).update(paid_by=member)
419
420
421
422
        membership = _create_membership_from_entry(entry, member)
        entry.membership = membership
        entry.status = Entry.STATUS_COMPLETED
        entry.save()
423
424
425
426
427
428
429
430
431
432


def execute_data_minimisation(dry_run=False):
    """
    Delete completed or rejected registrations that were modified
    at least 31 days ago

    :param dry_run: does not really remove data if True
    :return: number of removed registrations
    """
433
    deletion_period = timezone.now() - timezone.timedelta(days=31)
434
435
436
437
438
439
440
441
    objects = (Entry.objects
               .filter((Q(status=Entry.STATUS_COMPLETED)
                        | Q(status=Entry.STATUS_REJECTED))
                       & Q(updated_at__lt=deletion_period)))

    if dry_run:
        return objects.count()
    return objects.delete()[0]