Files @ 53413388e016
Branch filter:

Location: symposion_app/registrasion/views.py - annotation

Christopher Neugebauer
Optimises queries through simplifying repeated queries and select_related use
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 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
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
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
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
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
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
be277c17d22d
be277c17d22d
1b7d8a60c119
1b7d8a60c119
941b05786554
1b7d8a60c119
a4de15830c18
fc279b1922d3
a4d684f444e7
1b7d8a60c119
8324b5109474
8324b5109474
be277c17d22d
1b7d8a60c119
8324b5109474
1b7d8a60c119
745f6db444fa
d2d2a1b0ecdd
a4de15830c18
1b7d8a60c119
1b7d8a60c119
1b7d8a60c119
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
12e4d0a3cb24
be277c17d22d
be277c17d22d
be277c17d22d
be277c17d22d
be277c17d22d
be277c17d22d
12e4d0a3cb24
eb530bd4855e
eb530bd4855e
eb530bd4855e
eb530bd4855e
eb530bd4855e
eb530bd4855e
dcad2d5f7cb2
dcad2d5f7cb2
eb530bd4855e
eb530bd4855e
dcad2d5f7cb2
dcad2d5f7cb2
8324b5109474
8324b5109474
dcad2d5f7cb2
8324b5109474
478b328e41a8
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
478b328e41a8
8324b5109474
660e8cb75f67
be277c17d22d
660e8cb75f67
660e8cb75f67
dcad2d5f7cb2
660e8cb75f67
12e4d0a3cb24
12e4d0a3cb24
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
eb530bd4855e
8324b5109474
dcad2d5f7cb2
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
dcad2d5f7cb2
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
8324b5109474
53413388e016
53413388e016
53413388e016
53413388e016
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
6c9a68dc5b2a
6c9a68dc5b2a
6c9a68dc5b2a
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
8324b5109474
eb530bd4855e
8324b5109474
8324b5109474
8324b5109474
12e4d0a3cb24
8324b5109474
8324b5109474
8324b5109474
dcad2d5f7cb2
eb530bd4855e
236c61eefa0d
05923a9a8f58
466c664b680a
466c664b680a
26af6e86720f
26af6e86720f
26af6e86720f
26af6e86720f
26af6e86720f
26af6e86720f
26af6e86720f
466c664b680a
466c664b680a
466c664b680a
466c664b680a
466c664b680a
12e4d0a3cb24
466c664b680a
466c664b680a
466c664b680a
05923a9a8f58
05923a9a8f58
05923a9a8f58
be277c17d22d
3a6b4125e974
05923a9a8f58
05923a9a8f58
05923a9a8f58
be277c17d22d
be277c17d22d
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
89cba55807c1
3a6b4125e974
89cba55807c1
89cba55807c1
be277c17d22d
466c664b680a
89cba55807c1
466c664b680a
466c664b680a
466c664b680a
466c664b680a
466c664b680a
05923a9a8f58
05923a9a8f58
05923a9a8f58
05923a9a8f58
236c61eefa0d
466c664b680a
8d66ed57150d
12e4d0a3cb24
1b7d8a60c119
1b7d8a60c119
eb530bd4855e
eb530bd4855e
1b7d8a60c119
2d6b28c5a6da
2d6b28c5a6da
2d6b28c5a6da
464684f13e7b
464684f13e7b
464684f13e7b
464684f13e7b
464684f13e7b
1b7d8a60c119
1b7d8a60c119
dcad2d5f7cb2
fc279b1922d3
fc279b1922d3
834233cd72a9
fc279b1922d3
b13e6f7ce2c2
26af6e86720f
26af6e86720f
26af6e86720f
2e0144effe14
26af6e86720f
26af6e86720f
26af6e86720f
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
26af6e86720f
26af6e86720f
26af6e86720f
26af6e86720f
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
e0e0d4bf3bb0
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
834233cd72a9
3562772c13cc
1b7d8a60c119
464684f13e7b
464684f13e7b
834233cd72a9
464684f13e7b
53413388e016
464684f13e7b
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
464684f13e7b
834233cd72a9
464684f13e7b
464684f13e7b
834233cd72a9
464684f13e7b
464684f13e7b
834233cd72a9
8796670328dc
8796670328dc
464684f13e7b
464684f13e7b
464684f13e7b
464684f13e7b
834233cd72a9
464684f13e7b
464684f13e7b
464684f13e7b
464684f13e7b
464684f13e7b
834233cd72a9
464684f13e7b
464684f13e7b
eff5686dcf29
834233cd72a9
2d6b28c5a6da
941b05786554
464684f13e7b
834233cd72a9
8d66ed57150d
db332da9584d
834233cd72a9
8796670328dc
a4d684f444e7
53413388e016
53413388e016
53413388e016
53413388e016
8796670328dc
53413388e016
8796670328dc
a4d684f444e7
a4d684f444e7
a4d684f444e7
8796670328dc
8796670328dc
8796670328dc
a4d684f444e7
a4d684f444e7
a4d684f444e7
a4d684f444e7
a4d684f444e7
40bc5985f4b8
40bc5985f4b8
a4d684f444e7
a4d684f444e7
a4d684f444e7
745f6db444fa
db332da9584d
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
b13e6f7ce2c2
8d66ed57150d
db332da9584d
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
a4de15830c18
a4de15830c18
a4de15830c18
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
0340b6da2064
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
d2d2a1b0ecdd
d2d2a1b0ecdd
d2d2a1b0ecdd
d2d2a1b0ecdd
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
a4de15830c18
e0e0d4bf3bb0
e118a4e74c8c
8d66ed57150d
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
d2d2a1b0ecdd
e118a4e74c8c
e118a4e74c8c
e118a4e74c8c
import sys

