Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove Checkout class
Anna Siwik7c1d4e79876c
diff --git a/saleor/cart/checkout/core.py b/saleor/cart/checkout/core.pydeleted file mode 100644index 7d345725f3..0000000000--- a/saleor/cart/checkout/core.py+++ /dev/null@@ -1,207 +0,0 @@-"""Checkout session state management."""-from datetime import date-from functools import wraps--from django.db import transaction-from django.utils.encoding import smart_text-from django.utils.translation import get_language--from ...account.utils import store_user_address-from ...core import analytics-from ...core.utils.taxes import get_taxes_for_country-from ...discount.models import Voucher-from ...discount.utils import increase_voucher_usage-from ...order.models import Order-from ...order.utils import add_variant_to_order-from ..models import Cart-from ..utils import get_or_empty_db_cart-from .utils import get_voucher_for_cart--STORAGE_SESSION_KEY = 'checkout_storage'---class Checkout:- """Represents a checkout session.-- This object acts a temporary storage for the entire checkout session. An- order instance is only created when the user confirms their order and is- ready to pay.-- `VERSION` is used to prevent code trying to work with incompatible- checkout structures.-- The `modified` attribute keeps track of when checkout state changes and- needs to be saved.- """-- VERSION = '1.0.0'-- def __init__(self, cart, user, discounts, taxes, tracking_code):- self.modified = False- self.cart = cart- self.user = user- self.discounts = discounts- self.taxes = taxes- self.tracking_code = tracking_code- self.storage = {'version': self.VERSION}-- @classmethod- def from_storage(- cls, storage_data, cart, user, discounts, taxes, tracking_code):- """Restore a previously serialized checkout session.-- `storage_data` is the value previously returned by- `Checkout.for_storage()`.- """- checkout = cls(cart, user, discounts, taxes, tracking_code)- checkout.storage = storage_data- try:- version = checkout.storage['version']- except (TypeError, KeyError):- version = None- if version != cls.VERSION:- checkout.storage = {'version': cls.VERSION}- return checkout-- def for_storage(self):- """Serialize a checkout session to allow persistence.-- The session can later be restored using `Checkout.from_storage()`.- """- return self.storage-- def clear_storage(self):- """Discard the entire state."""- self.storage = None- self.modified = True-- @transaction.atomic- def create_order(self):- """Create an order from the checkout session.-- Each order will get a private copy of both the billing and the shipping- address (if shipping ).-- If any of the addresses is new and the user is logged in the address- will also get saved to that user's address book.-- Current user's language is saved in the order so we can later determine- which language to use when sending email.- """- # FIXME: save locale along with the language- voucher = get_voucher_for_cart(- self.cart,- vouchers=Voucher.objects.active(- date=date.today()).select_for_update())-- if self.cart.voucher_code is not None and voucher is None:- # Voucher expired in meantime, abort order placement- return None-- billing_address = self.cart.billing_address-- if self.cart.is_shipping_required():- shipping_address = self.cart.shipping_address- shipping_method = self.cart.shipping_method- shipping_method_name = smart_text(shipping_method)- else:- shipping_address = None- shipping_method = None- shipping_method_name = None-- if self.cart.user:- if (- shipping_address and- shipping_address not in self.cart.user.addresses.all()- ):- store_user_address(- self.user, shipping_address, shipping=True)- if billing_address not in self.cart.user.addresses.all():- store_user_address(- self.user, billing_address, billing=True)- if shipping_address:- shipping_address = shipping_address.get_copy()- billing_address = billing_address.get_copy()-- taxes = self.get_taxes()-- order_data = {- 'language_code': get_language(),- 'billing_address': billing_address,- 'shipping_address': shipping_address,- 'tracking_client_id': self.tracking_code,- 'shipping_method': shipping_method,- 'shipping_method_name': shipping_method_name,- 'shipping_price': self.cart.get_shipping_price(taxes),- 'total': self.get_total()}-- if self.user.is_authenticated:- order_data['user'] = self.user- order_data['user_email'] = self.user.email- else:- order_data['user_email'] = self.cart.user_email-- if voucher is not None:- order_data['voucher'] = voucher- order_data['discount_amount'] = self.cart.discount_amount- order_data['discount_name'] = self.cart.discount_name-- order = Order.objects.create(**order_data)-- for line in self.cart.lines.all():- add_variant_to_order(- order, line.variant, line.quantity, self.discounts, taxes,- add_to_existing=False)-- if voucher is not None:- increase_voucher_usage(voucher)-- if self.cart.note:- order.notes.create(user=order.user, content=self.cart.note)-- return order-- def get_subtotal(self):- """Calculate order total without shipping and discount."""- return self.cart.get_total(self.discounts, self.get_taxes())-- def get_total(self):- """Calculate order total with shipping and discount amount."""- total = self.get_subtotal()- total += self.cart.get_shipping_price(self.get_taxes())- total -= self.cart.discount_amount- return total-- def get_taxes(self):- """Return taxes based on shipping address (if set) or IP country."""- if self.cart.shipping_address:- return get_taxes_for_country(self.cart.shipping_address.country)-- return self.taxes---def load_checkout(view):- """Decorate view with checkout session and cart for each request.-- Any views decorated by this will change their signature from- `func(request)` to `func(request, cart, checkout)`.- """- # FIXME: behave like middleware and assign checkout and cart to request- # instead of changing the view signature- @wraps(view)- @get_or_empty_db_cart(Cart.objects.for_display())- def func(request, cart):- try:- session_data = request.session[STORAGE_SESSION_KEY]- except KeyError:- session_data = ''- tracking_code = analytics.get_client_id(request)- checkout = Checkout.from_storage(- session_data, cart, request.user, request.discounts, request.taxes,- tracking_code)- response = view(request, cart, checkout)- if checkout.modified:- request.session[STORAGE_SESSION_KEY] = checkout.for_storage()- return response-- return funcdiff --git a/saleor/cart/checkout/forms.py b/saleor/cart/checkout/forms.pyindex 108dfda33a..2aa842a8d9 100644--- a/saleor/cart/checkout/forms.py+++ b/saleor/cart/checkout/forms.py@@ -5,7 +5,7 @@ from django.utils.encoding import smart_textfrom django.utils.safestring import mark_safefrom django.utils.translation import pgettext_lazy-from ...cart.checkout.utils import get_voucher_discount_for_checkout+from ...cart.checkout.utils import get_voucher_discount_for_cartfrom ...cart.models import Cartfrom ...core.utils import format_moneyfrom ...core.utils.taxes import display_gross_prices@@ -152,7 +152,8 @@ class VoucherField(forms.ModelChoiceField):}-class CheckoutDiscountForm(forms.ModelForm):+class CartVoucherForm(forms.ModelForm):+ """Apply voucher to a cart form."""voucher = VoucherField(queryset=Voucher.objects.none(),@@ -167,11 +168,6 @@ class CheckoutDiscountForm(forms.ModelForm):fields = ['voucher']def __init__(self, *args, **kwargs):- self.checkout = kwargs.pop('checkout')- initial = kwargs.get('initial', {})- if 'voucher' not in initial:- initial['voucher'] = self.instance.voucher_code- kwargs['initial'] = initialsuper().__init__(*args, **kwargs)self.fields['voucher'].queryset = Voucher.objects.active(date=date.today())@@ -181,10 +177,9 @@ class CheckoutDiscountForm(forms.ModelForm):if 'voucher' in cleaned_data:voucher = cleaned_data['voucher']try:- discount = get_voucher_discount_for_checkout(- voucher, self.checkout)- cleaned_data['discount'] = discount- cleaned_data['discount_name'] = voucher.name+ discount_amount = get_voucher_discount_for_cart(+ voucher, self.instance)+ cleaned_data['discount_amount'] = discount_amountexcept NotApplicable as e:self.add_error('voucher', smart_text(e))return cleaned_data@@ -192,6 +187,6 @@ class CheckoutDiscountForm(forms.ModelForm):def save(self, commit=True):voucher = self.cleaned_data['voucher']self.instance.voucher_code = voucher.code- self.instance.discount_amount = self.cleaned_data['discount']- self.instance.discount_name = self.cleaned_data['discount_name']+ self.instance.discount_name = voucher.name+ self.instance.discount_amount = self.cleaned_data['discount_amount']return super().save(commit)diff --git a/saleor/cart/checkout/utils.py b/saleor/cart/checkout/utils.pyindex 88989a787a..5bc8ac44f9 100644--- a/saleor/cart/checkout/utils.py+++ b/saleor/cart/checkout/utils.py@@ -1,14 +1,20 @@from datetime import date-from django.utils.translation import pgettext+from django.db import transaction+from django.utils.encoding import smart_text+from django.utils.translation import get_language, pgettext+from ...account.utils import store_user_addressfrom ...cart.utils import (get_category_variants_and_prices, get_product_variants_and_prices)+from ...core.utils.taxes import ZERO_MONEY, get_taxes_for_countryfrom ...discount import VoucherTypefrom ...discount.models import NotApplicable, Voucherfrom ...discount.utils import (get_product_or_category_voucher_discount, get_shipping_voucher_discount,- get_value_voucher_discount)+ get_value_voucher_discount, increase_voucher_usage)+from ...order.models import Order+from ...order.utils import add_variant_to_orderdef save_billing_address_in_cart(cart, address):@@ -55,29 +61,31 @@ def get_checkout_data(cart, discounts, taxes):"""Data shared between views in checkout process."""lines = [(line, line.get_total(discounts, taxes)) for line in cart.lines.all()]- subtotal = cart.get_total(discounts, taxes)+ subtotal = cart.get_subtotal(discounts, taxes)+ total = cart.get_total(discounts, taxes)shipping_price = cart.get_shipping_price(taxes)return {'cart': cart,'cart_are_taxes_handled': bool(taxes),'cart_lines': lines,+ 'cart_shipping_price': shipping_price,'cart_subtotal': subtotal,- 'cart_shipping_price': shipping_price}+ 'cart_total': total}-def _get_value_voucher_discount_for_checkout(voucher, checkout):+def _get_value_voucher_discount_for_cart(voucher, cart):"""Calculate discount value for a voucher of value type."""- return get_value_voucher_discount(voucher, checkout.get_subtotal())+ return get_value_voucher_discount(voucher, cart.get_subtotal())-def _get_shipping_voucher_discount_for_checkout(voucher, checkout):+def _get_shipping_voucher_discount_for_cart(voucher, cart):"""Calculate discount value for a voucher of shipping type."""- if not checkout.cart.is_shipping_required():+ if not cart.is_shipping_required():msg = pgettext('Voucher not applicable','Your order does not require shipping.')raise NotApplicable(msg)- shipping_method = checkout.cart.shipping_method+ shipping_method = cart.shipping_methodif not shipping_method:msg = pgettext('Voucher not applicable',@@ -92,19 +100,19 @@ def _get_shipping_voucher_discount_for_checkout(voucher, checkout):raise NotApplicable(msg % {'country': voucher.get_apply_to_display()})return get_shipping_voucher_discount(- voucher, checkout.get_subtotal(), shipping_method.get_total_price())+ voucher, cart.get_subtotal(), shipping_method.get_total_price())-def _get_product_or_category_voucher_discount_for_checkout(voucher, checkout):+def _get_product_or_category_voucher_discount_for_cart(voucher, cart):"""Calculate discount value for a voucher of product or category type."""if voucher.type == VoucherType.PRODUCT:prices = [variant_price for _, variant_price in- get_product_variants_and_prices(checkout.cart, voucher.product)]+ get_product_variants_and_prices(cart, voucher.product)]else:prices = [variant_price for _, variant_price in- get_category_variants_and_prices(checkout.cart, voucher.category)]+ get_category_variants_and_prices(cart, voucher.category)]if not prices:msg = pgettext('Voucher not applicable',@@ -113,18 +121,18 @@ def _get_product_or_category_voucher_discount_for_checkout(voucher, checkout):return get_product_or_category_voucher_discount(voucher, prices)-def get_voucher_discount_for_checkout(voucher, checkout):+def get_voucher_discount_for_cart(voucher, cart):"""Calculate discount value depending on voucher and discount types.Raise NotApplicable if voucher of given type cannot be applied."""if voucher.type == VoucherType.VALUE:- return _get_value_voucher_discount_for_checkout(voucher, checkout)+ return _get_value_voucher_discount_for_cart(voucher, cart)if voucher.type == VoucherType.SHIPPING:- return _get_shipping_voucher_discount_for_checkout(voucher, checkout)+ return _get_shipping_voucher_discount_for_cart(voucher, cart)if voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):- return _get_product_or_category_voucher_discount_for_checkout(- voucher, checkout)+ return _get_product_or_category_voucher_discount_for_cart(+ voucher, cart)raise NotImplementedError('Unknown discount type')@@ -140,18 +148,16 @@ def get_voucher_for_cart(cart, vouchers=None):return None-def recalculate_cart_discount(cart, checkout):+def recalculate_cart_discount(cart):"""Recalculate `cart.discount` based on the voucher.Will clear both voucher and discount if the discount is no longerapplicable."""voucher = get_voucher_for_cart(cart)-if voucher is not None:try:- cart.discount_amount = get_voucher_discount_for_checkout(- voucher, checkout)+ cart.discount_amount = get_voucher_discount_for_cart(voucher, cart)cart.discount_name = voucher.namecart.save()except NotApplicable:@@ -162,7 +168,97 @@ def recalculate_cart_discount(cart, checkout):def remove_discount_from_cart(cart):"""Remove voucher data from cart."""- cart.discount_amount = 0- cart.discount_name = ''- cart.voucher_code = ''+ cart.discount_amount = ZERO_MONEY+ cart.discount_name = None+ cart.voucher_code = Nonecart.save()+++def get_taxes_for_cart(cart, default_taxes):+ """Return taxes based on shipping address (if set) or default one."""+ if cart.shipping_address:+ return get_taxes_for_country(cart.shipping_address.country)++ return default_taxes+++def create_order(cart, tracking_code, discounts, taxes):+ """Create an order from the cart.++ Each order will get a private copy of both the billing and the shipping+ address (if shipping).++ If any of the addresses is new and the user is logged in the address+ will also get saved to that user's address book.++ Current user's language is saved in the order so we can later determine+ which language to use when sending email.+ """+ # FIXME: save locale along with the language+ voucher = get_voucher_for_cart(+ cart, vouchers=Voucher.objects.active(+ date=date.today()).select_for_update())++ if cart.voucher_code and not voucher:+ # Voucher expired in meantime, abort order placement+ return None++ billing_address = cart.billing_address++ if cart.is_shipping_required():+ shipping_address = cart.shipping_address+ shipping_method = cart.shipping_method+ shipping_method_name = smart_text(shipping_method)+ else:+ shipping_address = None+ shipping_method = None+ shipping_method_name = None++ if cart.user:+ if (+ shipping_address and+ shipping_address not in cart.user.addresses.all()+ ):+ store_user_address(cart.user, shipping_address, shipping=True)+ if billing_address not in cart.user.addresses.all():+ store_user_address(cart.user, billing_address, billing=True)+ if shipping_address:+ shipping_address = shipping_address.get_copy()+ billing_address = billing_address.get_copy()++ order_data = {+ 'language_code': get_language(),+ 'billing_address': billing_address,+ 'shipping_address': shipping_address,+ 'tracking_client_id': tracking_code,+ 'shipping_method': shipping_method,+ 'shipping_method_name': shipping_method_name,+ 'shipping_price': cart.get_shipping_price(taxes),+ 'total': cart.get_total(taxes=taxes)}++ if cart.user:+ order_data['user'] = cart.user+ order_data['user_email'] = cart.user.email+ else:+ order_data['user_email'] = cart.user_email++ if voucher is not None:+ order_data['voucher'] = voucher+ order_data['discount_amount'] = cart.discount_amount+ order_data['discount_name'] = cart.discount_name++ order = Order.objects.create(**order_data)++ for line in cart.lines.all():+ add_variant_to_order(+ order, line.variant, line.quantity, discounts, taxes,+ add_to_existing=False)++ if voucher is not None:+ increase_voucher_usage(voucher)++ if cart.note:+ order.notes.create(user=order.user, content=cart.note)++ return orderdiff --git a/saleor/cart/checkout/views/__init__.py b/saleor/cart/checkout/views/__init__.pyindex 8feac2883c..3c5725b200 100644--- a/saleor/cart/checkout/views/__init__.py+++ b/saleor/cart/checkout/views/__init__.py@@ -2,9 +2,10 @@ from django.shortcuts import redirectfrom django.template.response import TemplateResponsefrom ....account.forms import LoginForm-from ..core import load_checkout+from ....cart.models import Cart+from ....cart.utils import get_or_empty_db_cartfrom ..forms import CartShippingMethodForm-from ..utils import get_checkout_data+from ..utils import get_checkout_data, get_taxes_for_cartfrom .discount import add_voucher_form, validate_voucherfrom .shipping import (anonymous_user_shipping_address_view, user_shipping_address_view)@@ -16,9 +17,9 @@ from .validators import (validate_shipping_method)-@load_checkout+@get_or_empty_db_cart(Cart.objects.for_display())@validate_cart-def login(request, cart, checkout):+def login(request, cart):"""Allow the user to log in prior to checkout."""if request.user.is_authenticated:return redirect('cart:checkout-index')@@ -26,35 +27,35 @@ def login(request, cart, checkout):return TemplateResponse(request, 'checkout/login.html', {'form': form})-@load_checkout+@get_or_empty_db_cart(Cart.objects.for_display())@validate_cart@validate_is_shipping_required-def index_view(request, cart, checkout):+def index_view(request, cart):"""Redirect to the initial step of checkout."""return redirect('cart:checkout-shipping-address')-@load_checkout+@get_or_empty_db_cart(Cart.objects.for_display())@validate_voucher@validate_cart@validate_is_shipping_required@add_voucher_form-def shipping_address_view(request, cart, checkout):+def shipping_address_view(request, cart):"""Display the correct shipping address step."""if request.user.is_authenticated:- return user_shipping_address_view(request, cart, checkout)- return anonymous_user_shipping_address_view(request, cart, checkout)+ return user_shipping_address_view(request, cart)+ return anonymous_user_shipping_address_view(request, cart)-@load_checkout+@get_or_empty_db_cart(Cart.objects.for_display())@validate_voucher@validate_cart@validate_is_shipping_required@validate_shipping_address@add_voucher_form-def shipping_method_view(request, cart, checkout):+def shipping_method_view(request, cart):"""Display the shipping method selection step."""- taxes = checkout.get_taxes()+ taxes = get_taxes_for_cart(cart, request.taxes)form = CartShippingMethodForm(request.POST or None, taxes=taxes, instance=cart,initial={'shipping_method': cart.shipping_method})@@ -65,21 +66,20 @@ def shipping_method_view(request, cart, checkout):ctx = get_checkout_data(cart, request.discounts, taxes)ctx.update({- 'checkout': checkout,'shipping_method_form': form})return TemplateResponse(request, 'checkout/shipping_method.html', ctx)-@load_checkout+@get_or_empty_db_cart(Cart.objects.for_display())@validate_voucher@validate_cart@add_voucher_form-def summary_view(request, cart, checkout):+def summary_view(request, cart):"""Display the correct order summary."""if cart.is_shipping_required():view = validate_shipping_address(summary_with_shipping_view)view = validate_shipping_method(view)- return view(request, cart, checkout)+ return view(request, cart)if request.user.is_authenticated:- return summary_without_shipping(request, cart, checkout)- return anonymous_summary_without_shipping(request, cart, checkout)+ return summary_without_shipping(request, cart)+ return anonymous_summary_without_shipping(request, cart)diff --git a/saleor/cart/checkout/views/discount.py b/saleor/cart/checkout/views/discount.pyindex acad249c67..723360c62a 100644--- a/saleor/cart/checkout/views/discount.py+++ b/saleor/cart/checkout/views/discount.py@@ -7,20 +7,21 @@ from django.template.response import TemplateResponsefrom django.utils.translation import pgettextfrom django.views.decorators.http import require_POST+from ....cart.models import Cart+from ....cart.utils import get_or_empty_db_cartfrom ....discount.models import Voucher-from ..core import load_checkout-from ..forms import CheckoutDiscountForm+from ..forms import CartVoucherFormfrom ..utils import recalculate_cart_discount, remove_discount_from_cartdef add_voucher_form(view):"""Decorate a view injecting a voucher form and handling its submission."""@wraps(view)- def func(request, cart, checkout):+ def func(request, cart):prefix = 'discount'data = {k: v for k, v in request.POST.items() if k.startswith(prefix)}- voucher_form = CheckoutDiscountForm(- data or None, checkout=checkout, prefix=prefix, instance=cart)+ voucher_form = CartVoucherForm(+ data or None, prefix=prefix, instance=cart)if voucher_form.is_bound:if voucher_form.is_valid():voucher_form.save()@@ -32,12 +33,10 @@ def add_voucher_form(view):# if only discount form was used we clear post for other formsrequest.POST = {}else:- recalculate_cart_discount(cart, checkout)- response = view(request, cart, checkout)+ recalculate_cart_discount(cart)+ response = view(request, cart)if isinstance(response, TemplateResponse):- voucher = voucher_form.initial.get('voucher')response.context_data['voucher_form'] = voucher_form- response.context_data['voucher'] = voucherreturn responsereturn func@@ -49,27 +48,25 @@ def validate_voucher(view):redirected to the checkout summary view."""@wraps(view)- def func(request, cart, checkout):+ def func(request, cart):if cart.voucher_code:try:Voucher.objects.active(date=date.today()).get(code=cart.voucher_code)except Voucher.DoesNotExist:- cart.voucher_code = ''- cart.save()- recalculate_cart_discount(cart, checkout)+ remove_discount_from_cart(cart)msg = pgettext('Checkout warning','This voucher has expired. Please review your checkout.')messages.warning(request, msg)return redirect('cart:checkout-summary')- return view(request, cart, checkout)+ return view(request, cart)return func@require_POST-@load_checkout-def remove_voucher_view(request, cart, checkout):+@get_or_empty_db_cart(Cart.objects.for_display())+def remove_voucher_view(request, cart):"""Clear the discount and remove the voucher."""next_url = request.GET.get('next', request.META['HTTP_REFERER'])remove_discount_from_cart(cart)diff --git a/saleor/cart/checkout/views/shipping.py b/saleor/cart/checkout/views/shipping.pyindex 2adc12b5ca..f6ab2fc41f 100644--- a/saleor/cart/checkout/views/shipping.py+++ b/saleor/cart/checkout/views/shipping.py@@ -4,10 +4,11 @@ from django.template.response import TemplateResponsefrom ....account.forms import get_address_formfrom ....account.models import Addressfrom ..forms import AddressChoiceForm, AnonymousUserShippingForm-from ..utils import get_checkout_data, save_shipping_address_in_cart+from ..utils import (+ get_checkout_data, get_taxes_for_cart, save_shipping_address_in_cart)-def anonymous_user_shipping_address_view(request, cart, checkout):+def anonymous_user_shipping_address_view(request, cart):"""Display the shipping step for a user who is not logged in."""address_form, preview = get_address_form(request.POST or None, country_code=request.country.code,@@ -24,30 +25,22 @@ def anonymous_user_shipping_address_view(request, cart, checkout):save_shipping_address_in_cart(cart, address)return redirect('cart:checkout-shipping-method')- ctx = get_checkout_data(cart, request.discounts, checkout.get_taxes())+ taxes = get_taxes_for_cart(cart, request.taxes)+ ctx = get_checkout_data(cart, request.discounts, taxes)ctx.update({'address_form': address_form,- 'checkout': checkout,'user_form': user_form})return TemplateResponse(request, 'checkout/shipping_address.html', ctx)-def user_shipping_address_view(request, cart, checkout):- """Display the shipping step for a logged in user.-- In addition to entering a new address the user has an option of selecting- one of the existing entries from their address book.- """- data = request.POST or None- user_addresses = request.user.addresses.all()+def get_shipping_address_forms(cart, user_addresses, data, country):+ """Forms initialized with data depending on current address in cart."""shipping_address = cart.shipping_address- cart.user_email = request.user.email- cart.save()if shipping_address and shipping_address in user_addresses:address_form, preview = get_address_form(- data, country_code=request.country.code,- initial={'country': request.country})+ data, country_code=country.code,+ initial={'country': country})addresses_form = AddressChoiceForm(data, addresses=user_addresses,initial={'address': shipping_address.id})@@ -59,11 +52,21 @@ def user_shipping_address_view(request, cart, checkout):data, addresses=user_addresses)else:address_form, preview = get_address_form(- data, country_code=request.country.code,- initial={'country': request.country})+ data, country_code=country.code,+ initial={'country': country})addresses_form = AddressChoiceForm(data, addresses=user_addresses)+ return address_form, addresses_form, preview+++def update_shipping_address_in_cart(cart, user_addresses, data, country):+ """Return shipping address choice forms and if and address was updated."""+ address_form, addresses_form, preview = (+ get_shipping_address_forms(cart, user_addresses, data, country))++ updated = False+if addresses_form.is_valid() and not preview:use_existing_address = (addresses_form.cleaned_data['address'] !=@@ -73,17 +76,36 @@ def user_shipping_address_view(request, cart, checkout):address_id = addresses_form.cleaned_data['address']address = Address.objects.get(id=address_id)save_shipping_address_in_cart(cart, address)- return redirect('cart:checkout-shipping-method')+ updated = Trueelif address_form.is_valid():address = address_form.save()save_shipping_address_in_cart(cart, address)- return redirect('cart:checkout-shipping-method')+ updated = True++ return addresses_form, address_form, updated+++def user_shipping_address_view(request, cart):+ """Display the shipping step for a logged in user.++ In addition to entering a new address the user has an option of selecting+ one of the existing entries from their address book.+ """+ cart.user_email = request.user.email+ cart.save()+ user_addresses = cart.user.addresses.all()++ addresses_form, address_form, updated = update_shipping_address_in_cart(+ cart, user_addresses, request.POST or None, request.country)++ if updated:+ return redirect('cart:checkout-shipping-method')- ctx = get_checkout_data(cart, request.discounts, checkout.get_taxes())+ taxes = get_taxes_for_cart(cart, request.taxes)+ ctx = get_checkout_data(cart, request.discounts, taxes)ctx.update({'additional_addresses': user_addresses,'address_form': address_form,- 'checkout': checkout,'user_form': addresses_form})return TemplateResponse(request, 'checkout/shipping_address.html', ctx)diff --git a/saleor/cart/checkout/views/summary.py b/saleor/cart/checkout/views/summary.pyindex 8cc77f8885..4a17247bd6 100644--- a/saleor/cart/checkout/views/summary.py+++ b/saleor/cart/checkout/views/summary.py@@ -5,40 +5,43 @@ from django.utils.translation import pgettext, pgettext_lazyfrom ....account.forms import get_address_formfrom ....account.models import Address+from ....core import analyticsfrom ....core.exceptions import InsufficientStockfrom ....order.emails import send_order_confirmationfrom ..forms import (AddressChoiceForm, AnonymousUserBillingForm, BillingAddressChoiceForm,CartNoteForm)-from ..utils import get_checkout_data, save_billing_address_in_cart+from ..utils import (+ get_checkout_data, get_taxes_for_cart, save_billing_address_in_cart)+from .. import utils-def create_order(checkout):- """Finalize a checkout session and create an order.+def create_order(cart, tracking_code, discounts, taxes):+ """Finalize a checkout process and create an order.This is a helper function.-- `checkout` is a `saleor.cart.checkout.core.Checkout` instance."""- order = checkout.create_order()+ order = utils.create_order(cart, tracking_code, discounts, taxes)if not order:return None, redirect('cart:checkout-summary')- checkout.clear_storage()- checkout.cart.clear()- user = None if checkout.user.is_anonymous else checkout.user+ user = cart.user+ cart.clear()msg = pgettext_lazy('Order status history entry', 'Order was placed')order.history.create(user=user, content=msg)send_order_confirmation.delay(order.pk)return order, redirect('order:payment', token=order.token)-def handle_order_placement(request, checkout):+def handle_order_placement(request, cart):"""Try to create an order and redirect the user as necessary.This is a helper function."""+ tracking_code = analytics.get_client_id(request)+ taxes = get_taxes_for_cart(cart, request.taxes)try:- order, redirect_url = create_order(checkout)+ order, redirect_url = create_order(+ cart, tracking_code, request.discounts, taxes)except InsufficientStock:return redirect('cart:index')if not order:@@ -88,7 +91,7 @@ def get_billing_forms_with_shipping(return address_form, addresses_form, None-def summary_with_shipping_view(request, cart, checkout):+def summary_with_shipping_view(request, cart):"""Display order summary with billing forms for a logged in user.Will create an order if all data is valid.@@ -109,19 +112,19 @@ def summary_with_shipping_view(request, cart, checkout):if address is not None:save_billing_address_in_cart(cart, address)- return handle_order_placement(request, checkout)+ return handle_order_placement(request, cart)- ctx = get_checkout_data(cart, request.discounts, checkout.get_taxes())+ taxes = get_taxes_for_cart(cart, request.taxes)+ ctx = get_checkout_data(cart, request.discounts, taxes)ctx.update({'additional_addresses': additional_addresses,'address_form': address_form,'addresses_form': addresses_form,- 'checkout': checkout,'note_form': note_form})return TemplateResponse(request, 'checkout/summary.html', ctx)-def anonymous_summary_without_shipping(request, cart, checkout):+def anonymous_summary_without_shipping(request, cart):"""Display order summary with billing forms for an unauthorized user.Will create an order if all data is valid.@@ -145,19 +148,19 @@ def anonymous_summary_without_shipping(request, cart, checkout):user_form.save()address = address_form.save()save_billing_address_in_cart(cart, address)- return handle_order_placement(request, checkout)+ return handle_order_placement(request, cart)- ctx = get_checkout_data(cart, request.discounts, checkout.get_taxes())+ taxes = get_taxes_for_cart(cart, request.taxes)+ ctx = get_checkout_data(cart, request.discounts, taxes)ctx.update({'address_form': address_form,- 'checkout': checkout,'note_form': note_form,'user_form': user_form})return TemplateResponse(request, 'checkout/summary_without_shipping.html', ctx)-def summary_without_shipping(request, cart, checkout):+def summary_without_shipping(request, cart):"""Display order summary for cases where shipping is not required.Will create an order if all data is valid.@@ -212,19 +215,19 @@ def summary_without_shipping(request, cart, checkout):address_id = addresses_form.cleaned_data['address']address = Address.objects.get(id=address_id)save_billing_address_in_cart(cart, address)- return handle_order_placement(request, checkout)+ return handle_order_placement(request, cart)elif address_form.is_valid():address = address_form.save()save_billing_address_in_cart(cart, address)- return handle_order_placement(request, checkout)+ return handle_order_placement(request, cart)- ctx = get_checkout_data(cart, request.discounts, checkout.get_taxes())+ taxes = get_taxes_for_cart(cart, request.taxes)+ ctx = get_checkout_data(cart, request.discounts, taxes)ctx.update({'additional_addresses': user_addresses,'address_form': address_form,'addresses_form': addresses_form,- 'checkout': checkout,'note_form': note_form})return TemplateResponse(request, 'checkout/summary_without_shipping.html', ctx)diff --git a/saleor/cart/checkout/views/validators.py b/saleor/cart/checkout/views/validators.pyindex b59ed8701b..1c21c3875e 100644--- a/saleor/cart/checkout/views/validators.py+++ b/saleor/cart/checkout/views/validators.py@@ -7,17 +7,12 @@ from django.shortcuts import redirectdef validate_cart(view):"""Decorate a view making it require a non-empty cart.- Expects to be decorated with `@load_checkout`.-- Changes view signature from `func(request, cart, checkout)` to- `func(request, checkout)`.-If the cart is empty redirects to the cart details."""@wraps(view)- def func(request, cart, checkout):+ def func(request, cart):if cart:- return view(request, cart, checkout)+ return view(request, cart)return redirect('cart:index')return func@@ -31,14 +26,14 @@ def validate_shipping_address(view):shipping address step."""@wraps(view)- def func(request, cart, checkout):+ def func(request, cart):if cart.user_email is None or cart.shipping_address is None:return redirect('cart:checkout-shipping-address')try:cart.shipping_address.full_clean()except ValidationError:return redirect('cart:checkout-shipping-address')- return view(request, cart, checkout)+ return view(request, cart)return func@@ -50,10 +45,10 @@ def validate_shipping_method(view):If the method is missing redirects to the shipping method step."""@wraps(view)- def func(request, cart, checkout):+ def func(request, cart):if cart.shipping_method is None:return redirect('cart:checkout-shipping-method')- return view(request, cart, checkout)+ return view(request, cart)return func@@ -65,8 +60,8 @@ def validate_is_shipping_required(view):If shipping is not needed redirects to the checkout summary."""@wraps(view)- def func(request, cart, checkout):+ def func(request, cart):if not cart.is_shipping_required():return redirect('cart:checkout-summary')- return view(request, cart, checkout)+ return view(request, cart)return funcdiff --git a/saleor/cart/migrations/0007_merge_checkout_into_cart.py b/saleor/cart/migrations/0007_merge_checkout_into_cart.pyindex fe33056d36..bb47eedf9a 100644--- a/saleor/cart/migrations/0007_merge_checkout_into_cart.py+++ b/saleor/cart/migrations/0007_merge_checkout_into_cart.py@@ -1,4 +1,4 @@-# Generated by Django 2.0.3 on 2018-05-22 16:00+# Generated by Django 2.0.3 on 2018-05-23 12:30from django.db import migrations, modelsimport django.db.models.deletion@@ -55,11 +55,11 @@ class Migration(migrations.Migration):migrations.AddField(model_name='cart',name='discount_name',- field=models.CharField(blank=True, default='', max_length=255),+ field=models.CharField(blank=True, max_length=255, null=True),),migrations.AddField(model_name='cart',name='voucher_code',- field=models.CharField(blank=True, default='', max_length=12),+ field=models.CharField(blank=True, max_length=12, null=True),),]diff --git a/saleor/cart/models.py b/saleor/cart/models.pyindex 03ec81150a..1fa5eae7f5 100644--- a/saleor/cart/models.py+++ b/saleor/cart/models.py@@ -1,5 +1,4 @@"""Cart-related ORM models."""-from collections import namedtuplefrom decimal import Decimalfrom uuid import uuid4@@ -10,7 +9,6 @@ from django.utils.encoding import smart_strfrom django.utils.timezone import nowfrom django_prices.models import MoneyFieldfrom jsonfield import JSONField-from prices import sum as sum_pricesfrom . import CartStatus, loggerfrom ..account.models import Address@@ -18,7 +16,6 @@ from ..core.utils.taxes import ZERO_TAXED_MONEYfrom ..shipping.models import ShippingMethodCountryCENTS = Decimal('0.01')-SimpleCart = namedtuple('SimpleCart', ('quantity', 'total', 'token'))def find_open_cart_for_user(user):@@ -90,8 +87,8 @@ class Cart(models.Model):discount_amount = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)- discount_name = models.CharField(max_length=255, default='', blank=True)- voucher_code = models.CharField(max_length=12, blank=True, default='')+ discount_name = models.CharField(max_length=255, blank=True, null=True)+ voucher_code = models.CharField(max_length=12, blank=True, null=True)objects = CartQueryset.as_manager()@@ -144,13 +141,18 @@ class Cart(models.Model):if self.shipping_method and self.is_shipping_required()else ZERO_TAXED_MONEY)- def get_total(self, discounts=None, taxes=None):+ def get_subtotal(self, discounts=None, taxes=None):"""Return the total cost of the cart prior to shipping."""- subtotals = [- line.get_total(discounts, taxes) for line in self.lines.all()]- if not subtotals:- raise AttributeError('Calling get_total() on an empty cart')- return sum_prices(subtotals)+ subtotals = (+ line.get_total(discounts, taxes) for line in self.lines.all())+ return sum(subtotals, ZERO_TAXED_MONEY)++ def get_total(self, discounts=None, taxes=None):+ """Return the total cost of the cart."""+ total = self.get_subtotal(discounts, taxes)+ total += self.get_shipping_price(taxes)+ total -= self.discount_amount+ return totaldef count(self):"""Return the total quantity in cart."""diff --git a/saleor/cart/utils.py b/saleor/cart/utils.pyindex fb63245a36..de5941a5fb 100644--- a/saleor/cart/utils.py+++ b/saleor/cart/utils.py@@ -218,7 +218,7 @@ def get_cart_data(cart, shipping_range, currency, discounts, taxes):total_with_shipping = Nonelocal_total_with_shipping = Noneif cart:- cart_total = cart.get_total(discounts, taxes)+ cart_total = cart.get_subtotal(discounts, taxes)local_cart_total = to_local_currency(cart_total, currency)shipping_required = cart.is_shipping_required()total_with_shipping = TaxedMoneyRange(diff --git a/saleor/cart/views.py b/saleor/cart/views.pyindex f14ae88084..4d5520891e 100644--- a/saleor/cart/views.py+++ b/saleor/cart/views.py@@ -103,7 +103,7 @@ def update(request, cart, variant_id):response['subtotal'] = format_money(updated_line.get_total(discounts, taxes).gross)if cart:- cart_total = cart.get_total(discounts, taxes)+ cart_total = cart.get_subtotal(discounts, taxes)response['total'] = format_money(cart_total.gross)local_cart_total = to_local_currency(cart_total, request.currency)if local_cart_total is not None:@@ -136,7 +136,7 @@ def summary(request, cart):else:data = {'quantity': cart.quantity,- 'total': cart.get_total(discounts, taxes),+ 'total': cart.get_subtotal(discounts, taxes),'lines': [prepare_line_data(line) for line in cart.lines.all()]}return render(request, 'cart_dropdown.html', data)diff --git a/templates/checkout/details.html b/templates/checkout/details.htmlindex 86e2b89f3f..283357fb1c 100644--- a/templates/checkout/details.html+++ b/templates/checkout/details.html@@ -70,36 +70,34 @@</p></div></div>- {% with total=checkout.get_total %}- {% if cart_are_taxes_handled %}- <div class="row checkout__review__section">- <div class="col-8">- {% if site.settings.display_gross_prices %}- <p>{% trans "Taxes (included)" context "Order review section title" %}</p>- {% else %}- <p>{% trans "Taxes" context "Order review section title" %}</p>- {% endif %}- </div>- <div class="col-4">- <p class="float-right">{% price total.tax %}</p>- </div>- </div>- {% endif %}- <div class="row checkout__review__section">- <div class="col-12">- <h3>{% trans "Promo code" context "Order review section title" %}</h3>- {% include "checkout/snippets/voucher_form.html" with checkout=checkout form=voucher_form %}- </div>- </div>+ {% if cart_are_taxes_handled %}<div class="row checkout__review__section"><div class="col-8">- <h3>{% trans "Total" context "Order review section title" %}</h3>+ {% if site.settings.display_gross_prices %}+ <p>{% trans "Taxes (included)" context "Order review section title" %}</p>+ {% else %}+ <p>{% trans "Taxes" context "Order review section title" %}</p>+ {% endif %}</div><div class="col-4">- <h3 class="float-right">{% price total.gross %}</h3>+ <p class="float-right">{% price cart_total.tax %}</p></div></div>- {% endwith %}+ {% endif %}+ <div class="row checkout__review__section">+ <div class="col-12">+ <h3>{% trans "Promo code" context "Order review section title" %}</h3>+ {% include "checkout/snippets/voucher_form.html" with checkout=checkout form=voucher_form %}+ </div>+ </div>+ <div class="row checkout__review__section">+ <div class="col-8">+ <h3>{% trans "Total" context "Order review section title" %}</h3>+ </div>+ <div class="col-4">+ <h3 class="float-right">{% price cart_total.gross %}</h3>+ </div>+ </div></div></div></div>diff --git a/tests/conftest.py b/tests/conftest.pyindex 60a126dd7e..509f394057 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -3,7 +3,7 @@ from io import BytesIOfrom unittest.mock import MagicMock, Mockimport pytest-from django.contrib.auth.models import AnonymousUser, Group, Permission+from django.contrib.auth.models import Group, Permissionfrom django.contrib.sites.models import Sitefrom django.core.files import Filefrom django.core.files.uploadedfile import SimpleUploadedFile@@ -18,7 +18,6 @@ from prices import Moneyfrom saleor.account.models import Address, Userfrom saleor.cart import utilsfrom saleor.cart.models import Cart-from saleor.cart.checkout.core import Checkoutfrom saleor.dashboard.order.utils import fulfill_order_linefrom saleor.discount.models import Sale, Voucherfrom saleor.menu.models import Menu, MenuItem@@ -349,17 +348,6 @@ def product_with_images(product_type, default_category):return product-def checkout():- return Checkout(Mock(), AnonymousUser(), None, None, 'tracking_code')---def checkout_with_items(request_cart_with_item, customer_user):- return Checkout(- request_cart_with_item, customer_user, None, None, 'tracking_code')--@pytest.fixturedef voucher(db): # pylint: disable=W0613return Voucher.objects.create(code='mirumee', discount_value=20)diff --git a/tests/test_cart.py b/tests/test_cart.pyindex 3e71b56ade..05709e54c5 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -15,6 +15,7 @@ from saleor.cart.context_processors import cart_counterfrom saleor.cart.models import Cart, find_open_cart_for_userfrom saleor.cart.views import updatefrom saleor.core.exceptions import InsufficientStock+from saleor.core.utils.taxes import ZERO_TAXED_MONEYfrom saleor.discount.models import Salefrom saleor.shipping.utils import get_shipment_options@@ -296,7 +297,7 @@ def test_adding_same_variant(cart, product, taxes):assert len(cart) == 1assert cart.count() == {'total_quantity': 3}cart_total = TaxedMoney(net=Money('24.39', 'USD'), gross=Money(30, 'USD'))- assert cart.get_total(taxes=taxes) == cart_total+ assert cart.get_subtotal(taxes=taxes) == cart_totaldef test_replacing_same_variant(cart, product):@@ -585,7 +586,7 @@ def test_cart_summary_page(settings, client, product, request_cart, vatlayer):assert response.status_code == 200content = response.contextassert content['quantity'] == request_cart.quantity- cart_total = request_cart.get_total(taxes=vatlayer)+ cart_total = request_cart.get_subtotal(taxes=vatlayer)assert content['total'] == cart_totalassert len(content['lines']) == 1cart_line = content['lines'][0]@@ -636,9 +637,7 @@ def test_cart_repr():def test_cart_get_total_empty(db):cart = Cart.objects.create()-- with pytest.raises(AttributeError):- cart.get_total()+ assert cart.get_subtotal() == ZERO_TAXED_MONEYdef test_cart_change_user(customer_user):diff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex b99fb07a84..86e3dfa42b 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -2,47 +2,19 @@ from datetime import date, timedeltafrom unittest.mock import Mockimport pytest-from django.contrib.auth.models import AnonymousUserfrom django.urls import reversefrom freezegun import freeze_timefrom prices import Money, TaxedMoneyfrom saleor.cart.checkout import views-from saleor.cart.checkout.core import STORAGE_SESSION_KEY, Checkout-from saleor.cart.checkout.forms import CheckoutDiscountForm-from saleor.cart.checkout.utils import get_voucher_discount_for_checkout+from saleor.cart.checkout.forms import CartVoucherForm+from saleor.cart.checkout.utils import (+ create_order, get_voucher_discount_for_cart)from saleor.core.exceptions import InsufficientStockfrom saleor.discount import DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Voucher-def test_checkout_version(checkout):- storage = checkout.for_storage()- assert storage['version'] == Checkout.VERSION--[email protected]('storage_data, expected_storage', [- (- {'version': Checkout.VERSION, 'new': 1},- {'version': Checkout.VERSION, 'new': 1}),- ({'version': 'wrong', 'new': 1}, {'version': Checkout.VERSION}),- ({'new': 1}, {'version': Checkout.VERSION}),- ({}, {'version': Checkout.VERSION}),- (None, {'version': Checkout.VERSION})])-def test_checkout_version_with_from_storage(storage_data, expected_storage):- checkout = Checkout.from_storage(- storage_data, Mock(), AnonymousUser(), None, None, 'tracking_code')- storage = checkout.for_storage()- assert storage == expected_storage---def test_checkout_clear_storage(checkout):- checkout.storage['new'] = 1- checkout.clear_storage()- assert checkout.storage is None- assert checkout.modified is True--@pytest.mark.parametrize('cart, status_code, url', [(Mock(__len__=Mock(return_value=0)), 302, reverse('cart:index')),(@@ -60,11 +32,9 @@ def test_checkout_clear_storage(checkout):__len__=Mock(return_value=0),is_shipping_required=Mock(return_value=False)),302, reverse('cart:index'))])-def test_index_view(checkout, cart, status_code, url, rf, monkeypatch):- checkout.cart = cart+def test_index_view(cart, status_code, url, rf, monkeypatch):request = rf.get('cart:checkout-index', follow=True)- request.user = checkout.user- request.session = {STORAGE_SESSION_KEY: checkout.for_storage()}+ request.user = cart.userrequest.discounts = []request.taxes = Nonemonkeypatch.setattr(@@ -74,47 +44,48 @@ def test_index_view(checkout, cart, status_code, url, rf, monkeypatch):assert response.url == url-def test_checkout_discount(checkout_with_items, sale, vatlayer):- checkout_with_items.discounts = (sale,)- checkout_with_items.taxes = vatlayer- assert checkout_with_items.get_total() == TaxedMoney(+def test_checkout_discount(request_cart_with_item, sale, vatlayer):+ total = (+ request_cart_with_item.get_total(discounts=(sale,), taxes=vatlayer))+ assert total == TaxedMoney(net=Money('4.07', 'USD'), gross=Money('5.00', 'USD'))def test_checkout_create_order_insufficient_stock(- checkout, request_cart, customer_user, product):+ request_cart, customer_user, product):product_type = product.product_typeproduct_type.is_shipping_required = Falseproduct_type.save()variant = product.variants.get()request_cart.add(variant, quantity=10, check_quantity=False)- checkout.cart = request_cart- checkout.user = customer_user+ request_cart.user = customer_user+ request_cart.billing_address = customer_user.default_billing_address+ request_cart.save()with pytest.raises(InsufficientStock):- checkout.create_order()+ create_order(+ request_cart, 'tracking_code', discounts=None, taxes=None)-def test_checkout_taxes(checkout_with_items, shipping_method, vatlayer):- checkout_with_items.taxes = vatlayer- cart = checkout_with_items.cart+def test_checkout_taxes(request_cart_with_item, shipping_method, vatlayer):+ cart = request_cart_with_itemcart.shipping_method = shipping_method.price_per_country.get()cart.save()- assert checkout_with_items.cart.get_shipping_price(vatlayer) == (- TaxedMoney(net=Money('8.13', 'USD'), gross=Money(10, 'USD')))- subtotal = checkout_with_items.cart.get_total(taxes=vatlayer)- assert checkout_with_items.get_subtotal() == subtotal+ taxed_price = TaxedMoney(net=Money('8.13', 'USD'), gross=Money(10, 'USD'))+ assert cart.get_shipping_price(taxes=vatlayer) == taxed_price+ assert cart.get_subtotal(taxes=vatlayer) == taxed_price-def test_note_in_created_order(checkout_with_items):- cart = checkout_with_items.cart- cart.note = ''- cart.save()- order = checkout_with_items.create_order()+def test_note_in_created_order(request_cart_with_item):+ request_cart_with_item.note = ''+ request_cart_with_item.save()+ order = create_order(+ request_cart_with_item, 'tracking_code', discounts=None, taxes=None)assert not order.notes.all()- cart.note = 'test_note'- cart.save()- order = checkout_with_items.create_order()+ request_cart_with_item.note = 'test_note'+ request_cart_with_item.save()+ order = create_order(+ request_cart_with_item, 'tracking_code', discounts=None, taxes=None)assert order.notes.filter(content='test_note').exists()@@ -130,8 +101,8 @@ def test_value_voucher_checkout_discount(discount_value=discount_value,limit=Money(limit, 'USD') if limit is not None else None)subtotal = TaxedMoney(net=Money(total, 'USD'), gross=Money(total, 'USD'))- checkout = Mock(get_subtotal=Mock(return_value=subtotal))- discount = get_voucher_discount_for_checkout(voucher, checkout)+ cart = Mock(get_subtotal=Mock(return_value=subtotal))+ discount = get_voucher_discount_for_cart(voucher, cart)assert discount == Money(expected_value, 'USD')@@ -142,9 +113,9 @@ def test_value_voucher_checkout_discount_not_applicable(settings):discount_value=10,limit=Money(100, 'USD'))subtotal = TaxedMoney(net=Money(10, 'USD'), gross=Money(10, 'USD'))- checkout = Mock(get_subtotal=Mock(return_value=subtotal))+ cart = Mock(get_subtotal=Mock(return_value=subtotal))with pytest.raises(NotApplicable) as e:- get_voucher_discount_for_checkout(voucher, checkout)+ get_voucher_discount_for_cart(voucher, cart)assert e.value.limit == Money(100, 'USD')@@ -160,21 +131,20 @@ def test_shipping_voucher_checkout_discount(subtotal = TaxedMoney(net=Money(100, 'USD'), gross=Money(100, 'USD'))shipping_total = TaxedMoney(net=Money(shipping_cost, 'USD'), gross=Money(shipping_cost, 'USD'))- checkout = Mock(+ cart = Mock(get_subtotal=Mock(return_value=subtotal),- cart=Mock(- is_shipping_required=Mock(return_value=True),- shipping_method=Mock(- price=Money(shipping_cost, 'USD'),- country_code=shipping_country_code,- get_total_price=Mock(return_value=shipping_total))))+ is_shipping_required=Mock(return_value=True),+ shipping_method=Mock(+ price=Money(shipping_cost, 'USD'),+ country_code=shipping_country_code,+ get_total_price=Mock(return_value=shipping_total)))voucher = Voucher(code='unique', type=VoucherType.SHIPPING,discount_value_type=discount_type,discount_value=discount_value,apply_to=apply_to,limit=None)- discount = get_voucher_discount_for_checkout(voucher, checkout)+ discount = get_voucher_discount_for_cart(voucher, cart)assert discount == Money(expected_value, 'USD')@@ -197,11 +167,10 @@ def test_shipping_voucher_checkout_discount_not_applicable(settings, is_shipping_required, shipping_method, discount_value,discount_type, apply_to, limit, subtotal, error_msg):subtotal_price = TaxedMoney(net=subtotal, gross=subtotal)- checkout = Mock(- cart=Mock(- is_shipping_required=Mock(return_value=is_shipping_required),- shipping_method=shipping_method),- get_subtotal=Mock(return_value=subtotal_price))+ cart = Mock(+ get_subtotal=Mock(return_value=subtotal_price),+ is_shipping_required=Mock(return_value=is_shipping_required),+ shipping_method=shipping_method)voucher = Voucher(code='unique', type=VoucherType.SHIPPING,discount_value_type=discount_type,@@ -209,7 +178,7 @@ def test_shipping_voucher_checkout_discount_not_applicable(limit=Money(limit, 'USD') if limit is not None else None,apply_to=apply_to)with pytest.raises(NotApplicable) as e:- get_voucher_discount_for_checkout(voucher, checkout)+ get_voucher_discount_for_cart(voucher, cart)assert str(e.value) == error_msg@@ -222,10 +191,10 @@ def test_product_voucher_checkout_discount_not_applicable(code='unique', type=VoucherType.PRODUCT,discount_value_type=DiscountValueType.FIXED,discount_value=10)- checkout = Mock(cart=Mock())+ cart=Mock()with pytest.raises(NotApplicable) as e:- get_voucher_discount_for_checkout(voucher, checkout)+ get_voucher_discount_for_cart(voucher, cart)assert str(e.value) == 'This offer is only valid for selected items.'@@ -238,69 +207,71 @@ def test_category_voucher_checkout_discount_not_applicable(code='unique', type=VoucherType.CATEGORY,discount_value_type=DiscountValueType.FIXED,discount_value=10)- checkout = Mock(cart=Mock())+ cart = Mock()with pytest.raises(NotApplicable) as e:- get_voucher_discount_for_checkout(voucher, checkout)+ get_voucher_discount_for_cart(voucher, cart)assert str(e.value) == 'This offer is only valid for selected items.'---def test_checkout_discount_form_invalid_voucher_code(monkeypatch):- checkout = Mock(cart=Mock())- form = CheckoutDiscountForm({'voucher': 'invalid'}, checkout=checkout)+def test_checkout_discount_form_invalid_voucher_code(+ monkeypatch, request_cart_with_item):+ form = CartVoucherForm(+ {'voucher': 'invalid'}, instance=request_cart_with_item)assert not form.is_valid()assert 'voucher' in form.errors-def test_checkout_discount_form_not_applicable_voucher(monkeypatch, voucher):- checkout = Mock(cart=Mock())- form = CheckoutDiscountForm({'voucher': voucher.code}, checkout=checkout)+def test_checkout_discount_form_not_applicable_voucher(+ monkeypatch, voucher, request_cart_with_item):+ form = CartVoucherForm(+ {'voucher': voucher.code}, instance=request_cart_with_item)monkeypatch.setattr(- 'saleor.discount.forms.get_voucher_discount_for_checkout',+ 'saleor.cart.checkout.forms.get_voucher_discount_for_cart',Mock(side_effect=NotApplicable('Not applicable')))assert not form.is_valid()assert 'voucher' in form.errors-def test_checkout_discount_form_active_queryset_voucher_not_active(voucher):+def test_checkout_discount_form_active_queryset_voucher_not_active(+ voucher, request_cart_with_item):assert Voucher.objects.count() == 1- checkout = Mock(cart=Mock())voucher.start_date = date.today() + timedelta(days=1)voucher.save()- form = CheckoutDiscountForm({'voucher': voucher.code}, checkout=checkout)+ form = CartVoucherForm(+ {'voucher': voucher.code}, instance=request_cart_with_item)qs = form.fields['voucher'].querysetassert qs.count() == 0-def test_checkout_discount_form_active_queryset_voucher_active(voucher):+def test_checkout_discount_form_active_queryset_voucher_active(+ voucher, request_cart_with_item):assert Voucher.objects.count() == 1- checkout = Mock(cart=Mock())voucher.start_date = date.today()voucher.save()- form = CheckoutDiscountForm({'voucher': voucher.code}, checkout=checkout)+ form = CartVoucherForm(+ {'voucher': voucher.code}, instance=request_cart_with_item)qs = form.fields['voucher'].querysetassert qs.count() == 1-def test_checkout_discount_form_active_queryset_after_some_time(voucher):+def test_checkout_discount_form_active_queryset_after_some_time(+ voucher, request_cart_with_item):assert Voucher.objects.count() == 1- checkout = Mock(cart=Mock())voucher.start_date = date(year=2016, month=6, day=1)voucher.end_date = date(year=2016, month=6, day=2)voucher.save()with freeze_time('2016-05-31'):- form = CheckoutDiscountForm(- {'voucher': voucher.code}, checkout=checkout)+ form = CartVoucherForm(+ {'voucher': voucher.code}, instance=request_cart_with_item)assert form.fields['voucher'].queryset.count() == 0with freeze_time('2016-06-01'):- form = CheckoutDiscountForm(- {'voucher': voucher.code}, checkout=checkout)+ form = CartVoucherForm(+ {'voucher': voucher.code}, instance=request_cart_with_item)assert form.fields['voucher'].queryset.count() == 1with freeze_time('2016-06-03'):- form = CheckoutDiscountForm(- {'voucher': voucher.code}, checkout=checkout)+ form = CartVoucherForm(+ {'voucher': voucher.code}, instance=request_cart_with_item)assert form.fields['voucher'].queryset.count() == 0diff --git a/tests/test_checkout_integration.py b/tests/test_checkout_integration.pyindex 523bd013a4..4dcd0945ce 100644--- a/tests/test_checkout_integration.py+++ b/tests/test_checkout_integration.py@@ -261,13 +261,13 @@ def test_voucher_invalid(voucher_response = client.post('{url}?next={url}'.format(url=url), follow=True, data=discount_data,HTTP_REFERER=url)- assert voucher_response.context['checkout'].voucher_code == voucher.code+ assert voucher_response.context['cart'].voucher_code == voucher.codevoucher.used = 3voucher.save()address_data = {'address': 'shipping_address'}assert url == reverse('cart:checkout-summary')summary_response = client.post(url, data=address_data, follow=True)- assert summary_response.context['checkout'].voucher_code is None+ assert summary_response.context['cart'].voucher_code is Nonesummary_response = client.post(url, data=address_data, follow=True)assert summary_response.context['order'].voucher is None@@ -313,7 +313,7 @@ def test_voucher_code_invalid(HTTP_REFERER=url)assert voucher_response.status_code == 200assert 'voucher' in voucher_response.context['voucher_form'].errors- assert voucher_response.context['checkout'].voucher_code is None+ assert voucher_response.context['cart'].voucher_code is Nonedef test_remove_voucher(@@ -354,12 +354,12 @@ def test_remove_voucher(voucher_response = client.post('{url}?next={url}'.format(url=url), follow=True, data=discount_data,HTTP_REFERER=url)- assert voucher_response.context['checkout'].voucher_code is not None+ assert voucher_response.context['cart'].voucher_code is not None# Remove voucher from checkoutvoucher_response = client.post(reverse('cart:checkout-remove-voucher'), follow=True, HTTP_REFERER=url)assert voucher_response.status_code == 200- assert voucher_response.context['checkout'].voucher_code is None+ assert voucher_response.context['cart'].voucher_code is Nonedef test_language_is_saved_in_order(diff --git a/tests/test_discounts.py b/tests/test_discounts.pyindex d15323cba4..9c91cf83b7 100644--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@ -4,7 +4,7 @@ from unittest.mock import Mockimport pytestfrom prices import Money, TaxedMoney-from saleor.cart.checkout.utils import get_voucher_discount_for_checkout+from saleor.cart.checkout.utils import get_voucher_discount_for_cartfrom saleor.discount import (DiscountValueType, VoucherApplyToProduct, VoucherType)from saleor.discount.models import NotApplicable, Sale, Voucher@@ -108,7 +108,7 @@ def test_products_voucher_checkout_discount_not(discount_value=discount_value,apply_to=apply_to)checkout = Mock(cart=Mock())- discount = get_voucher_discount_for_checkout(voucher, checkout)+ discount = get_voucher_discount_for_cart(voucher, checkout)assert discount == Money(expected_value, 'USD')