Changeset - 4cdbdb71ceee
[Not reviewed]
0 6 0
Christopher Neugebauer - 8 years ago 2016-04-25 07:37:33
chrisjrn@gmail.com
flake8 fixes
6 files changed with 20 insertions and 16 deletions:
0 comments (0 inline, 0 general)
registrasion/controllers/discount.py
Show inline comments
 
import itertools
 

	
 
from conditions import ConditionController
 
from registrasion.models import commerce
 
from registrasion.models import conditions
 

	
 
from django.db.models import Sum
 

	
 

	
 
class DiscountAndQuantity(object):
 
    def __init__(self, discount, clause, quantity):
 
        self.discount = discount
 
        self.clause = clause
 
        self.quantity = quantity
 

	
 
    def __repr__(self):
 
        return "(discount=%s, clause=%s, quantity=%d)" % (
 
            self.discount, self.clause, self.quantity,
 
        )
 

	
 

	
 
def available_discounts(user, categories, products):
 
    ''' Returns all discounts available to this user for the given categories
 
    and products. The discounts also list the available quantity for this user,
 
    not including products that are pending purchase. '''
 

	
 
    # discounts that match provided categories
 
    category_discounts = conditions.DiscountForCategory.objects.filter(
 
        category__in=categories
 
    )
 
    # discounts that match provided products
 
    product_discounts = conditions.DiscountForProduct.objects.filter(
 
        product__in=products
 
    )
 
    # discounts that match categories for provided products
 
    product_category_discounts = conditions.DiscountForCategory.objects.filter(
 
        category__in=(product.category for product in products)
 
    )
 
    # (Not relevant: discounts that match products in provided categories)
 

	
 
    product_discounts = product_discounts.select_related(
 
        "product",
 
        "product__category",
 
    )
 

	
 
    all_category_discounts = category_discounts | product_category_discounts
 
    all_category_discounts = all_category_discounts.select_related(
 
        "category",
 
    )
 

	
 
    # The set of all potential discounts
 
    potential_discounts = set(itertools.chain(
 
        product_discounts,
 
        all_category_discounts,
 
    ))
 

	
 
    discounts = []
 

	
 
    # Markers so that we don't need to evaluate given conditions more than once
 
    accepted_discounts = set()
 
    failed_discounts = set()
 

	
 
    for discount in potential_discounts:
 
        real_discount = conditions.DiscountBase.objects.get_subclass(
 
            pk=discount.discount.pk,
 
        )
 
        cond = ConditionController.for_condition(real_discount)
 

	
 
        # Count the past uses of the given discount item.
 
        # If this user has exceeded the limit for the clause, this clause
 
        # is not available any more.
 
        past_uses = commerce.DiscountItem.objects.filter(
 
            cart__user=user,
 
            cart__status=commerce.Cart.STATUS_PAID, # Only past carts count
 
            cart__status=commerce.Cart.STATUS_PAID,  # Only past carts count
 
            discount=real_discount,
 
        )
 
        agg = past_uses.aggregate(Sum("quantity"))
 
        past_use_count = agg["quantity__sum"]
 
        if past_use_count is None:
 
            past_use_count = 0
 

	
 
        if past_use_count >= discount.quantity:
 
            # This clause has exceeded its use count
 
            pass
 
        elif real_discount not in failed_discounts:
 
            # This clause is still available
 
            if real_discount in accepted_discounts or cond.is_met(user):
 
                # This clause is valid for this user
 
                discounts.append(DiscountAndQuantity(
 
                    discount=real_discount,
 
                    clause=discount,
 
                    quantity=discount.quantity - past_use_count,
 
                ))
 
                accepted_discounts.add(real_discount)
 
            else:
 
                # This clause is not valid for this user
 
                failed_discounts.add(real_discount)
 
    return discounts
registrasion/templatetags/registrasion_tags.py
Show inline comments
 
from registrasion.models import commerce
 
from registrasion.models import inventory
 
from registrasion.controllers.category import CategoryController
 

	
 
from collections import namedtuple
 
from django import template
 
from django.db.models import Sum
 

	
 
register = template.Library()
 

	
 