from registrasion import forms
from registrasion import models as rego
from registrasion.controllers import discount
from registrasion.controllers.cart import CartController
from registrasion.controllers.invoice import InvoiceController
from registrasion.controllers.product import ProductController
from registrasion.exceptions import CartValidationError

from collections import namedtuple

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ValidationError
from django.http import Http404
from django.shortcuts import redirect
from django.shortcuts import render


GuidedRegistrationSection = namedtuple(
    "GuidedRegistrationSection",
    (
        "title",
        "discounts",
        "description",
        "form",
    )
)
GuidedRegistrationSection.__new__.__defaults__ = (
    (None,) * len(GuidedRegistrationSection._fields)
)


def get_form(name):
    dot = name.rindex(".")
    mod_name, form_name = name[:dot], name[dot + 1:]
    __import__(mod_name)
    return getattr(sys.modules[mod_name], form_name)


@login_required
def guided_registration(request, page_id=0):
    ''' Goes through the registration process in order,
    making sure user sees all valid categories.

    WORK IN PROGRESS: the finalised version of this view will allow
    grouping of categories into a specific page. Currently, it just goes
    through each category one by one
    '''

    next_step = redirect("guided_registration")

    sections = []

    attendee = rego.Attendee.get_instance(request.user)

    if attendee.completed_registration:
        return render(
            request,
            "registrasion/guided_registration_complete.html",
            {},
        )

    # Step 1: Fill in a badge and collect a voucher code
    try:
        profile = attendee.attendeeprofilebase
    except ObjectDoesNotExist:
        profile = None

    if not profile:
        # TODO: if voucherform is invalid, make sure
        # that profileform does not save
        voucher_form, voucher_handled = handle_voucher(request, "voucher")
        profile_form, profile_handled = handle_profile(request, "profile")

        voucher_section = GuidedRegistrationSection(
            title="Voucher Code",
            form=voucher_form,
        )

        profile_section = GuidedRegistrationSection(
            title="Profile and Personal Information",
            form=profile_form,
        )

        title = "Attendee information"
        current_step = 1
        sections.append(voucher_section)
        sections.append(profile_section)
    else:
        # We're selling products

        last_category = attendee.highest_complete_category

        # Get the next category
        cats = rego.Category.objects
        cats = cats.filter(id__gt=last_category).order_by("order")

        if cats.count() == 0:
            # We've filled in every category
            attendee.completed_registration = True
            attendee.save()
            return next_step

        if last_category == 0:
            # Only display the first Category
            title = "Select ticket type"
            current_step = 2
            cats = [cats[0]]
        else:
            # Set title appropriately for remaining categories
            current_step = 3
            title = "Additional items"

        all_products = rego.Product.objects.filter(
            category__in=cats,
        ).select_related("category")

        available_products = set(ProductController.available_products(
            request.user,
            products=all_products,
        ))

        for category in cats:
            products = [
                i for i in available_products
                if i.category == category
            ]

            prefix = "category_" + str(category.id)
            p = handle_products(request, category, products, prefix)
            products_form, discounts, products_handled = p

            section = GuidedRegistrationSection(
                title=category.name,
                description=category.description,
                discounts=discounts,
                form=products_form,
            )
            if products:
                # This product category does not exist for this user
                sections.append(section)

            if request.method == "POST" and not products_form.errors:
                if category.id > attendee.highest_complete_category:
                    # This is only saved if we pass each form with no errors.
                    attendee.highest_complete_category = category.id

    if sections and request.method == "POST":
        for section in sections:
            if section.form.errors:
                break
        else:
            attendee.save()
            # We've successfully processed everything
            return next_step

    data = {
        "current_step": current_step,
        "sections": sections,
        "title": title,
        "total_steps": 3,
    }
    return render(request, "registrasion/guided_registration.html", data)


