From 39021cd3dd3e03047ba602ec16822eff52759c89 Mon Sep 17 00:00:00 2001 From: Christopher Neugebauer Date: Sat, 2 Apr 2016 13:39:42 +1100 Subject: [PATCH] Adds set_quantities, refactors set_quantity in terms of set_quantities --- registrasion/controllers/cart.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/registrasion/controllers/cart.py b/registrasion/controllers/cart.py index 45796781..aec77c07 100644 --- a/registrasion/controllers/cart.py +++ b/registrasion/controllers/cart.py @@ -3,6 +3,7 @@ import discount 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 @@ -57,17 +58,40 @@ class CartController(object): def end_batch(self): ''' Performs operations that occur occur at the end of a batch of - product changes/voucher applications etc. ''' + product changes/voucher applications etc. + THIS SHOULD BE PRIVATE + ''' + self.recalculate_discounts() self.extend_reservation() self.cart.revision += 1 self.cart.save() + @transaction.atomic + def set_quantities(self, product_quantities): + + # Remove all items that we're updating + rego.ProductItem.objects.filter( + cart=self.cart, + product__in=(i[0] for i in product_quantities), + ).delete() + + for product, quantity in product_quantities: + self._set_quantity_old(product, quantity) + + self.end_batch() + def set_quantity(self, product, quantity, batched=False): ''' Sets the _quantity_ of the given _product_ in the cart to the given _quantity_. ''' + self.set_quantities( ((product,quantity),) ) + + def _set_quantity_old(self, product, quantity): + ''' Sets the _quantity_ of the given _product_ in the cart to the given + _quantity_. ''' + if quantity < 0: raise ValidationError("Cannot have fewer than 0 items in cart.") @@ -106,9 +130,6 @@ class CartController(object): product_item.quantity = quantity product_item.save() - if not batched: - self.end_batch() - def add_to_cart(self, product, quantity): ''' Adds _quantity_ of the given _product_ to the cart. Raises ValidationError if constraints are violated.'''