_ProductAndQuantity = namedtuple("ProductAndQuantity", ["product", "quantity"])
 

	
 

	
 
class ProductAndQuantity(_ProductAndQuantity):
 
    ''' Class that holds a product and a quantity.
 

	
 
    Attributes:
 
        product (models.inventory.Product)
 

	
 
        quantity (int)
 

	
 
    '''
 
    pass
 

	
 

	
 
@register.assignment_tag(takes_context=True)
 
def available_categories(context):
 
    ''' Gets all of the currently available products.
 

	
 
    Returns:
 
        [models.inventory.Category, ...]: A list of all of the categories that
 
            have Products that the current user can reserve.
 

	
 
    '''
 
    return CategoryController.available_categories(context.request.user)
 

	
 

	
 
@register.assignment_tag(takes_context=True)
 
def available_credit(context):
 
    ''' Calculates the sum of unclaimed credit from this user's credit notes.
 

	
 
    Returns:
 
        Decimal: the sum of the values of unclaimed credit notes for the
 
            current user.
 

	
 
    '''
 

	
 
    notes = commerce.CreditNote.unclaimed().filter(
 
        invoice__user=context.request.user,
 
    )
 
    ret = notes.values("amount").aggregate(Sum("amount"))["amount__sum"] or 0
 
    return 0 - ret
 

	
 

	
 
@register.assignment_tag(takes_context=True)
 
def invoices(context):
 
    '''
 

	
 
    Returns:
 
        [models.commerce.Invoice, ...]: All of the current user's invoices. '''
 
    return commerce.Invoice.objects.filter(user=context.request.user)
 

	
 

	
 
@register.assignment_tag(takes_context=True)
 
def items_pending(context):
 
    ''' Gets all of the items that the user has reserved, but has not yet
 
    paid for.
 

	
 
    Returns:
 
        [ProductAndQuantity, ...]: A list of product-quantity pairs for the
 
            items that the user has not yet paid for.
 

	
 
    '''
 

	
 
    all_items = commerce.ProductItem.objects.filter(
 
        cart__user=context.request.user,
 
        cart__status=commerce.Cart.STATUS_ACTIVE,
 
    ).select_related(
 
        "product",
 
        "product__category",
 
    ).order_by(
 
        "product__category__order",
 
        "product__order",
 
    )
 
    return all_items
 

	
 

	
 
@register.assignment_tag(takes_context=True)
 
def items_purchased(context, category=None):
 
    ''' Aggregates the items that this user has purchased.
 

	
 
    Arguments:
 
        category (Optional[models.inventory.Category]): the category of items
 
            to restrict to.
 

	
 
    Returns:
 
        [ProductAndQuantity, ...]: A list of product-quantity pairs,
 
            aggregating like products from across multiple invoices.
 

	
 
    '''
 

	
 
    all_items = commerce.ProductItem.objects.filter(
 
        cart__user=context.request.user,
 
        cart__status=commerce.Cart.STATUS_PAID,
 
    ).select_related("product", "product__category")
 

	
 
    if category:
 
        all_items = all_items.filter(product__category=category)
 

	
registrasion/tests/test_cart.py
Show inline comments
 
import datetime
 
import pytz
 

	
 
from decimal import Decimal
 
from django.contrib.auth.models import User
 
from django.core.exceptions import ObjectDoesNotExist
 
from django.core.exceptions import ValidationError
 
from django.core.management import call_command
 
from django.test import TestCase
 

	
 
from registrasion.models import commerce
 
from registrasion.models import conditions
 
from registrasion.models import inventory
 
from registrasion.models import people
 
from registrasion.controllers.product import ProductController
 

	
 
from controller_helpers import TestingCartController
 
from patch_datetime import SetTimeMixin
 

	
 
UTC = pytz.timezone('UTC')
 

	
 

	
 
