Changeset - 1b404728351e
[Not reviewed]
Merge
0 3 1
Christopher Neugebauer - 8 years ago 2016-08-22 05:03:32
chrisjrn@gmail.com
Merge branch 'chrisjrn/long_and_thin'

Fixes #26
4 files changed with 205 insertions and 28 deletions:
0 comments (0 inline, 0 general)
registrasion/forms.py
Show inline comments
 
from registrasion.models import commerce
 
from registrasion.models import inventory
 

	
 
from django import forms
 
from django.core.exceptions import ValidationError
 

	
 

	
 
class ApplyCreditNoteForm(forms.Form):
 

	
 
    def __init__(self, user, *a, **k):
 
        ''' User: The user whose invoices should be made available as
 
        choices. '''
 
        self.user = user
 
        super(ApplyCreditNoteForm, self).__init__(*a, **k)
 

	
 
        self.fields["invoice"].choices = self._unpaid_invoices_for_user
 

	
 
    def _unpaid_invoices_for_user(self):
 
        invoices = commerce.Invoice.objects.filter(
 
            status=commerce.Invoice.STATUS_UNPAID,
 
            user=self.user,
 
        )
 

	
 
        return [
 
            (invoice.id, "Invoice %(id)d - $%(value)d" % invoice.__dict__)
 
            for invoice in invoices
 
        ]
 

	
 
    invoice = forms.ChoiceField(
 
        required=True,
 
    )
 

	
 

	
 
class ManualCreditNoteRefundForm(forms.ModelForm):
 

	
 
    class Meta:
 
        model = commerce.ManualCreditNoteRefund
 
        fields = ["reference"]
 

	
 

	
 
class ManualPaymentForm(forms.ModelForm):
 

	
 
    class Meta:
 
        model = commerce.ManualPayment
 
        fields = ["reference", "amount"]
 

	
 

	
 
# Products forms -- none of these have any fields: they are to be subclassed
 
# and the fields added as needs be.
 
# and the fields added as needs be. ProductsForm (the function) is responsible
 
# for the subclassing.
 

	
 
class _ProductsForm(forms.Form):
 
def ProductsForm(category, products):
 
    ''' Produces an appropriate _ProductsForm subclass for the given render
 
    type. '''
 

	
 
    # Each Category.RENDER_TYPE value has a subclass here.
 
    RENDER_TYPES = {
 
        inventory.Category.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
 
        inventory.Category.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
 
        inventory.Category.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
 
    }
 

	
 
    # Produce a subclass of _ProductsForm which we can alter the base_fields on
 
    class ProductsForm(RENDER_TYPES[category.render_type]):
 
        pass
 

	
 
    ProductsForm.set_fields(category, products)
 

	
 
    if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
 
        ProductsForm = forms.formset_factory(
 
            ProductsForm,
 
            formset=_ItemQuantityProductsFormSet,
 
        )
 

	
 
    return ProductsForm
 

	
 

	
 
class _HasProductsFields(object):
 

	
 
    PRODUCT_PREFIX = "product_"
 

	
 
    ''' Base class for product entry forms. '''
 
    def __init__(self, *a, **k):
 
        if "product_quantities" in k:
 
            initial = self.initial_data(k["product_quantities"])
 
            k["initial"] = initial
 
            del k["product_quantities"]
 
        super(_ProductsForm, self).__init__(*a, **k)
 
        super(_HasProductsFields, self).__init__(*a, **k)
 

	
 
    @classmethod
 
    def field_name(cls, product):
 
        return cls.PRODUCT_PREFIX + ("%d" % product.id)
 

	
 
    @classmethod
 
    def set_fields(cls, category, products):
 
        ''' Sets the base_fields on this _ProductsForm to allow selecting
 
        from the provided products. '''
 
        pass
 

	
 
    @classmethod
 
    def initial_data(cls, product_quantites):
 
        ''' Prepares initial data for an instance of this form.
 
        product_quantities is a sequence of (product,quantity) tuples '''
 
        return {}
 

	
 
    def product_quantities(self):
 
        ''' Yields a sequence of (product, quantity) tuples from the
 
        cleaned form data. '''
 
        return iter([])
 

	
 
    def add_product_error(self, product, error):
 
        ''' Adds an error to the given product's field '''
 

	
 
        ''' if product in field_names:
 
            field = field_names[product]
 
        elif isinstance(product, inventory.Product):
 
            return
 
        else:
 
            field = None '''
 

	
 
        self.add_error(self.field_name(product), error)
 

	
 

	
 
