services.py 13.5 KB
Newer Older
1
"""The services defined by the registrations package"""
2
3
4
import string
import unicodedata

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

import members
from members.models import Membership, Profile
14
from payments.models import Payment
15
16
from registrations import emails
from registrations.models import Entry, Registration, Renewal
17
from utils.snippets import datetime_to_lectureyear
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
72
73
74
75
76
77
78
79


def _generate_username(registration):
    """
    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


def check_unique_user(entry):
    """
    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


def confirm_entry(queryset):
    """
    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


80
def reject_entries(user_id, queryset):
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    """
    Reject 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_REVIEW)
    entries = list(queryset.all())
    rows_updated = queryset.update(status=Entry.STATUS_REJECTED,
                                   updated_at=timezone.now())

    for entry in entries:
95
96
        log_obj = None

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

107
108
109
110
111
112
113
114
115
116
        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',
            )

117
118
119
    return rows_updated


120
def accept_entries(user_id, queryset):
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    """
    Accept 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_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

139
140
141
        entry.status = Entry.STATUS_ACCEPTED
        entry.updated_at = timezone.now()
        entry.payment = _create_payment_for_entry(entry)
142

143
144
        log_obj = None

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

161
162
163
164
165
166
167
168
169
170
        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',
            )

171
        entry.save()
172
173
        updated_entries.append(entry.pk)

174
    return len(updated_entries)
175
176


177
def revert_entry(user_id, entry):
178
179
180
181
182
183
184
185
    """
    Revert status of entry to review so that it can be corrected

    :param entry: Entry that should be reverted
    """
    if not (entry.status in [Entry.STATUS_ACCEPTED, Entry.STATUS_REJECTED]):
        return

186
    payment = entry.payment
187
188
    entry.status = Entry.STATUS_REVIEW
    entry.updated_at = timezone.now()
189
    entry.payment = None
190
    entry.save()
191
192
    if payment is not None:
        payment.delete()
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    log_obj = None

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

    print(log_obj)

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

216

217
218
219
220
221
222
223
224
225
226
def _create_payment_for_entry(entry):
    """
    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]
227
    notes = f'Membership registration. {entry.get_membership_type_display()}.'
228
229
230
231

    try:
        renewal = entry.renewal
        membership = renewal.member.latest_membership
232
        notes = f'Membership renewal. {entry.get_membership_type_display()}.'
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        # 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
                entry.created_at.date() < membership.until and
                renewal.length == Entry.MEMBERSHIP_STUDY):
            amount = (settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY] -
                      settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR])
    except Renewal.DoesNotExist:
        pass

252
    return Payment.objects.create(
253
        amount=amount,
254
        notes=notes
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
286
287
288
289
290
291
292
293
294
    )


def _create_member_from_registration(registration):
    """
    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,
295
        address_country=registration.address_country,
296
297
        phone_number=registration.phone_number,
        birthday=registration.birthday,
298
299
300
        language=registration.language,
        show_birthday=registration.optin_birthday,
        receive_optin=registration.optin_mailinglist
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
    )

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

    return user


def _create_membership_from_entry(entry, member=None):
    """
    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')
337
                since = membership.until
338
339
340
341
342
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
        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
    )


374
def process_payment(payment):
375
376
377
    """
    Process the payment for the entry and send the right emails

378
379
    :param payment: The payment that should be processed
    :type payment: Payment
380
381
    """

382
383
    if not payment.processed:
        return
384

385
386
387
388
    try:
        entry = payment.registrations_entry
    except Entry.DoesNotExist:
        return
389

390
391
    if entry.status != Entry.STATUS_ACCEPTED:
        return
392

393
    member = None
394

395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
    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
410

411
412
    # If member was retrieved, then create a new membership
    if member is not None:
413
        Payment.objects.filter(pk=payment.pk).update(paid_by=member)
414
415
416
417
        membership = _create_membership_from_entry(entry, member)
        entry.membership = membership
        entry.status = Entry.STATUS_COMPLETED
        entry.save()