class RegistrationCartTestCase(SetTimeMixin, TestCase):
 

	
 
    def setUp(self):
 
        super(RegistrationCartTestCase, self).setUp()
 

	
 
    def tearDown(self):
 
        if False:
 
        if True:
 
            # If you're seeing segfaults in tests, enable this.
 
            call_command('flush', verbosity=0, interactive=False,
 
                             reset_sequences=False,
 
                             allow_cascade=False,
 
                             inhibit_post_migrate=False)
 
            call_command(
 
                'flush',
 
                verbosity=0,
 
                interactive=False,
 
                reset_sequences=False,
 
                allow_cascade=False,
 
                inhibit_post_migrate=False
 
            )
 

	
 
        super(RegistrationCartTestCase, self).tearDown()
 

	
 
    @classmethod
 
    def setUpTestData(cls):
 

	
 
        super(RegistrationCartTestCase, cls).setUpTestData()
 

	
 
        cls.USER_1 = User.objects.create_user(
 
            username='testuser',
 
            email='test@example.com',
 
            password='top_secret')
 

	
 
        cls.USER_2 = User.objects.create_user(
 
            username='testuser2',
 
            email='test2@example.com',
 
            password='top_secret')
 

	
 
        attendee1 = people.Attendee.get_instance(cls.USER_1)
 
        profile1 = people.AttendeeProfileBase.objects.create(
 
        people.AttendeeProfileBase.objects.create(
 
            attendee=attendee1,
 
        )
 
        attendee2 = people.Attendee.get_instance(cls.USER_2)
 
        profile2 = people.AttendeeProfileBase.objects.create(
 
        people.AttendeeProfileBase.objects.create(
 
            attendee=attendee2,
 
        )
 

	
 
        cls.RESERVATION = datetime.timedelta(hours=1)
 

	
 
        cls.categories = []
 
        for i in xrange(2):
 
            cat = inventory.Category.objects.create(
 
                name="Category " + str(i + 1),
 
                description="This is a test category",
 
                order=i,
 
                render_type=inventory.Category.RENDER_TYPE_RADIO,
 
                required=False,
 
            )
 
            cls.categories.append(cat)
 

	
 
        cls.CAT_1 = cls.categories[0]
 
        cls.CAT_2 = cls.categories[1]
 

	
 
        cls.products = []
 
        for i in xrange(4):
 
            prod = inventory.Product.objects.create(
 
                name="Product " + str(i + 1),
 
                description="This is a test product.",
 
                category=cls.categories[i / 2],  # 2 products per category
 
                price=Decimal("10.00"),
 
                reservation_duration=cls.RESERVATION,
 
                limit_per_user=10,
 
                order=1,
 
            )
 
            cls.products.append(prod)
 

	
 
        cls.PROD_1 = cls.products[0]
 
        cls.PROD_2 = cls.products[1]
 
        cls.PROD_3 = cls.products[2]
 
        cls.PROD_4 = cls.products[3]
 

	
 
        cls.PROD_4.price = Decimal("5.00")
 
        cls.PROD_4.save()
 

	
 
        # Burn through some carts -- this made some past flag tests fail
 
        current_cart = TestingCartController.for_user(cls.USER_1)
 

	
 
        current_cart.next_cart()
 

	
 
        current_cart = TestingCartController.for_user(cls.USER_2)
 

	
 
        current_cart.next_cart()
 

	
 
    @classmethod
 
    def make_ceiling(cls, name, limit=None, start_time=None, end_time=None):
 
        limit_ceiling = conditions.TimeOrStockLimitFlag.objects.create(
 
            description=name,
 
            condition=conditions.FlagBase.DISABLE_IF_FALSE,
 
            limit=limit,
 
            start_time=start_time,
 
            end_time=end_time
 
        )
 
        limit_ceiling.products.add(cls.PROD_1, cls.PROD_2)
 

	
 
    @classmethod
 
    def make_category_ceiling(
 
            cls, name, limit=None, start_time=None, end_time=None):
 
        limit_ceiling = conditions.TimeOrStockLimitFlag.objects.create(
 
            description=name,
 
            condition=conditions.FlagBase.DISABLE_IF_FALSE,
 
            limit=limit,
 
            start_time=start_time,
 
            end_time=end_time
 
        )
 
        limit_ceiling.categories.add(cls.CAT_1)
 

	
 
    @classmethod
 
    def make_discount_ceiling(
 
            cls, name, limit=None, start_time=None, end_time=None,
 
            percentage=100):
 
        limit_ceiling = conditions.TimeOrStockLimitDiscount.objects.create(
 
            description=name,
 
            start_time=start_time,
 
            end_time=end_time,
 
            limit=limit,
 
        )
 
        conditions.DiscountForProduct.objects.create(
 
            discount=limit_ceiling,
 
            product=cls.PROD_1,
 
            percentage=percentage,
 
            quantity=10,
 
        )
 

	
 
    @classmethod
 
    def new_voucher(self, code="VOUCHER", limit=1):
 
        voucher = inventory.Voucher.objects.create(
 
            recipient="Voucher recipient",
 
            code=code,
 
            limit=limit,
 
        )
registrasion/tests/test_invoice.py
Show inline comments
...
 
@@ -391,145 +391,145 @@ class InvoiceTestCase(RegistrationCartTestCase):
 
        # Create a new cart with invoice, pay it
 
        invoice_2 = self._invoice_containing_prod_1(1)
 
        invoice_2.pay("LOL", invoice_2.invoice.value)
 

	
 
        # Cannot pay paid invoice
 
        with self.assertRaises(ValidationError):
 
            cn.apply_to_invoice(invoice_2.invoice)
 

	
 
        invoice_2.refund()
 
        # Cannot pay refunded invoice
 
        with self.assertRaises(ValidationError):
 
            cn.apply_to_invoice(invoice_2.invoice)
 

	
 
        # Create a new cart with invoice
 
        invoice_2 = self._invoice_containing_prod_1(1)
 
        invoice_2.void()
 
        # Cannot pay void invoice
 
        with self.assertRaises(ValidationError):
 
            cn.apply_to_invoice(invoice_2.invoice)
 

	
 
    def test_cannot_apply_a_refunded_credit_note(self):
 
        invoice = self._invoice_containing_prod_1(1)
 

	
 
        to_pay = invoice.invoice.value
 
        invoice.pay("Reference", to_pay)
 
        self.assertTrue(invoice.invoice.is_paid)
 

	
 
        invoice.refund()
 

	
 
        self.assertEquals(1, commerce.CreditNote.unclaimed().count())
 

	
 
        cn = self._credit_note_for_invoice(invoice.invoice)
 

	
 
        cn.refund()
 

	
 
        # Refunding a credit note should mark it as claimed
 
        self.assertEquals(0, commerce.CreditNote.unclaimed().count())
 

	
 
        # Create a new cart with invoice
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_1, 1)
 

	
 
        invoice_2 = TestingInvoiceController.for_cart(self.reget(cart.cart))
 

	
 
        # Cannot pay with this credit note.
 
        with self.assertRaises(ValidationError):
 
            cn.apply_to_invoice(invoice_2.invoice)
 

	
 
    def test_cannot_refund_an_applied_credit_note(self):
 
        invoice = self._invoice_containing_prod_1(1)
 

	
 
        to_pay = invoice.invoice.value
 
        invoice.pay("Reference", to_pay)
 
        self.assertTrue(invoice.invoice.is_paid)
 

	
 
        invoice.refund()
 

	
 
        self.assertEquals(1, commerce.CreditNote.unclaimed().count())
 

	
 
        cn = self._credit_note_for_invoice(invoice.invoice)
 

	
 
        # Create a new cart with invoice
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_1, 1)
 

	
 
        invoice_2 = TestingInvoiceController.for_cart(self.reget(cart.cart))
 
        cn.apply_to_invoice(invoice_2.invoice)
 

	
 
        self.assertEquals(0, commerce.CreditNote.unclaimed().count())
 

	
 
        # Cannot refund this credit note as it is already applied.
 
        with self.assertRaises(ValidationError):
 
            cn.refund()
 

	
 
    def test_money_into_void_invoice_generates_credit_note(self):
 
        invoice = self._invoice_containing_prod_1(1)
 
        invoice.void()
 

	
 
        val = invoice.invoice.value
 

	
 
        invoice.pay("Paying into the void.", val, pre_validate=False)
 
        cn = self._credit_note_for_invoice(invoice.invoice)
 
        self.assertEqual(val, cn.credit_note.value)
 

	
 
    def test_money_into_refunded_invoice_generates_credit_note(self):
 
        invoice = self._invoice_containing_prod_1(1)
 

	
 
        val = invoice.invoice.value
 

	
 
        invoice.pay("Paying the first time.", val)
 
        invoice.refund()
 

	
 
        cnval = val - 1
 
        invoice.pay("Paying into the void.", cnval, pre_validate=False)
 

	
 
        notes = commerce.CreditNote.objects.filter(invoice=invoice.invoice)
 
        notes = sorted(notes, key = lambda note: note.value)
 
        notes = sorted(notes, key=lambda note: note.value)
 

	
 
        self.assertEqual(cnval, notes[0].value)
 
        self.assertEqual(val, notes[1].value)
 

	
 
    def test_money_into_paid_invoice_generates_credit_note(self):
 
        invoice = self._invoice_containing_prod_1(1)
 

	
 
        val = invoice.invoice.value
 

	
 
        invoice.pay("Paying the first time.", val)
 

	
 
        invoice.pay("Paying into the void.", val, pre_validate=False)
 
        cn = self._credit_note_for_invoice(invoice.invoice)
 
        self.assertEqual(val, cn.credit_note.value)
 

	
 
    def test_required_category_constraints_prevent_invoicing(self):
 
        self.CAT_1.required = True
 
        self.CAT_1.save()
 

	
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_3, 1)
 

	
 
        # CAT_1 is required, we don't have CAT_1 yet
 
        with self.assertRaises(ValidationError):
 
            invoice = TestingInvoiceController.for_cart(cart.cart)
 

	
 
        # Now that we have CAT_1, we can check out the cart
 
        cart.add_to_cart(self.PROD_1, 1)
 
        invoice = TestingInvoiceController.for_cart(cart.cart)
 

	
 
        # Paying for the invoice should work fine
 
        invoice.pay("Boop", invoice.invoice.value)
 

	
 
        # We have an item in the first cart, so should be able to invoice
 
        # for the second cart, even without CAT_1 in it.
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_3, 1)
 

	
 
        invoice2 = TestingInvoiceController.for_cart(cart.cart)
 

	
 
        # Void invoice2, and release the first cart
 
        # now we don't have any CAT_1
 
        invoice2.void()
 
        invoice.refund()
 

	
 
        # Now that we don't have CAT_1, we can't checkout this cart
 
        with self.assertRaises(ValidationError):
 
            invoice = TestingInvoiceController.for_cart(cart.cart)