class _ProductsForm(_HasProductsFields, forms.Form):
 
    pass
 

	
 

	
 
class _QuantityBoxProductsForm(_ProductsForm):
 
    ''' Products entry form that allows users to enter quantities
 
    of desired products. '''
 

	
 
    @classmethod
 
    def set_fields(cls, category, products):
 
        for product in products:
 
            if product.description:
 
                help_text = "$%d each -- %s" % (
 
                    product.price,
 
                    product.description,
 
                )
 
            else:
 
                help_text = "$%d each" % product.price
 

	
 
            field = forms.IntegerField(
 
                label=product.name,
 
                help_text=help_text,
 
                min_value=0,
 
                max_value=500,  # Issue #19. We should figure out real limit.
 
            )
 
            cls.base_fields[cls.field_name(product)] = field
 

	
 
    @classmethod
 
    def initial_data(cls, product_quantities):
 
        initial = {}
 
        for product, quantity in product_quantities:
 
            initial[cls.field_name(product)] = quantity
 

	
 
        return initial
 

	
 
    def product_quantities(self):
 
        for name, value in self.cleaned_data.items():
 
            if name.startswith(self.PRODUCT_PREFIX):
 
                product_id = int(name[len(self.PRODUCT_PREFIX):])
 
                yield (product_id, value, name)
 
                yield (product_id, value)
 

	
 

	
 
class _RadioButtonProductsForm(_ProductsForm):
 
    ''' Products entry form that allows users to enter quantities
 
    of desired products. '''
 

	
 
    FIELD = "chosen_product"
 

	
 
    @classmethod
 
    def set_fields(cls, category, products):
 
        choices = []
 
        for product in products:
 

	
 
            choice_text = "%s -- $%d" % (product.name, product.price)
 
            choices.append((product.id, choice_text))
 

	
 
        if not category.required:
 
            choices.append((0, "No selection"))
 

	
 
        cls.base_fields[cls.FIELD] = forms.TypedChoiceField(
 
            label=category.name,
 
            widget=forms.RadioSelect,
 
            choices=choices,
 
            empty_value=0,
 
            coerce=int,
 
        )
 

	
 
    @classmethod
 
    def initial_data(cls, product_quantities):
 
        initial = {}
 

	
 
        for product, quantity in product_quantities:
 
            if quantity > 0:
 
                initial[cls.FIELD] = product.id
 
                break
 

	
 
        return initial
 

	
 
    def product_quantities(self):
 
        ours = self.cleaned_data[self.FIELD]
 
        choices = self.fields[self.FIELD].choices
 
        for choice_value, choice_display in choices:
 
            if choice_value == 0:
 
                continue
 
            yield (
 
                choice_value,
 
                1 if ours == choice_value else 0,
 
                self.FIELD,
 
            )
 

	
 
    def add_product_error(self, product, error):
 
        self.add_error(cls.FIELD, error)
 

	
 
def ProductsForm(category, products):
 
    ''' Produces an appropriate _ProductsForm subclass for the given render
 
    type. '''
 