@login_required
def edit_profile(request):
    form, handled = handle_profile(request, "profile")

    if handled and not form.errors:
        messages.success(
            request,
            "Your attendee profile was updated.",
        )
        return redirect("dashboard")

    data = {
        "form": form,
    }
    return render(request, "registrasion/profile_form.html", data)


def handle_profile(request, prefix):
    ''' Returns a profile form instance, and a boolean which is true if the
    form was handled. '''
    attendee = rego.Attendee.get_instance(request.user)

    try:
        profile = attendee.attendeeprofilebase
        profile = rego.AttendeeProfileBase.objects.get_subclass(pk=profile.id)
    except ObjectDoesNotExist:
        profile = None

    ProfileForm = get_form(settings.ATTENDEE_PROFILE_FORM)

    # Load a pre-entered name from the speaker's profile,
    # if they have one.
    try:
        speaker_profile = request.user.speaker_profile
        speaker_name = speaker_profile.name
    except ObjectDoesNotExist:
        speaker_name = None

    name_field = ProfileForm.Meta.model.name_field()
    initial = {}
    if profile is None and name_field is not None:
        initial[name_field] = speaker_name

    form = ProfileForm(
        request.POST or None,
        initial=initial,
        instance=profile,
        prefix=prefix
    )

    handled = True if request.POST else False

    if request.POST and form.is_valid():
        form.instance.attendee = attendee
        form.save()

    return form, handled


@login_required
def product_category(request, category_id):
    ''' Registration selections form for a specific category of items.
    '''

    PRODUCTS_FORM_PREFIX = "products"
    VOUCHERS_FORM_PREFIX = "vouchers"

    # Handle the voucher form *before* listing products.
    # Products can change as vouchers are entered.
    v = handle_voucher(request, VOUCHERS_FORM_PREFIX)
    voucher_form, voucher_handled = v

    category_id = int(category_id)  # Routing is [0-9]+
    category = rego.Category.objects.get(pk=category_id)

    products = ProductController.available_products(
        request.user,
        category=category,
    )

    if not products:
        messages.warning(
            request,
            "There are no products available from category: " + category.name,
        )
        return redirect("dashboard")

    p = handle_products(request, category, products, PRODUCTS_FORM_PREFIX)
    products_form, discounts, products_handled = p

    if request.POST and not voucher_handled and not products_form.errors:
        # Only return to the dashboard if we didn't add a voucher code
        # and if there's no errors in the products form
        messages.success(
            request,
            "Your reservations have been updated.",
        )
        return redirect("dashboard")

    data = {
        "category": category,
        "discounts": discounts,
        "form": products_form,
        "voucher_form": voucher_form,
    }

    return render(request, "registrasion/product_category.html", data)