registrasion/views.py
Show inline comments
 
import sys
 

	
 
from registrasion import forms
 
from registrasion import util
 
from registrasion.models import commerce
 
from registrasion.models import inventory
 
from registrasion.models import people
 
from registrasion.controllers import discount
 
from registrasion.controllers.cart import CartController
 
from registrasion.controllers.credit_note import CreditNoteController
 
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.auth.decorators import user_passes_test
 
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 get_object_or_404
 
from django.shortcuts import redirect
 
from django.shortcuts import render
 

	
 

	
 
_GuidedRegistrationSection = namedtuple(
 
    "GuidedRegistrationSection",
 
    (
 
        "title",
 
        "discounts",
 
        "description",
 
        "form",
 
    )
 
)
 

	
 

	
 
@util.all_arguments_optional
 
class GuidedRegistrationSection(_GuidedRegistrationSection):
 
    ''' Represents a section of a guided registration page.
 

	
 
    Attributes:
 
        title (str): The title of the section.
 
       title (str): The title of the section.
 

	
 
        discounts ([registrasion.contollers.discount.DiscountAndQuantity, ...]):
 
       discounts ([registrasion.contollers.discount.DiscountAndQuantity, ...]):
 
            A list of discount objects that are available in the section. You
 
            can display ``.clause`` to show what the discount applies to, and
 
            ``.quantity`` to display the number of times that discount can be
 
            applied.
 

	
 
        description (str): A description of the section.
 
       description (str): A description of the section.
 

	
 
        form (forms.Form): A form to display.
 
       form (forms.Form): A form to display.
 
    '''
 
    pass
 

	
 

	
 
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):
 
    ''' Goes through the registration process in order, making sure user sees
 
    all valid categories.
 

	
 
    The user must be logged in to see this view.
 

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

	
 
                {
 
                    "current_step": int(),  # The current step in the
 
                                            # registration
 
                    "sections": sections,   # A list of
 
                                            # GuidedRegistrationSections
 
                    "title": str(),         # The title of the page
 
                    "total_steps": int(),   # The total number of steps
 
                }
 

	
 
    '''
 

	
 
    SESSION_KEY = "guided_registration_categories"
 
    ASK_FOR_PROFILE = 777  # Magic number. Meh.
 

	
 
    next_step = redirect("guided_registration")
 

	
 
    sections = []
 

	
 
    attendee = people.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
 

	
 
    # Figure out if we need to show the profile form and the voucher form
 
    show_profile_and_voucher = False
 
    if SESSION_KEY not in request.session:
 
        if not profile:
 
            show_profile_and_voucher = True
 
    else:
 
        if request.session[SESSION_KEY] == ASK_FOR_PROFILE:
 
            show_profile_and_voucher = True
 

	
 
    if show_profile_and_voucher:
 
        # Keep asking for the profile until everything passes.
 
        request.session[SESSION_KEY] = ASK_FOR_PROFILE
 

	
 
        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
 

	
 
        starting = attendee.guided_categories_complete.count() == 0
 

	
 
        # Get the next category
 
        cats = inventory.Category.objects
 
        if SESSION_KEY in request.session:
 
            _cats = request.session[SESSION_KEY]
 
            cats = cats.filter(id__in=_cats)
 
        else:
...
 
@@ -476,258 +475,258 @@ def _handle_voucher(request, prefix):
 
        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.
 
                }
 

	
 
    '''
 

	
 
    FORM_PREFIX = "manual_payment"
 

	
 
    current_invoice = InvoiceController.for_id_or_404(invoice_id)
 

	
 
    form = forms.ManualPaymentForm(
 
        request.POST or None,
 
        prefix=FORM_PREFIX,
 
    )
 

	
 
    if request.POST and form.is_valid():
 
        form.instance.invoice = current_invoice.invoice
 
        form.instance.entered_by = request.user
 
        form.save()
 
        current_invoice.update_status()
 
        form = forms.ManualPaymentForm(prefix=FORM_PREFIX)
 

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

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

	
 

	
 
@user_passes_test(_staff_only)
 
def refund(request, invoice_id):
 
    ''' Marks an invoice as refunded and requests a credit note for the
 
    full amount paid against the invoice.
 

	
 
    This view requires a login, and the logged in user must be staff.
 

	
 
    Arguments:
 
        invoice_id (castable to int): The ID of the invoice to refund.
 

	
 
    Returns:
 
        redirect:
 
            Redirects to ``invoice``.
 

	
 
    '''
 

	
 
    current_invoice = InvoiceController.for_id_or_404(invoice_id)
 

	
 
    try:
 
        current_invoice.refund()
 
        messages.success(request, "This invoice has been refunded.")
 
    except ValidationError as ve:
 
        messages.error(request, ve)
 

	
 
    return redirect("invoice", invoice_id)
 

	
 

	
 
@user_passes_test(_staff_only)
 
def credit_note(request, note_id, access_code=None):
 
    ''' Displays a credit note.
 

	
 
    If ``request`` is a ``POST`` request, forms for applying or refunding
 
    a credit note will be processed.
 

	
 
    This view requires a login, and the logged in user must be staff.
 

	
 
    Arguments:
 
        note_id (castable to int): The ID of the credit note to view.
 

	
 
    Returns:
 
        render or redirect:
 
            If the "apply to invoice" form is correctly processed, redirect to
 
            that invoice, otherwise, render ``registration/credit_note.html``
 
            with the following data::
 

	
 
                {
 
                    "credit_note": models.commerce.CreditNote(),
 
                    "apply_form": form,  # A form for applying credit note
 
                                         # to an invoice.
 
                    "refund_form": form, # A form for applying a *manual*
setup.cfg
Show inline comments
 
[flake8]
 
exclude = registrasion/migrations/*, build/*
 
exclude = registrasion/migrations/*, build/*, docs/*
0 comments (0 inline, 0 general)