class _ItemQuantityProductsForm(_ProductsForm):
 
    ''' Products entry form that allows users to select a product type, and
 
     enter a quantity of that product. This version _only_ allows a single
 
     product type to be purchased. This form is usually used in concert with the
 
     _ItemQuantityProductsFormSet to allow selection of multiple products.'''
 

	
 
    # Each Category.RENDER_TYPE value has a subclass here.
 
    RENDER_TYPES = {
 
        inventory.Category.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
 
        inventory.Category.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
 
    CHOICE_FIELD = "choice"
 
    QUANTITY_FIELD = "quantity"
 

	
 
    @classmethod
 
    def set_fields(cls, category, products):
 
        choices = []
 

	
 
        if not category.required:
 
            choices.append((0, "---"))
 

	
 
        for product in products:
 
            choice_text = "%s -- $%d each" % (product.name, product.price)
 
            choices.append((product.id, choice_text))
 

	
 
        cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField(
 
            label=category.name,
 
            widget=forms.Select,
 
            choices=choices,
 
            initial=0,
 
            empty_value=0,
 
            coerce=int,
 
        )
 

	
 
        cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField(
 
            label="Quantity",  # TODO: internationalise
 
            min_value=0,
 
            max_value=500,  # Issue #19. We should figure out real limit.
 
        )
 

	
 
    @classmethod
 
    def initial_data(cls, product_quantities):
 
        initial = {}
 

	
 
        for product, quantity in product_quantities:
 
            if quantity > 0:
 
                initial[cls.CHOICE_FIELD] = product.id
 
                initial[cls.QUANTITY_FIELD] = quantity
 
                break
 

	
 
        return initial
 

	
 
    def product_quantities(self):
 
        our_choice = self.cleaned_data[self.CHOICE_FIELD]
 
        our_quantity = self.cleaned_data[self.QUANTITY_FIELD]
 
        choices = self.fields[self.CHOICE_FIELD].choices
 
        for choice_value, choice_display in choices:
 
            if choice_value == 0:
 
                continue
 
            yield (
 
                choice_value,
 
                our_quantity if our_choice == choice_value else 0,
 
            )
 

	
 
    def add_product_error(self, product, error):
 
        if self.CHOICE_FIELD not in self.cleaned_data:
 
            return
 

	
 
        if product.id == self.cleaned_data[self.CHOICE_FIELD]:
 
            self.add_error(self.CHOICE_FIELD, error)
 
            self.add_error(self.QUANTITY_FIELD, error)
 

	
 

	
 
class _ItemQuantityProductsFormSet(_HasProductsFields, forms.BaseFormSet):
 

	
 
    @classmethod
 
    def set_fields(cls, category, products):
 
        raise ValueError("set_fields must be called on the underlying Form")
 

	
 
    @classmethod
 
    def initial_data(cls, product_quantities):
 
        ''' Prepares initial data for an instance of this form.
 
        product_quantities is a sequence of (product,quantity) tuples '''
 

	
 
        f = [
 
            {
 
                _ItemQuantityProductsForm.CHOICE_FIELD: product.id,
 
                _ItemQuantityProductsForm.QUANTITY_FIELD: quantity,
 
            }
 
            for product, quantity in product_quantities
 
            if quantity > 0
 
        ]
 
        return f
 

	
 
    # Produce a subclass of _ProductsForm which we can alter the base_fields on
 
    class ProductsForm(RENDER_TYPES[category.render_type]):
 
        pass
 
    def product_quantities(self):
 
        ''' Yields a sequence of (product, quantity) tuples from the
 
        cleaned form data. '''
 

	
 
    ProductsForm.set_fields(category, products)
 
    return ProductsForm
 
        products = set()
 
        # Track everything so that we can yield some zeroes
 
        all_products = set()
 

	
 
        for form in self:
 
            if form.empty_permitted and not form.cleaned_data:
 
                # This is the magical empty form at the end of the list.
 
                continue
 

	
 
            for product, quantity in form.product_quantities():
 
                all_products.add(product)
 
                if quantity == 0:
 
                    continue
 
                if product in products:
 
                    form.add_error(
 
                        _ItemQuantityProductsForm.CHOICE_FIELD,
 
                        "You may only choose each product type once.",
 
                    )
 
                    form.add_error(
 
                        _ItemQuantityProductsForm.QUANTITY_FIELD,
 
                        "You may only choose each product type once.",
 
                    )
 
                products.add(product)
 
                yield product, quantity
 

	
 
        for product in (all_products - products):
 
            yield product, 0
 

	
 
    def add_product_error(self, product, error):
 
        for form in self.forms:
 
            form.add_product_error(product, error)
 

	
 

	
 
class VoucherForm(forms.Form):
 
    voucher = forms.CharField(
 
        label="Voucher code",
 
        help_text="If you have a voucher code, enter it here",
 
        required=False,
 
    )
registrasion/migrations/0002_auto_20160822_0034.py
Show inline comments
 
new file 100644
 
# -*- coding: utf-8 -*-
 
# Generated by Django 1.9.2 on 2016-08-22 00:34
 
from __future__ import unicode_literals
 

	
 
from django.db import migrations, models
 

	
 

	
 
class Migration(migrations.Migration):
 

	
 
    dependencies = [
 
        ('registrasion', '0001_initial'),
 
    ]
 

	
 
    operations = [
 
        migrations.AlterField(
 
            model_name='category',
 
            name='render_type',
 
            field=models.IntegerField(choices=[(1, 'Radio button'), (2, 'Quantity boxes'), (3, 'Product selector and quantity box')], help_text='The registration form will render this category in this style.', verbose_name='Render type'),
 
        ),
 
    ]
registrasion/models/inventory.py
Show inline comments
 
import datetime
 

	
 
from django.db import models
 
from django.utils.encoding import python_2_unicode_compatible
 
from django.utils.translation import ugettext_lazy as _
 

	
 

	
 
# Inventory Models
 

	
 
@python_2_unicode_compatible
 
class Category(models.Model):
 
    ''' Registration product categories, used as logical groupings for Products
 
    in registration forms.
 

	
 
    Attributes:
 
        name (str): The display name for the category.
 

	
 
        description (str): Some explanatory text for the category. This is
 
            displayed alongside the forms where your attendees choose their
 
            items.
 

	
 
        required (bool): Requires a user to select an item from this category
 
            during initial registration. You can use this, e.g., for making
 
            sure that the user has a ticket before they select whether they
 
            want a t-shirt.
 

	
 
        render_type (int): This is used to determine what sort of form the
 
            attendee will be presented with when choosing Products from this
 
            category. These may be either of the following:
 

	
 
            ``RENDER_TYPE_RADIO`` presents the Products in the Category as a
 
            list of radio buttons. At most one item can be chosen at a time.
 
            This works well when setting limit_per_user to 1.
 

	
 
            ``RENDER_TYPE_QUANTITY`` shows each Product next to an input field,
 
            where the user can specify a quantity of each Product type. This is
 
            useful for additional extras, like Dinner Tickets.
 

	
 
            ``RENDER_TYPE_ITEM_QUANTITY`` shows a select menu to select a
 
            Product type, and an input field, where the user can specify the
 
            quantity for that Product type. This is useful for categories that
 
            have a lot of options, from which the user is not going to select
 
            all of the options.
 

	
 
        limit_per_user (Optional[int]): This restricts the number of items
 
            from this Category that each attendee may claim. This extends
 
            across multiple Invoices.
 

	
 
        display_order (int): An ascending order for displaying the Categories
 
            available. By convention, your Category for ticket types should
 
            have the lowest display order.
 
    '''
 

	
 
    class Meta:
 
        app_label = "registrasion"
 
        verbose_name = _("inventory - category")
 
        verbose_name_plural = _("inventory - categories")
 
        ordering = ("order", )
 

	
 
    def __str__(self):
 
        return self.name
 

	
 
    RENDER_TYPE_RADIO = 1
 
    RENDER_TYPE_QUANTITY = 2
 
    RENDER_TYPE_ITEM_QUANTITY = 3
 

	
 
    CATEGORY_RENDER_TYPES = [
 
        (RENDER_TYPE_RADIO, _("Radio button")),
 
        (RENDER_TYPE_QUANTITY, _("Quantity boxes")),
 
        (RENDER_TYPE_ITEM_QUANTITY, _("Product selector and quantity box")),
 
    ]
 

	
 
    name = models.CharField(
 
        max_length=65,
 
        verbose_name=_("Name"),
 
    )
 
    description = models.CharField(
 
        max_length=255,
 
        verbose_name=_("Description"),
 
    )
 
    limit_per_user = models.PositiveIntegerField(
 
        null=True,
 
        blank=True,
 
        verbose_name=_("Limit per user"),
 
        help_text=_("The total number of items from this category one "
 
                    "attendee may purchase."),
 
    )
 
    required = models.BooleanField(
 
        blank=True,
 
        help_text=_("If enabled, a user must select an "
 
                    "item from this category."),
 
    )
 
    order = models.PositiveIntegerField(
 
        verbose_name=("Display order"),
 
        db_index=True,
 
    )
 
    render_type = models.IntegerField(
 
        choices=CATEGORY_RENDER_TYPES,
 
        verbose_name=_("Render type"),
 
        help_text=_("The registration form will render this category in this "
 
                    "style."),
 
    )
 

	
 

	
 
@python_2_unicode_compatible
 
class Product(models.Model):
 
    ''' Products make up the conference inventory.
 

	
 
    Attributes:
 
        name (str): The display name for the product.
 

	
 
        description (str): Some descriptive text that will help the user to
 
            understand the product when they're at the registration form.
 

	
 
        category (Category): The Category that this product will be grouped
 
            under.
 

	
 
        price (Decimal): The price that 1 unit of this product will sell for.
 
            Note that this should be the full price, before any discounts are
 
            applied.
 

	
 
        limit_per_user (Optional[int]): This restricts the number of this
 
            Product that each attendee may claim. This extends across multiple
 
            Invoices.
 

	
 
        reservation_duration (datetime): When a Product is added to the user's
 
            tentative registration, it is marked as unavailable for a period of
 
            time. This allows the user to build up their registration and then
 
            pay for it. This reservation duration determines how long an item
 
            should be allowed to be reserved whilst being unpaid.
 

	
 
        display_order (int): An ascending order for displaying the Products
 
            within each Category.
 

	
 
    '''
 

	
 
    class Meta:
 
        app_label = "registrasion"
 
        verbose_name = _("inventory - product")
 
        ordering = ("category__order", "order")
 

	
 
    def __str__(self):
 
        return "%s - %s" % (self.category.name, self.name)
 

	
 
    name = models.CharField(
 
        max_length=65,
 
        verbose_name=_("Name"),
 
    )
 
    description = models.CharField(
 
        max_length=255,
 
        verbose_name=_("Description"),
 
        null=True,
 
        blank=True,
 
    )
 
    category = models.ForeignKey(
 
        Category,
 
        verbose_name=_("Product category")
 
    )
 
    price = models.DecimalField(
 
        max_digits=8,
 
        decimal_places=2,
 
        verbose_name=_("Price"),
 
    )
 
    limit_per_user = models.PositiveIntegerField(
 
        null=True,
 
        blank=True,
 
        verbose_name=_("Limit per user"),
 
    )
 
    reservation_duration = models.DurationField(
 
        default=datetime.timedelta(hours=1),
 
        verbose_name=_("Reservation duration"),
 
        help_text=_("The length of time this product will be reserved before "
 
                    "it is released for someone else to purchase."),
 
    )
 
    order = models.PositiveIntegerField(
 
        verbose_name=("Display order"),
 
        db_index=True,
 
    )
 

	
 

	
 
@python_2_unicode_compatible
 
class Voucher(models.Model):
 
    ''' Vouchers are used to enable Discounts or Flags for the people who hold
 
    the voucher code.
 

	
 
    Attributes:
 
        recipient (str): A display string used to identify the holder of the
 
            voucher on the admin page.
 

	
 
        code (str): The string that is used to prove that the attendee holds
 
            this voucher.
 

	
 
        limit (int): The number of attendees who are permitted to hold this
 
            voucher.
 

	
 
     '''
 

	
 
    class Meta:
 
        app_label = "registrasion"
 

	
 
    # Vouchers reserve a cart for a fixed amount of time, so that
 
    # items may be added without the voucher being swiped by someone else
 
    RESERVATION_DURATION = datetime.timedelta(hours=1)
 

	
 
    def __str__(self):
 
        return "Voucher for %s" % self.recipient
 

	
 
    @classmethod
 
    def normalise_code(cls, code):
 
        return code.upper()
 

	
 
    def save(self, *a, **k):
 
        ''' Normalise the voucher code to be uppercase '''
 
        self.code = self.normalise_code(self.code)
 
        super(Voucher, self).save(*a, **k)
 

	
 
    recipient = models.CharField(max_length=64, verbose_name=_("Recipient"))
 
    code = models.CharField(max_length=16,
 
                            unique=True,
 
                            verbose_name=_("Voucher code"))
 
    limit = models.PositiveIntegerField(verbose_name=_("Voucher use limit"))
registrasion/views.py
Show inline comments
...
 
@@ -257,411 +257,407 @@ def edit_profile(request):
 
            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 = people.Attendee.get_instance(request.user)
 

	
 
    try:
 
        profile = attendee.attendeeprofilebase
 
        profile = people.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):
 
    ''' Form for selecting products from an individual product category.
 

	
 
    Arguments:
 
        category_id (castable to int): The id of the category to display.
 

	
 
    Returns:
 
        redirect or render:
 
            If the form has been sucessfully submitted, redirect to
 
            ``dashboard``. Otherwise, render
 
            ``registrasion/product_category.html`` with data::
 

	
 
                {
 
                    "category": category,         # An inventory.Category for
 
                                                  # category_id
 
                    "discounts": discounts,       # A list of
 
                                                  # DiscountAndQuantity
 
                    "form": products_form,        # A form for selecting
 
                                                  # products
 
                    "voucher_form": voucher_form, # A form for entering a
 
                                                  # voucher code
 
                }
 

	
 
    '''
 

	
 
    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 = inventory.Category.objects.get(pk=category_id)
 

	
 
    with BatchController.batch(request.user):
 
        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 = commerce.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 = commerce.Cart.objects.filter(user=request.user)
 
            items = commerce.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
 

	
 
    # Making this a function to lazily evaluate when it's displayed
 
    # in templates.
 

	
 
    discounts = util.lazy(
 
        DiscountController.available_discounts,
 
        request.user,
 
        [],
 
        products,
 
    )
 

	
 
    return products_form, discounts, handled
 

	
 

	
 