def handle_products(request, category, products, prefix):
    ''' Handles a products list form in the given request. Returns the
    form instance, the discounts applicable to this form, and whether the
    contents were handled. '''

    current_cart = CartController.for_user(request.user)

    ProductsForm = forms.ProductsForm(category, products)

    # Create initial data for each of products in category
    items = rego.ProductItem.objects.filter(
        product__in=products,
        cart=current_cart.cart,
    ).select_related("product")
    quantities = []
    seen = set()

    for item in items:
        quantities.append((item.product, item.quantity))
        seen.add(item.product)

    zeros = set(products) - seen
    for product in zeros:
        quantities.append((product, 0))

    products_form = ProductsForm(
        request.POST or None,
        product_quantities=quantities,
        prefix=prefix,
    )

    if request.method == "POST" and products_form.is_valid():
        if products_form.has_changed():
            set_quantities_from_products_form(products_form, current_cart)

        # If category is required, the user must have at least one
        # in an active+valid cart
        if category.required:
            carts = rego.Cart.objects.filter(user=request.user)
            items = rego.ProductItem.objects.filter(
                product__category=category,
                cart=carts,
            )
            if len(items) == 0:
                products_form.add_error(
                    None,
                    "You must have at least one item from this category",
                )
    handled = False if products_form.errors else True

    discounts = discount.available_discounts(request.user, [], products)

    return products_form, discounts, handled


def set_quantities_from_products_form(products_form, current_cart):

    quantities = list(products_form.product_quantities())

    pks = [i[0] for i in quantities]
    products = rego.Product.objects.filter(id__in=pks).select_related("category")

    product_quantities = [
        (products.get(pk=i[0]), i[1]) for i in quantities
    ]
    field_names = dict(
        (i[0][0], i[1][2]) for i in zip(product_quantities, quantities)
    )

    try:
        current_cart.set_quantities(product_quantities)
    except CartValidationError as ve:
        for ve_field in ve.error_list:
            product, message = ve_field.message
            if product in field_names:
                field = field_names[product]
            elif isinstance(product, rego.Product):
                continue
            else:
                field = None
            products_form.add_error(field, message)


def handle_voucher(request, prefix):
    ''' Handles a voucher form in the given request. Returns the voucher
    form instance, and whether the voucher code was handled. '''

    voucher_form = forms.VoucherForm(request.POST or None, prefix=prefix)
    current_cart = CartController.for_user(request.user)

    if (voucher_form.is_valid() and
            voucher_form.cleaned_data["voucher"].strip()):

        voucher = voucher_form.cleaned_data["voucher"]
        voucher = rego.Voucher.normalise_code(voucher)

        if len(current_cart.cart.vouchers.filter(code=voucher)) > 0:
            # This voucher has already been applied to this cart.
            # Do not apply code
            handled = False
        else:
            try:
                current_cart.apply_voucher(voucher)
            except Exception as e:
                voucher_form.add_error("voucher", e)
            handled = True
    else:
        handled = False

    return (voucher_form, handled)


@login_required
def checkout(request):
    ''' Runs checkout for the current cart of items, ideally generating an
    invoice. '''

    current_cart = CartController.for_user(request.user)

    if "fix_errors" in request.GET and request.GET["fix_errors"] == "true":
        current_cart.fix_simple_errors()

    try:
        current_invoice = InvoiceController.for_cart(current_cart.cart)
    except ValidationError as ve:
        return checkout_errors(request, ve)

    return redirect("invoice", current_invoice.invoice.id)

def checkout_errors(request, errors):

    error_list = []
    for error in errors.error_list:
        if isinstance(error, tuple):
            error = error[1]
        error_list.append(error)

    data = {
        "error_list": error_list,
    }

    return render(request, "registrasion/checkout_errors.html", data)

@login_required
def invoice(request, invoice_id):
    ''' Displays an invoice for a given invoice id. '''

    invoice_id = int(invoice_id)
    inv = rego.Invoice.objects.get(pk=invoice_id)

    if request.user != inv.cart.user and not request.user.is_staff:
        raise Http404()

    current_invoice = InvoiceController(inv)

    data = {
        "invoice": current_invoice.invoice,
    }

    return render(request, "registrasion/invoice.html", data)


@login_required
def pay_invoice(request, invoice_id):
    ''' Marks the invoice with the given invoice id as paid.
    WORK IN PROGRESS FUNCTION. Must be replaced with real payment workflow.

    '''
    invoice_id = int(invoice_id)
    inv = rego.Invoice.objects.get(pk=invoice_id)
    current_invoice = InvoiceController(inv)
    if not current_invoice.invoice.paid and not current_invoice.invoice.void:
        current_invoice.pay("Demo invoice payment", inv.value)

    return redirect("invoice", current_invoice.invoice.id)