File diff 760996588372 → a4d684f444e7
registrasion/controllers/cart.py
Show inline comments
 
import collections
 
import datetime
 
import discount
 
import itertools
 

	
 
from django.core.exceptions import ObjectDoesNotExist
 
from django.core.exceptions import ValidationError
 
from django.db import transaction
 
from django.db.models import Max
 
from django.utils import timezone
 

	
 
from registrasion import models as rego
 
from registrasion.exceptions import CartValidationError
 

	
 
from category import CategoryController
 
from conditions import ConditionController
 
from product import ProductController
 

	
 

	
 
class CartController(object):
 

	
 
    def __init__(self, cart):
 
        self.cart = cart
 

	
 
    @classmethod
 
    def for_user(cls, user):
 
        ''' Returns the user's current cart, or creates a new cart
 
        if there isn't one ready yet. '''
 

	
 
        try:
 
            existing = rego.Cart.objects.get(user=user, active=True)
 
        except ObjectDoesNotExist:
 
            existing = rego.Cart.objects.create(
 
                user=user,
 
                time_last_updated=timezone.now(),
 
                reservation_duration=datetime.timedelta(),
 
                 )
...
 
@@ -93,95 +94,104 @@ class CartController(object):
 

	
 
        for product, quantity in product_quantities:
 
            try:
 
                product_item = rego.ProductItem.objects.get(
 
                    cart=self.cart,
 
                    product=product,
 
                )
 
                product_item.quantity = quantity
 
                product_item.save()
 
            except ObjectDoesNotExist:
 
                rego.ProductItem.objects.create(
 
                    cart=self.cart,
 
                    product=product,
 
                    quantity=quantity,
 
                )
 

	
 
        items_in_cart.filter(quantity=0).delete()
 

	
 
        self.end_batch()
 

	
 
    def _test_limits(self, product_quantities):
 
        ''' Tests that the quantity changes we intend to make do not violate
 
        the limits and enabling conditions imposed on the products. '''
 

	
 
        errors = []
 

	
 
        # Test each product limit here
 
        for product, quantity in product_quantities:
 
            if quantity < 0:
 
                # TODO: batch errors
 
                raise ValidationError("Value must be zero or greater.")
 
                errors.append((product, "Value must be zero or greater."))
 

	
 
            prod = ProductController(product)
 
            limit = prod.user_quantity_remaining(self.cart.user)
 

	
 
            if quantity > limit:
 
                # TODO: batch errors
 
                raise ValidationError(
 
                errors.append((
 
                    product,
 
                    "You may only have %d of product: %s" % (
 
                        limit, product.name,
 
                        limit, product,
 
                    )
 
                )
 
                ))
 

	
 
        # Collect by category
 
        by_cat = collections.defaultdict(list)
 
        for product, quantity in product_quantities:
 
            by_cat[product.category].append((product, quantity))
 

	
 
        # Test each category limit here
 
        for cat in by_cat:
 
            ctrl = CategoryController(cat)
 
        for category in by_cat:
 
            ctrl = CategoryController(category)
 
            limit = ctrl.user_quantity_remaining(self.cart.user)
 

	
 
            # Get the amount so far in the cart
 
            to_add = sum(i[1] for i in by_cat[cat])
 
            to_add = sum(i[1] for i in by_cat[category])
 

	
 
            if to_add > limit:
 
                # TODO: batch errors
 
                raise ValidationError(
 
                errors.append((
 
                    category,
 
                    "You may only have %d items in category: %s" % (
 
                        limit, cat.name,
 
                        limit, category.name,
 
                    )
 
                )
 
                ))
 

	
 
        # Test the enabling conditions
 
        errs = ConditionController.test_enabling_conditions(
 
            self.cart.user,
 
            product_quantities=product_quantities,
 
        )
 

	
 
        if errs:
 
            # TODO: batch errors
 
            raise ValidationError("An enabling condition failed")
 
            errors.append(
 
                ("enabling_conditions", "An enabling condition failed")
 
            )
 

	
 
        if errors:
 
            raise CartValidationError(errors)
 

	
 
    def apply_voucher(self, voucher_code):
 
        ''' Applies the voucher with the given code to this cart. '''
 

	
 
        # Is voucher exhausted?
 
        active_carts = rego.Cart.reserved_carts()
 

	
 
        # Try and find the voucher
 
        voucher = rego.Voucher.objects.get(code=voucher_code.upper())
 

	
 
        # It's invalid for a user to enter a voucher that's exhausted
 
        carts_with_voucher = active_carts.filter(vouchers=voucher)
 
        if len(carts_with_voucher) >= voucher.limit:
 
            raise ValidationError("This voucher is no longer available")
 

	
 
        # It's not valid for users to re-enter a voucher they already have
 
        user_carts_with_voucher = rego.Cart.objects.filter(
 
            user=self.cart.user,
 
            released=False,
 
            vouchers=voucher,
 
        )
 
        if len(user_carts_with_voucher) > 0:
 
            raise ValidationError("You have already entered this voucher.")