def _set_quantities_from_products_form(products_form, current_cart):
 

	
 
    # Makes id_to_quantity, a dictionary from product ID to its quantity
 
    quantities = list(products_form.product_quantities())
 
    id_to_quantity = dict(i[:2] for i in quantities)
 
    id_to_quantity = dict(quantities)
 

	
 
    # Get the actual product objects
 
    pks = [i[0] for i in quantities]
 
    products = inventory.Product.objects.filter(
 
        id__in=pks,
 
    ).select_related("category").order_by("id")
 

	
 
    quantities.sort(key = lambda i: i[0])
 

	
 
    # Match the product objects to their quantities
 
    product_quantities = [
 
        (product, id_to_quantity[product.id]) for product in products
 
    ]
 
    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, inventory.Product):
 
                continue
 
            else:
 
                field = None
 
            products_form.add_error(field, message)
 
            products_form.add_product_error(product, 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 = inventory.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 the checkout process for the current cart.
 

	
 
    If the query string contains ``fix_errors=true``, Registrasion will attempt
 
    to fix errors preventing the system from checking out, including by
 
    cancelling expired discounts and vouchers, and removing any unavailable
 
    products.
 

	
 
    Returns:
 
        render or redirect:
 
            If the invoice is generated successfully, or there's already a
 
            valid invoice for the current cart, redirect to ``invoice``.
 
            If there are errors when generating the invoice, render
 
            ``registrasion/checkout_errors.html`` with the following data::
 

	
 
                {
 
                    "error_list", [str, ...]  # The errors to display.
 
                }
 

	
 
    '''
 

	
 
    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)
 

	
 

	
 
def invoice_access(request, access_code):
 
    ''' Redirects to an invoice for the attendee that matches the given access
 
    code, if any.
 

	
 
    If the attendee has multiple invoices, we use the following tie-break:
 

	
 
    - If there's an unpaid invoice, show that, otherwise
 
    - If there's a paid invoice, show the most recent one, otherwise
 
    - Show the most recent invoid of all
 

	
 
    Arguments:
 

	
 
        access_code (castable to int): The access code for the user whose
 
            invoice you want to see.
 

	
 
    Returns:
 
        redirect:
 
            Redirect to the selected invoice for that user.
 

	
 
    Raises:
 
        Http404: If the user has no invoices.
 
    '''
 

	
 
    invoices = commerce.Invoice.objects.filter(
 
        user__attendee__access_code=access_code,
 
    ).order_by("-issue_time")
 

	
 
    if not invoices:
 
        raise Http404()
 

	
 
    unpaid = invoices.filter(status=commerce.Invoice.STATUS_UNPAID)
 
    paid = invoices.filter(status=commerce.Invoice.STATUS_PAID)
 

	
 
    if unpaid:
 
        invoice = unpaid[0]  # (should only be 1 unpaid invoice?)
 
    elif paid:
 
        invoice = paid[0]  # Most recent paid invoice
 
    else:
 
        invoice = invoices[0]  # Most recent of any invoices
 

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

	
 

	
 
def invoice(request, invoice_id, access_code=None):
 
    ''' Displays an invoice.
 

	
 
    This view is not authenticated, but it will only allow access to either:
 
    the user the invoice belongs to; staff; or a request made with the correct
 
    access code.
 

	
 
    Arguments:
 

	
 
        invoice_id (castable to int): The invoice_id for the invoice you want
 
            to view.
 

	
 
        access_code (Optional[str]): The access code for the user who owns
 
            this invoice.
 

	
 
    Returns:
 
        render:
 
            Renders ``registrasion/invoice.html``, with the following
 
            data::
 

	
 
                {
 
                    "invoice": models.commerce.Invoice(),
 
                }
 

	
 
    Raises:
 
        Http404: if the current user cannot view this invoice and the correct
 
            access_code is not provided.
 

	
 
    '''
 

	
 
    current_invoice = InvoiceController.for_id_or_404(invoice_id)
 

	
 
    if not current_invoice.can_view(
 
            user=request.user,
 
            access_code=access_code,
 
            ):
 
        raise Http404()
 

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

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

	
 

	
 
def _staff_only(user):
 
    ''' Returns true if the user is staff. '''
 
    return user.is_staff
 

	
 

	
 
@user_passes_test(_staff_only)
 
def manual_payment(request, invoice_id):
 
    ''' Allows staff to make manual payments or refunds on an invoice.
 

	
 
    This form requires a login, and the logged in user needs to be staff.
 

	
 
    Arguments:
 
        invoice_id (castable to int): The invoice ID to be paid
 

	
 
    Returns:
 
        render:
 
            Renders ``registrasion/manual_payment.html`` with the following
 
            data::
 

	
 
                {
 
                    "invoice": models.commerce.Invoice(),
 
                    "form": form,   # A form that saves a ``ManualPayment``
 
                                    # object.
0 comments (0 inline, 0 general)