services.py 11.2 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
8
9
10
11
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
12
from payments.models import Payment
13
14
from registrations import emails
from registrations.models import Entry, Registration, Renewal
15
from utils.snippets import datetime_to_lectureyear
16
17
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
80
81
82
83
84
85
86
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


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


def reject_entries(queryset):
    """
    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:
        try:
            emails.send_registration_rejected_message(entry.registration)
        except Registration.DoesNotExist:
            try:
                emails.send_renewal_rejected_message(entry.renewal)
            except Renewal.DoesNotExist:
                pass

    return rows_updated


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

123
124
125
        entry.status = Entry.STATUS_ACCEPTED
        entry.updated_at = timezone.now()
        entry.payment = _create_payment_for_entry(entry)
126

127
128
129
130
131
132
        try:
            if entry.registration.username is None:
                entry.registration.username = _generate_username(
                    entry.registration)
                entry.registration.save()
            emails.send_registration_accepted_message(entry.registration,
133
                                                      entry.payment)
134
135
        except Registration.DoesNotExist:
            try:
136
137
                emails.send_renewal_accepted_message(entry.renewal,
                                                     entry.payment)
138
139
140
            except Renewal.DoesNotExist:
                pass

141
        entry.save()
142
143
        updated_entries.append(entry.pk)

144
    return len(updated_entries)
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


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]

    try:
        renewal = entry.renewal
        membership = renewal.member.latest_membership
        # 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

180
    return Payment.objects.create(
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
        amount=amount,
    )


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,
        phone_number=registration.phone_number,
        birthday=registration.birthday,
224
225
226
        language=registration.language,
        show_birthday=registration.optin_birthday,
        receive_optin=registration.optin_mailinglist
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    )

    # 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')
263
                since = membership.until
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
299
        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
    )


300
def process_payment(payment):
301
302
303
    """
    Process the payment for the entry and send the right emails

304
305
    :param payment: The payment that should be processed
    :type payment: Payment
306
307
    """

308
309
    if not payment.processed:
        return
310

311
312
313
314
    try:
        entry = payment.registrations_entry
    except Entry.DoesNotExist:
        return
315

316
317
    if entry.status != Entry.STATUS_ACCEPTED:
        return
318

319
    member = None
320

321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
    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
336

337
338
339
340
341
342
    # If member was retrieved, then create a new membership
    if member is not None:
        membership = _create_membership_from_entry(entry, member)
        entry.membership = membership
        entry.status = Entry.STATUS_COMPLETED
        entry.save()