Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Move logic from discount view to form and checkout

Michał Ociepkafe0a4f1c1689
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.py
index 0a0f559284..b511fdcdac 100644
--- a/saleor/checkout/core.py
+++ b/saleor/checkout/core.py
@@ -9,6 +9,7 @@ from prices import Price, FixedDiscount
from ..cart import Cart
from ..core import analytics
from ..order.models import Order
+from saleor.discount.models import Voucher, NotApplicable
from ..shipping.models import ShippingMethodCountry
from ..userprofile.models import Address, User
@@ -224,6 +225,21 @@ class Checkout(object):
return order
+ def recalculate_discount(self):
+ voucher_code = self.voucher_code
+ if voucher_code is not None:
+ try:
+ voucher = Voucher.objects.get(code=voucher_code)
+ except Voucher.DoesNotExist:
+ del self.voucher_code
+ del self.discount
+ else:
+ try:
+ self.discount = voucher.get_discount_for_checkout(self)
+ except NotApplicable:
+ del self.discount
+ del self.voucher_code
+
def get_subtotal(self):
zero = Price(0, currency=settings.DEFAULT_CURRENCY)
cost_iterator = (
diff --git a/saleor/checkout/views/discount.py b/saleor/checkout/views/discount.py
index ae6e0f01bf..2c09c2b628 100644
--- a/saleor/checkout/views/discount.py
+++ b/saleor/checkout/views/discount.py
@@ -5,7 +5,6 @@ from django.shortcuts import redirect
from django.template.response import TemplateResponse
from ...discount.forms import CheckoutDiscountForm
-from ...discount.models import Voucher, NotApplicable
def add_voucher_form(view):
@@ -42,10 +41,7 @@ def apply_voucher_view(request, checkout):
request.POST or None, checkout=checkout, prefix='discount')
next_url = request.GET.get('next', request.META['HTTP_REFERER'])
if voucher_form.is_valid():
- discount = voucher_form.cleaned_data['discount']
- voucher = voucher_form.cleaned_data['voucher']
- checkout.discount = discount
- checkout.voucher_code = voucher.code
+ voucher_form.apply_discount()
else:
for error in voucher_form.errors['voucher']:
messages.error(request, error, extra_tags='discount')
diff --git a/saleor/discount/forms.py b/saleor/discount/forms.py
index 95dd6258c1..a9afa61619 100644
--- a/saleor/discount/forms.py
+++ b/saleor/discount/forms.py
@@ -25,6 +25,7 @@ class CheckoutDiscountForm(forms.Form):
initial = kwargs.get('initial', {})
if 'voucher' not in initial:
initial['voucher'] = self.checkout.voucher_code
+ kwargs['initial'] = initial
super(CheckoutDiscountForm, self).__init__(*args, **kwargs)
def clean(self):
@@ -37,3 +38,9 @@ class CheckoutDiscountForm(forms.Form):
except NotApplicable as e:
self.add_error('voucher', str(e))
return cleaned_data
+
+ def apply_discount(self):
+ discount = self.cleaned_data['discount']
+ voucher = self.cleaned_data['voucher']
+ self.checkout.discount = discount
+ self.checkout.voucher_code = voucher.code