Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor exception handling
Patryk Zawadzki3a15cf8fc471
diff --git a/cart/__init__.py b/cart/__init__.pyindex 03f3b9f742..3fc22c6610 100755--- a/cart/__init__.py+++ b/cart/__init__.py@@ -1,34 +1,26 @@-from decimal import Decimalfrom django.conf import settingsfrom django.utils.translation import ugettext as _-from satchless.item import ItemSet, ItemLinefrom satchless import cart-class InvalidQuantityException(Exception):+class InsufficientStockException(Exception):- def __init__(self, reason, quantity_delta):- super(InvalidQuantityException, self).__init__(reason)- self.quantity_delta = quantity_delta+ def __init__(self, product):+ super(InsufficientStockException, self).__init__(+ 'Insufficient stock for %r' % (product,))+ self.product = productclass Cart(cart.Cart):SESSION_KEY = 'cart'- modified = Falsedef __unicode__(self):return _('Cart (%(cart_count)s)' % {'cart_count': self.count()})def check_quantity(self, product, quantity, data=None):if quantity > product.stock:- raise InvalidQuantityException(- _(u'Only %(total)s of product in stock.' % {- 'total':product.stock- }),- product.stock - quantity- )-+ raise InsufficientStockException(product)return super(Cart, self).check_quantity(product, quantity, data)def get_default_currency(self):@@ -42,4 +34,3 @@ def get_cart_from_request(request):_cart = Cart()request.session[Cart.SESSION_KEY] = _cartreturn _cart-diff --git a/cart/forms.py b/cart/forms.pyindex 2bac3e2c9d..6664cd709d 100644--- a/cart/forms.py+++ b/cart/forms.py@@ -1,4 +1,4 @@-from . import InvalidQuantityException+from . import InsufficientStockExceptionfrom decimal import Decimalfrom django import formsfrom django.forms.formsets import BaseFormSet@@ -15,6 +15,8 @@ class AddToCartForm(forms.Form):quantity = QuantityField(_('Form field', 'quantity'), min_value=Decimal(0),max_digits=10, decimal_places=4,initial=Decimal(1))+ error_messages = {+ 'insufficient-stock': _('Only %(remaining)d remaining in stock.')}def __init__(self, *args, **kwargs):self.cart = kwargs.pop('cart')@@ -25,36 +27,36 @@ class AddToCartForm(forms.Form):def clean_quantity(self):quantity = self.cleaned_data['quantity']-+ if self.cart_line:+ new_quantity = quantity + self.cart_line.quantity+ else:+ new_quantity = quantitytry:- self.cart.check_quantity(self.product,- quantity + self.cart_line.quantity if- self.cart_line else quantity)- except InvalidQuantityException as e:- raise forms.ValidationError(e)-+ self.cart.check_quantity(self.product, new_quantity)+ except InsufficientStockException as e:+ remaining = e.product.stock - quantity+ msg = self.error_messages['insufficient-stock']+ raise forms.ValidationError(msg % {'remaining': remaining})return quantitydef save(self):- return self.cart.add_line(self.product,- self.cleaned_data['quantity'])+ return self.cart.add(self.product, self.cleaned_data['quantity'])class ReplaceCartLineForm(AddToCartForm):def clean_quantity(self):quantity = self.cleaned_data['quantity']-try:self.cart.check_quantity(self.product, quantity)- except InvalidQuantityException as e:- raise forms.ValidationError(e)-+ except InsufficientStockException as e:+ msg = self.error_messages['insufficient-stock']+ raise forms.ValidationError(msg % {'remaining': e.product.stock})return quantitydef save(self):- return self.cart.add_line(self.product,- self.cleaned_data['quantity'], replace=True)+ return self.cart.add(self.product, self.cleaned_data['quantity'],+ replace=True)class ReplaceCartLineFormSet(BaseFormSet):@@ -67,9 +69,8 @@ class ReplaceCartLineFormSet(BaseFormSet):def __init__(self, *args, **kwargs):self.cart = kwargs.pop('cart')- kwargs['initial'] = [{'quantity':cart_line.get_quantity()} for- cart_line in self.cart]-+ kwargs['initial'] = [{'quantity': cart_line.get_quantity()}+ for cart_line in self.cart]super(ReplaceCartLineFormSet, self).__init__(*args, **kwargs)def _construct_form(self, i, **kwargs):