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)
@@ -300,57 +301,66 @@ def handle_products(request, category, products, prefix):
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 = products_form.product_quantities()
quantities = list(products_form.product_quantities())
product_quantities = [
(rego.Product.objects.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 ValidationError as ve:
products_form.add_error(None, ve)
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]
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
current_cart.apply_voucher(voucher)
except Exception as e:
voucher_form.add_error("voucher", e)