Skip to content

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

Merge cart and checkout folders into checkout app

Anna Siwik2e8b46c36337
diff --git a/saleor/cart/checkout/__init__.py b/saleor/cart/checkout/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/cart/checkout/forms.py b/saleor/cart/checkout/forms.py
deleted file mode 100644
index 020c6eaa75..0000000000
--- a/saleor/cart/checkout/forms.py
+++ /dev/null
@@ -1,186 +0,0 @@
-from datetime import date
-
-from django import forms
-from django.utils.encoding import smart_text
-from django.utils.safestring import mark_safe
-from django.utils.translation import pgettext_lazy
-
-from ...cart.models import Cart
-from ...core.utils import format_money
-from ...core.utils.taxes import display_gross_prices
-from ...discount.models import NotApplicable, Voucher
-from ...shipping.models import ShippingMethodCountry
-from ...shipping.utils import get_taxed_shipping_price
-
-
-class AnonymousUserShippingForm(forms.ModelForm):
- """Additional shipping information form for users who are not logged in."""
-
- user_email = forms.EmailField(
- widget=forms.EmailInput(attrs={'autocomplete': 'shipping email'}),
- label=pgettext_lazy('Address form field label', 'Email'))
-
- class Meta:
- model = Cart
- fields = ['user_email']
-
-
-class AnonymousUserBillingForm(forms.ModelForm):
- """Additional billing information form for users who are not logged in."""
-
- user_email = forms.EmailField(
- widget=forms.EmailInput(attrs={'autocomplete': 'billing email'}),
- label=pgettext_lazy('Address form field label', 'Email'))
-
- class Meta:
- model = Cart
- fields = ['user_email']
-
-
-class AddressChoiceForm(forms.Form):
- """Choose one of user's addresses or to create new one."""
-
- NEW_ADDRESS = 'new_address'
- CHOICES = [
- (NEW_ADDRESS, pgettext_lazy(
- 'Shipping addresses form choice', 'Enter a new address'))]
-
- address = forms.ChoiceField(
- label=pgettext_lazy('Shipping addresses form field label', 'Address'),
- choices=CHOICES, initial=NEW_ADDRESS, widget=forms.RadioSelect)
-
- def __init__(self, *args, **kwargs):
- addresses = kwargs.pop('addresses')
- super().__init__(*args, **kwargs)
- address_choices = [(address.id, str(address)) for address in addresses]
- self.fields['address'].choices = self.CHOICES + address_choices
-
-
-class BillingAddressChoiceForm(AddressChoiceForm):
- """Choose one of user's addresses, a shipping one or to create new."""
-
- NEW_ADDRESS = 'new_address'
- SHIPPING_ADDRESS = 'shipping_address'
- CHOICES = [
- (NEW_ADDRESS, pgettext_lazy(
- 'Billing addresses form choice', 'Enter a new address')),
- (SHIPPING_ADDRESS, pgettext_lazy(
- 'Billing addresses form choice', 'Same as shipping'))]
-
- address = forms.ChoiceField(
- label=pgettext_lazy('Billing addresses form field label', 'Address'),
- choices=CHOICES, initial=SHIPPING_ADDRESS, widget=forms.RadioSelect)
-
-
-class ShippingCountryMethodChoiceField(forms.ModelChoiceField):
- """Shipping method country choice field.
-
- Uses a radio group instead of a dropdown and includes estimated shipping
- prices.
- """
-
- taxes = None
- widget = forms.RadioSelect()
-
- def label_from_instance(self, obj):
- """Return a friendly label for the shipping method."""
- price = get_taxed_shipping_price(obj.price, self.taxes)
- if display_gross_prices():
- price = price.gross
- else:
- price = price.net
- price_html = format_money(price)
- label = mark_safe('%s %s' % (obj.shipping_method, price_html))
- return label
-
-
-class CartShippingMethodForm(forms.ModelForm):
- """Cart shipping method form."""
-
- shipping_method = ShippingCountryMethodChoiceField(
- queryset=ShippingMethodCountry.objects.select_related(
- 'shipping_method').order_by('price').all(),
- label=pgettext_lazy(
- 'Shipping method form field label', 'Shipping method'),
- required=True)
-
- class Meta:
- model = Cart
- fields = ['shipping_method']
-
- def __init__(self, *args, **kwargs):
- taxes = kwargs.pop('taxes')
- super().__init__(*args, **kwargs)
- method_field = self.fields['shipping_method']
- method_field.taxes = taxes
-
- country_code = self.instance.shipping_address.country.code
- if country_code:
- queryset = method_field.queryset
- method_field.queryset = queryset.unique_for_country_code(
- country_code)
-
- if self.initial.get('shipping_method') is None:
- self.initial['shipping_method'] = method_field.queryset.first()
-
- method_field.empty_label = None
-
-
-class CartNoteForm(forms.ModelForm):
- """Save note in cart."""
-
- note = forms.CharField(
- max_length=250, required=False, strip=True, label=False,
- widget=forms.Textarea({'rows': 3}))
-
- class Meta:
- model = Cart
- fields = ['note']
-
-
-class VoucherField(forms.ModelChoiceField):
-
- default_error_messages = {
- 'invalid_choice': pgettext_lazy(
- 'Voucher form error', 'Discount code incorrect or expired')}
-
-
-class CartVoucherForm(forms.ModelForm):
- """Apply voucher to a cart form."""
-
- voucher = VoucherField(
- queryset=Voucher.objects.none(),
- to_field_name='code',
- help_text=pgettext_lazy(
- 'Checkout discount form label for voucher field',
- 'Gift card or discount code'),
- widget=forms.TextInput)
-
- class Meta:
- model = Cart
- fields = ['voucher']
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.fields['voucher'].queryset = Voucher.objects.active(
- date=date.today())
-
- def clean(self):
- from .utils import get_voucher_discount_for_cart
- cleaned_data = super().clean()
- if 'voucher' in cleaned_data:
- voucher = cleaned_data['voucher']
- try:
- discount_amount = get_voucher_discount_for_cart(
- voucher, self.instance)
- cleaned_data['discount_amount'] = discount_amount
- except NotApplicable as e:
- self.add_error('voucher', smart_text(e))
- return cleaned_data
-
- def save(self, commit=True):
- voucher = self.cleaned_data['voucher']
- self.instance.voucher_code = voucher.code
- 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/urls.py b/saleor/cart/checkout/urls.py
deleted file mode 100644
index 23d7da5477..0000000000
--- a/saleor/cart/checkout/urls.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from django.conf.urls import url
-
-from . import views
-from .views.discount import remove_voucher_view
-
-urlpatterns = [
- url(r'^$', views.index_view, name='checkout-index'),
- url(r'^shipping-address/', views.shipping_address_view,
- name='checkout-shipping-address'),
- url(r'^shipping-method/', views.shipping_method_view,
- name='checkout-shipping-method'),
- url(r'^summary/', views.summary_view, name='checkout-summary'),
- url(r'^remove_voucher/', remove_voucher_view,
- name='checkout-remove-voucher'),
- url(r'^login/', views.login, name='checkout-login')]
diff --git a/saleor/cart/checkout/utils.py b/saleor/cart/checkout/utils.py
deleted file mode 100644
index d618f373a5..0000000000
--- a/saleor/cart/checkout/utils.py
+++ /dev/null
@@ -1,499 +0,0 @@
-from datetime import date
-
-from django.db import transaction
-from django.utils.encoding import smart_text
-from django.utils.translation import get_language, pgettext
-
-from ...account.forms import get_address_form
-from ...account.models import Address
-from ...account.utils import store_user_address
-from ...cart.checkout.forms import (
- AddressChoiceForm, AnonymousUserBillingForm, AnonymousUserShippingForm,
- BillingAddressChoiceForm)
-from ...cart.utils import (
- get_category_variants_and_prices, get_product_variants_and_prices)
-from ...core.utils.taxes import ZERO_MONEY, get_taxes_for_country
-from ...discount import VoucherType
-from ...discount.models import NotApplicable, Voucher
-from ...discount.utils import (
- get_product_or_category_voucher_discount, get_shipping_voucher_discount,
- get_value_voucher_discount, increase_voucher_usage)
-from ...order.models import Order
-from ...order.utils import add_variant_to_order
-
-
-def get_shipping_address_forms(cart, user_addresses, data, country):
- """Forms initialized with data depending on shipping address in cart."""
- shipping_address = cart.shipping_address
-
- if shipping_address and shipping_address in user_addresses:
- address_form, preview = get_address_form(
- data, country_code=country.code,
- initial={'country': country})
- addresses_form = AddressChoiceForm(
- data, addresses=user_addresses,
- initial={'address': shipping_address.id})
- elif shipping_address:
- address_form, preview = get_address_form(
- data, country_code=shipping_address.country.code,
- instance=shipping_address)
- addresses_form = AddressChoiceForm(
- data, addresses=user_addresses)
- else:
- address_form, preview = get_address_form(
- 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 an 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'] !=
- AddressChoiceForm.NEW_ADDRESS)
-
- if use_existing_address:
- address_id = addresses_form.cleaned_data['address']
- address = Address.objects.get(id=address_id)
- change_shipping_address_in_cart(cart, address)
- updated = True
-
- elif address_form.is_valid():
- address = address_form.save()
- change_shipping_address_in_cart(cart, address)
- updated = True
-
- return addresses_form, address_form, updated
-
-
-def update_shipping_address_in_anonymous_cart(cart, data, country):
- """Return shipping address choice forms and if an address was updated."""
- address_form, preview = get_address_form(
- data, country_code=country.code,
- autocomplete_type='shipping',
- instance=cart.shipping_address,
- initial={'country': country})
- user_form = AnonymousUserShippingForm(
- data if not preview else None, instance=cart)
-
- updated = False
-
- if user_form.is_valid() and address_form.is_valid():
- user_form.save()
- address = address_form.save()
- change_shipping_address_in_cart(cart, address)
- updated = True
-
- return user_form, address_form, updated
-
-
-def get_billing_forms_with_shipping(cart, data, user_addresses, country):
- """Get billing form based on a the current billing and shipping data."""
- shipping_address = cart.shipping_address
- billing_address = cart.billing_address or Address(country=country)
-
- if not billing_address.id or billing_address == shipping_address:
- address_form, preview = get_address_form(
- data, country_code=shipping_address.country.code,
- autocomplete_type='billing',
- initial={'country': shipping_address.country})
- addresses_form = BillingAddressChoiceForm(
- data, addresses=user_addresses, initial={
- 'address': BillingAddressChoiceForm.SHIPPING_ADDRESS})
- elif billing_address in user_addresses:
- address_form, preview = get_address_form(
- data, country_code=billing_address.country.code,
- autocomplete_type='billing',
- initial={'country': billing_address.country})
- addresses_form = BillingAddressChoiceForm(
- data, addresses=user_addresses, initial={
- 'address': billing_address.id})
- else:
- address_form, preview = get_address_form(
- data, country_code=billing_address.country.code,
- autocomplete_type='billing',
- initial={'country': billing_address.country},
- instance=billing_address)
- addresses_form = BillingAddressChoiceForm(
- data, addresses=user_addresses, initial={
- 'address': BillingAddressChoiceForm.NEW_ADDRESS})
-
- return address_form, addresses_form, preview
-
-
-def update_billing_address_in_cart_with_shipping(
- cart, user_addresses, data, country):
- """Return shipping address choice forms and if an address was updated."""
- address_form, addresses_form, preview = get_billing_forms_with_shipping(
- cart, data, user_addresses, country)
-
- updated = False
-
- if addresses_form.is_valid() and not preview:
- address = None
- address_id = addresses_form.cleaned_data['address']
-
- if address_id == BillingAddressChoiceForm.SHIPPING_ADDRESS:
- if cart.user and cart.shipping_address in user_addresses:
- address = cart.shipping_address
- else:
- address = cart.shipping_address.get_copy()
- elif address_id != BillingAddressChoiceForm.NEW_ADDRESS:
- address = user_addresses.get(id=address_id)
- elif address_form.is_valid():
- address = address_form.save()
-
- if address:
- change_billing_address_in_cart(cart, address)
- updated = True
-
- return addresses_form, address_form, updated
-
-
-def get_anonymous_summary_without_shipping_forms(cart, data, country):
- """Forms initialized with data depending on addresses in cart."""
- billing_address = cart.billing_address
-
- if billing_address:
- address_form, preview = get_address_form(
- data, country_code=billing_address.country.code,
- autocomplete_type='billing', instance=billing_address)
- else:
- address_form, preview = get_address_form(
- data, country_code=country.code,
- autocomplete_type='billing', initial={'country': country})
-
- return address_form, preview
-
-
-def update_billing_address_in_anonymous_cart(cart, data, country):
- """Return shipping address choice forms and if an address was updated."""
- address_form, preview = get_anonymous_summary_without_shipping_forms(
- cart, data, country)
- user_form = AnonymousUserBillingForm(data, instance=cart)
-
- updated = False
-
- if user_form.is_valid() and address_form.is_valid() and not preview:
- user_form.save()
- address = address_form.save()
- change_billing_address_in_cart(cart, address)
- updated = True
-
- return user_form, address_form, updated
-
-
-def get_summary_without_shipping_forms(cart, user_addresses, data, country):
- """Forms initialized with data depending on addresses in cart."""
- billing_address = cart.billing_address
-
- if billing_address and billing_address in user_addresses:
- address_form, preview = get_address_form(
- data,
- autocomplete_type='billing',
- country_code=billing_address.country.code,
- initial={'country': billing_address.country})
- initial_address = billing_address.id
- elif billing_address:
- address_form, preview = get_address_form(
- data,
- autocomplete_type='billing',
- country_code=billing_address.country.code,
- initial={'country': billing_address.country},
- instance=billing_address)
- initial_address = AddressChoiceForm.NEW_ADDRESS
- else:
- address_form, preview = get_address_form(
- data,
- autocomplete_type='billing',
- country_code=country.code,
- initial={'country': country})
- if cart.user and cart.user.default_billing_address:
- initial_address = cart.user.default_billing_address.id
- else:
- initial_address = AddressChoiceForm.NEW_ADDRESS
-
- addresses_form = AddressChoiceForm(
- data, addresses=user_addresses, initial={'address': initial_address})
- return address_form, addresses_form, preview
-
-
-def update_billing_address_in_cart(cart, user_addresses, data, country):
- """Return shipping address choice forms and if an address was updated."""
- address_form, addresses_form, preview = (
- get_summary_without_shipping_forms(
- cart, user_addresses, data, country))
-
- updated = False
-
- if addresses_form.is_valid():
- use_existing_address = (
- addresses_form.cleaned_data['address'] !=
- AddressChoiceForm.NEW_ADDRESS)
-
- if use_existing_address:
- address_id = addresses_form.cleaned_data['address']
- address = Address.objects.get(id=address_id)
- change_billing_address_in_cart(cart, address)
- updated = True
-
- elif address_form.is_valid():
- address = address_form.save()
- change_billing_address_in_cart(cart, address)
- updated = True
-
- return addresses_form, address_form, updated
-
-
-def change_billing_address_in_cart(cart, address):
- """Save billing address in cart if changed.
-
- Remove previously saved address if not connected to any user.
- """
- has_address_changed = (
- not address and cart.billing_address or
- address and not cart.billing_address or
- address and cart.billing_address and address != cart.billing_address)
- if has_address_changed:
- remove_old_address = (
- cart.billing_address and (not cart.user or (
- cart.user and
- cart.billing_address not in cart.user.addresses.all())))
- if remove_old_address:
- cart.billing_address.delete()
- cart.billing_address = address
- cart.save(update_fields=['billing_address'])
-
-
-def change_shipping_address_in_cart(cart, address):
- """Save shipping address in cart if changed.
-
- Remove previously saved address if not connected to any user.
- """
- has_address_changed = (
- not address and cart.shipping_address or
- address and not cart.shipping_address or
- address and cart.shipping_address and address != cart.shipping_address)
- if has_address_changed:
- remove_old_address = (
- cart.shipping_address and (not cart.user or (
- cart.user and
- cart.shipping_address not in cart.user.addresses.all())))
- if remove_old_address:
- cart.shipping_address.delete()
- cart.shipping_address = address
- cart.save(update_fields=['shipping_address'])
-
-
-def get_cart_data_for_checkout(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_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_total': total}
-
-
-def _get_value_voucher_discount_for_cart(voucher, cart):
- """Calculate discount value for a voucher of value type."""
- return get_value_voucher_discount(voucher, cart.get_subtotal())
-
-
-def _get_shipping_voucher_discount_for_cart(voucher, cart):
- """Calculate discount value for a voucher of shipping type."""
- if not cart.is_shipping_required():
- msg = pgettext(
- 'Voucher not applicable',
- 'Your order does not require shipping.')
- raise NotApplicable(msg)
- shipping_method = cart.shipping_method
- if not shipping_method:
- msg = pgettext(
- 'Voucher not applicable',
- 'Please select a shipping method first.')
- raise NotApplicable(msg)
- not_valid_for_country = (
- voucher.apply_to and shipping_method.country_code != voucher.apply_to)
- if not_valid_for_country:
- msg = pgettext(
- 'Voucher not applicable',
- 'This offer is only valid in %(country)s.')
- raise NotApplicable(
- msg % {'country': voucher.get_apply_to_display()})
- return get_shipping_voucher_discount(
- voucher, cart.get_subtotal(), shipping_method.get_total_price())
-
-
-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(cart, voucher.product)]
- else:
- prices = [
- variant_price for _, variant_price in
- get_category_variants_and_prices(cart, voucher.category)]
- if not prices:
- msg = pgettext(
- 'Voucher not applicable',
- 'This offer is only valid for selected items.')
- raise NotApplicable(msg)
- return get_product_or_category_voucher_discount(voucher, prices)
-
-
-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_cart(voucher, cart)
- if voucher.type == VoucherType.SHIPPING:
- 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_cart(
- voucher, cart)
- raise NotImplementedError('Unknown discount type')
-
-
-def get_voucher_for_cart(cart, vouchers=None):
- """Return voucher with voucher code saved in cart if active or None."""
- if cart.voucher_code is not None:
- if vouchers is None:
- vouchers = Voucher.objects.active(date=date.today())
- try:
- return vouchers.get(code=cart.voucher_code)
- except Voucher.DoesNotExist:
- return None
- return None
-
-
-def recalculate_cart_discount(cart):
- """Recalculate `cart.discount` based on the voucher.
-
- Will clear both voucher and discount if the discount is no longer
- applicable.
- """
- voucher = get_voucher_for_cart(cart)
- if voucher is not None:
- try:
- cart.discount_amount = get_voucher_discount_for_cart(voucher, cart)
- cart.discount_name = voucher.name
- cart.save(update_fields=['discount_amount', 'discount_name'])
- except NotApplicable:
- remove_voucher_from_cart(cart)
- else:
- remove_voucher_from_cart(cart)
-
-
-def remove_voucher_from_cart(cart):
- """Remove voucher data from cart."""
- cart.voucher_code = None
- cart.discount_name = None
- cart.discount_amount = ZERO_MONEY
- cart.save(update_fields=[
- 'voucher_code', 'discount_name', 'discount_amount'])
-
-
-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.user:
- if billing_address not in cart.user.addresses.all():
- store_user_address(cart.user, billing_address, billing=True)
- billing_address = billing_address.get_copy()
-
- if cart.is_shipping_required():
- shipping_address = cart.shipping_address
- shipping_method = cart.shipping_method
- shipping_method_name = smart_text(shipping_method)
-
- if cart.user and shipping_address not in cart.user.addresses.all():
- store_user_address(cart.user, shipping_address, shipping=True)
-
- shipping_address = shipping_address.get_copy()
- else:
- shipping_address = None
- shipping_method = None
- shipping_method_name = None
-
- 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:
- 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)
-
- if voucher:
- increase_voucher_usage(voucher)
-
- if cart.note:
- order.notes.create(user=order.user, content=cart.note)
-
- return order
diff --git a/saleor/cart/checkout/views/__init__.py b/saleor/cart/checkout/views/__init__.py
deleted file mode 100644
index 09edc5c28f..0000000000
--- a/saleor/cart/checkout/views/__init__.py
+++ /dev/null
@@ -1,84 +0,0 @@
-from django.shortcuts import redirect
-from django.template.response import TemplateResponse
-
-from ....account.forms import LoginForm
-from ....cart.models import Cart
-from ....cart.utils import get_or_empty_db_cart
-from ..forms import CartShippingMethodForm
-from ..utils import get_cart_data_for_checkout, get_taxes_for_cart
-from .discount import add_voucher_form, validate_voucher
-from .shipping import (
- anonymous_user_shipping_address_view, user_shipping_address_view)
-from .summary import (
- anonymous_summary_without_shipping, summary_with_shipping_view,
- summary_without_shipping)
-from .validators import (
- validate_cart, validate_is_shipping_required, validate_shipping_address,
- validate_shipping_method)
-
-
-@get_or_empty_db_cart(Cart.objects.for_display())
-@validate_cart
-def login(request, cart):
- """Allow the user to log in prior to checkout."""
- if request.user.is_authenticated:
- return redirect('cart:checkout-index')
- form = LoginForm()
- return TemplateResponse(request, 'checkout/login.html', {'form': form})
-
-
-@get_or_empty_db_cart(Cart.objects.for_display())
-@validate_cart
-@validate_is_shipping_required
-def index_view(request, cart):
- """Redirect to the initial step of checkout."""
- return redirect('cart:checkout-shipping-address')
-
-
-@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):
- """Display the correct shipping address step."""
- if request.user.is_authenticated:
- return user_shipping_address_view(request, cart)
- return anonymous_user_shipping_address_view(request, cart)
-
-
-@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):
- """Display the shipping method selection step."""
- taxes = get_taxes_for_cart(cart, request.taxes)
- form = CartShippingMethodForm(
- request.POST or None, taxes=taxes, instance=cart,
- initial={'shipping_method': cart.shipping_method})
-
- if form.is_valid():
- form.save()
- return redirect('cart:checkout-summary')
-
- ctx = get_cart_data_for_checkout(cart, request.discounts, taxes)
- ctx.update({'shipping_method_form': form})
- return TemplateResponse(request, 'checkout/shipping_method.html', ctx)
-
-
-@get_or_empty_db_cart(Cart.objects.for_display())
-@validate_voucher
-@validate_cart
-@add_voucher_form
-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)
- if request.user.is_authenticated:
- return summary_without_shipping(request, cart)
- return anonymous_summary_without_shipping(request, cart)
diff --git a/saleor/cart/forms.py b/saleor/cart/forms.py
index 84ea003271..e03a498953 100644
--- a/saleor/cart/forms.py
+++ b/saleor/cart/forms.py
@@ -1,13 +1,21 @@
"""Cart-related forms and fields."""
+from datetime import date
+
from django import forms
from django.conf import settings
from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExist
+from django.utils.encoding import smart_text
+from django.utils.safestring import mark_safe
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_countries.fields import LazyTypedChoiceField, countries
-from ..cart.utils import add_variant_to_cart
from ..core.exceptions import InsufficientStock
-from ..shipping.utils import get_shipment_options
+from ..core.utils import format_money
+from ..core.utils.taxes import display_gross_prices
+from ..discount.models import NotApplicable, Voucher
+from ..shipping.models import ShippingMethodCountry
+from ..shipping.utils import get_shipment_options, get_taxed_shipping_price
+from .models import Cart
class QuantityField(forms.IntegerField):
@@ -84,6 +92,7 @@ class AddToCartForm(forms.Form):
def save(self):
"""Add the selected product variant and quantity to the cart."""
+ from .utils import add_variant_to_cart
variant = self.get_variant(self.cleaned_data)
quantity = self.cleaned_data['quantity']
add_variant_to_cart(self.cart, variant, quantity)
@@ -143,6 +152,7 @@ class ReplaceCartLineForm(AddToCartForm):
def save(self):
"""Replace the selected product's quantity in cart."""
+ from .utils import add_variant_to_cart
variant = self.get_variant(self.cleaned_data)
quantity = self.cleaned_data['quantity']
add_variant_to_cart(self.cart, variant, quantity, replace=True)
@@ -163,3 +173,176 @@ class CountryForm(forms.Form):
"""Return a list of shipping methods for the selected country."""
code = self.cleaned_data['country']
return get_shipment_options(code, self.taxes)
+
+
+class AnonymousUserShippingForm(forms.ModelForm):
+ """Additional shipping information form for users who are not logged in."""
+
+ user_email = forms.EmailField(
+ widget=forms.EmailInput(attrs={'autocomplete': 'shipping email'}),
+ label=pgettext_lazy('Address form field label', 'Email'))
+
+ class Meta:
+ model = Cart
+ fields = ['user_email']
+
+
+class AnonymousUserBillingForm(forms.ModelForm):
+ """Additional billing information form for users who are not logged in."""
+
+ user_email = forms.EmailField(
+ widget=forms.EmailInput(attrs={'autocomplete': 'billing email'}),
+ label=pgettext_lazy('Address form field label', 'Email'))
+
+ class Meta:
+ model = Cart
+ fields = ['user_email']
+
+
+class AddressChoiceForm(forms.Form):
+ """Choose one of user's addresses or to create new one."""
+
+ NEW_ADDRESS = 'new_address'
+ CHOICES = [
+ (NEW_ADDRESS, pgettext_lazy(
+ 'Shipping addresses form choice', 'Enter a new address'))]
+
+ address = forms.ChoiceField(
+ label=pgettext_lazy('Shipping addresses form field label', 'Address'),
+ choices=CHOICES, initial=NEW_ADDRESS, widget=forms.RadioSelect)
+
+ def __init__(self, *args, **kwargs):
+ addresses = kwargs.pop('addresses')
+ super().__init__(*args, **kwargs)
+ address_choices = [(address.id, str(address)) for address in addresses]
+ self.fields['address'].choices = self.CHOICES + address_choices
+
+
+class BillingAddressChoiceForm(AddressChoiceForm):
+ """Choose one of user's addresses, a shipping one or to create new."""
+
+ NEW_ADDRESS = 'new_address'
+ SHIPPING_ADDRESS = 'shipping_address'
+ CHOICES = [
+ (NEW_ADDRESS, pgettext_lazy(
+ 'Billing addresses form choice', 'Enter a new address')),
+ (SHIPPING_ADDRESS, pgettext_lazy(
+ 'Billing addresses form choice', 'Same as shipping'))]
+
+ address = forms.ChoiceField(
+ label=pgettext_lazy('Billing addresses form field label', 'Address'),
+ choices=CHOICES, initial=SHIPPING_ADDRESS, widget=forms.RadioSelect)
+
+
+class ShippingCountryMethodChoiceField(forms.ModelChoiceField):
+ """Shipping method country choice field.
+
+ Uses a radio group instead of a dropdown and includes estimated shipping
+ prices.
+ """
+
+ taxes = None
+ widget = forms.RadioSelect()
+
+ def label_from_instance(self, obj):
+ """Return a friendly label for the shipping method."""
+ price = get_taxed_shipping_price(obj.price, self.taxes)
+ if display_gross_prices():
+ price = price.gross
+ else:
+ price = price.net
+ price_html = format_money(price)
+ label = mark_safe('%s %s' % (obj.shipping_method, price_html))
+ return label
+
+
+class CartShippingMethodForm(forms.ModelForm):
+ """Cart shipping method form."""
+
+ shipping_method = ShippingCountryMethodChoiceField(
+ queryset=ShippingMethodCountry.objects.select_related(
+ 'shipping_method').order_by('price').all(),
+ label=pgettext_lazy(
+ 'Shipping method form field label', 'Shipping method'),
+ required=True)
+
+ class Meta:
+ model = Cart
+ fields = ['shipping_method']
+
+ def __init__(self, *args, **kwargs):
+ taxes = kwargs.pop('taxes')
+ super().__init__(*args, **kwargs)
+ method_field = self.fields['shipping_method']
+ method_field.taxes = taxes
+
+ country_code = self.instance.shipping_address.country.code
+ if country_code:
+ queryset = method_field.queryset
+ method_field.queryset = queryset.unique_for_country_code(
+ country_code)
+
+ if self.initial.get('shipping_method') is None:
+ self.initial['shipping_method'] = method_field.queryset.first()
+
+ method_field.empty_label = None
+
+
+class CartNoteForm(forms.ModelForm):
+ """Save note in cart."""
+
+ note = forms.CharField(
+ max_length=250, required=False, strip=True, label=False,
+ widget=forms.Textarea({'rows': 3}))
+
+ class Meta:
+ model = Cart
+ fields = ['note']
+
+
+class VoucherField(forms.ModelChoiceField):
+
+ default_error_messages = {
+ 'invalid_choice': pgettext_lazy(
+ 'Voucher form error', 'Discount code incorrect or expired')}
+
+
+class CartVoucherForm(forms.ModelForm):
+ """Apply voucher to a cart form."""
+
+ voucher = VoucherField(
+ queryset=Voucher.objects.none(),
+ to_field_name='code',
+ help_text=pgettext_lazy(
+ 'Checkout discount form label for voucher field',
+ 'Gift card or discount code'),
+ widget=forms.TextInput)
+
+ class Meta:
+ model = Cart
+ fields = ['voucher']
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.fields['voucher'].queryset = Voucher.objects.active(
+ date=date.today())
+
+ def clean(self):
+ from .utils import get_voucher_discount_for_cart
+ cleaned_data = super().clean()
+ if 'voucher' in cleaned_data:
+ voucher = cleaned_data['voucher']
+ try:
+ discount_amount = get_voucher_discount_for_cart(
+ voucher, self.instance)
+ cleaned_data['discount_amount'] = discount_amount
+ except NotApplicable as e:
+ self.add_error('voucher', smart_text(e))
+ return cleaned_data
+
+ def save(self, commit=True):
+ voucher = self.cleaned_data['voucher']
+ self.instance.voucher_code = voucher.code
+ self.instance.discount_name = voucher.name
+ self.instance.discount_amount = self.cleaned_data['discount_amount']
+ return super().save(commit)
diff --git a/saleor/cart/migrations/0007_merge_checkout_into_cart.py b/saleor/cart/migrations/0007_merge_cart_with_checkout.py
similarity index 100%
rename from saleor/cart/migrations/0007_merge_checkout_into_cart.py
rename to saleor/cart/migrations/0007_merge_cart_with_checkout.py
diff --git a/saleor/cart/urls.py b/saleor/cart/urls.py
index a5e7ab8fb3..31726f8d75 100644
--- a/saleor/cart/urls.py
+++ b/saleor/cart/urls.py
@@ -1,12 +1,23 @@
-from django.conf.urls import include, url
+from django.conf.urls import url
from . import views
-from .checkout.urls import urlpatterns as checkout_urls
+from saleor.cart.views.discount import remove_voucher_view
-urlpatterns = [
- url(r'^$', views.index, name='index'),
- url(r'^update/(?P<variant_id>\d+)/$', views.update, name='update-line'),
- url(r'^summary/$', views.summary, name='cart-summary'),
- url(r'^shipping-options/$', views.get_shipping_options,
- name='shipping-options'),
- url(r'^checkout/', include(checkout_urls))]
+cart_urlpatterns = [
+ url(r'^$', views.cart_index, name='index'),
+ url(r'^update/(?P<variant_id>\d+)/$',
+ views.update_cart_line, name='update-line'),
+ url(r'^summary/$', views.cart_summary, name='summary'),
+ url(r'^shipping-options/$', views.cart_shipping_options,
+ name='shipping-options')]
+
+checkout_urlpatterns = [
+ url(r'^$', views.checkout_index, name='index'),
+ url(r'^shipping-address/', views.checkout_shipping_address,
+ name='shipping-address'),
+ url(r'^shipping-method/', views.checkout_shipping_method,
+ name='shipping-method'),
+ url(r'^summary/', views.checkout_summary, name='summary'),
+ url(r'^remove_voucher/', remove_voucher_view,
+ name='remove-voucher'),
+ url(r'^login/', views.checkout_login, name='login')]
diff --git a/saleor/cart/utils.py b/saleor/cart/utils.py
index d37c422a3f..6735c9a385 100644
--- a/saleor/cart/utils.py
+++ b/saleor/cart/utils.py
@@ -1,17 +1,31 @@
"""Cart-related utility functions."""
-from datetime import timedelta
+from datetime import date, timedelta
from functools import wraps
from uuid import UUID
from django.contrib import messages
from django.db import transaction
from django.db.models import Sum
-from django.utils.translation import pgettext_lazy
+from django.utils.encoding import smart_text
+from django.utils.translation import get_language, pgettext, pgettext_lazy
from prices import TaxedMoneyRange
from . import logger
+from ..account.forms import get_address_form
+from ..account.models import Address
+from ..account.utils import store_user_address
+from ..cart.forms import (
+ AddressChoiceForm, AnonymousUserBillingForm, AnonymousUserShippingForm,
+ BillingAddressChoiceForm)
from ..core.exceptions import InsufficientStock
from ..core.utils import to_local_currency
+from ..core.utils.taxes import ZERO_MONEY, get_taxes_for_country
+from ..discount import VoucherType
+from ..discount.models import NotApplicable, Voucher
+from ..discount.utils import (
+ get_product_or_category_voucher_discount, get_shipping_voucher_discount,
+ get_value_voucher_discount, increase_voucher_usage)
+from ..order.models import Order
from .models import Cart
COOKIE_NAME = 'cart'
@@ -301,3 +315,482 @@ def add_variant_to_cart(
line.save(update_fields=['quantity'])
update_cart_quantity(cart)
+
+
+def get_shipping_address_forms(cart, user_addresses, data, country):
+ """Forms initialized with data depending on shipping address in cart."""
+ shipping_address = cart.shipping_address
+
+ if shipping_address and shipping_address in user_addresses:
+ address_form, preview = get_address_form(
+ data, country_code=country.code,
+ initial={'country': country})
+ addresses_form = AddressChoiceForm(
+ data, addresses=user_addresses,
+ initial={'address': shipping_address.id})
+ elif shipping_address:
+ address_form, preview = get_address_form(
+ data, country_code=shipping_address.country.code,
+ instance=shipping_address)
+ addresses_form = AddressChoiceForm(
+ data, addresses=user_addresses)
+ else:
+ address_form, preview = get_address_form(
+ 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 an 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'] !=
+ AddressChoiceForm.NEW_ADDRESS)
+
+ if use_existing_address:
+ address_id = addresses_form.cleaned_data['address']
+ address = Address.objects.get(id=address_id)
+ change_shipping_address_in_cart(cart, address)
+ updated = True
+
+ elif address_form.is_valid():
+ address = address_form.save()
+ change_shipping_address_in_cart(cart, address)
+ updated = True
+
+ return addresses_form, address_form, updated
+
+
+def update_shipping_address_in_anonymous_cart(cart, data, country):
+ """Return shipping address choice forms and if an address was updated."""
+ address_form, preview = get_address_form(
+ data, country_code=country.code,
+ autocomplete_type='shipping',
+ instance=cart.shipping_address,
+ initial={'country': country})
+ user_form = AnonymousUserShippingForm(
+ data if not preview else None, instance=cart)
+
+ updated = False
+
+ if user_form.is_valid() and address_form.is_valid():
+ user_form.save()
+ address = address_form.save()
+ change_shipping_address_in_cart(cart, address)
+ updated = True
+
+ return user_form, address_form, updated
+
+
+def get_billing_forms_with_shipping(cart, data, user_addresses, country):
+ """Get billing form based on a the current billing and shipping data."""
+ shipping_address = cart.shipping_address
+ billing_address = cart.billing_address or Address(country=country)
+
+ if not billing_address.id or billing_address == shipping_address:
+ address_form, preview = get_address_form(
+ data, country_code=shipping_address.country.code,
+ autocomplete_type='billing',
+ initial={'country': shipping_address.country})
+ addresses_form = BillingAddressChoiceForm(
+ data, addresses=user_addresses, initial={
+ 'address': BillingAddressChoiceForm.SHIPPING_ADDRESS})
+ elif billing_address in user_addresses:
+ address_form, preview = get_address_form(
+ data, country_code=billing_address.country.code,
+ autocomplete_type='billing',
+ initial={'country': billing_address.country})
+ addresses_form = BillingAddressChoiceForm(
+ data, addresses=user_addresses, initial={
+ 'address': billing_address.id})
+ else:
+ address_form, preview = get_address_form(
+ data, country_code=billing_address.country.code,
+ autocomplete_type='billing',
+ initial={'country': billing_address.country},
+ instance=billing_address)
+ addresses_form = BillingAddressChoiceForm(
+ data, addresses=user_addresses, initial={
+ 'address': BillingAddressChoiceForm.NEW_ADDRESS})
+
+ return address_form, addresses_form, preview
+
+
+def update_billing_address_in_cart_with_shipping(
+ cart, user_addresses, data, country):
+ """Return shipping address choice forms and if an address was updated."""
+ address_form, addresses_form, preview = get_billing_forms_with_shipping(
+ cart, data, user_addresses, country)
+
+ updated = False
+
+ if addresses_form.is_valid() and not preview:
+ address = None
+ address_id = addresses_form.cleaned_data['address']
+
+ if address_id == BillingAddressChoiceForm.SHIPPING_ADDRESS:
+ if cart.user and cart.shipping_address in user_addresses:
+ address = cart.shipping_address
+ else:
+ address = cart.shipping_address.get_copy()
+ elif address_id != BillingAddressChoiceForm.NEW_ADDRESS:
+ address = user_addresses.get(id=address_id)
+ elif address_form.is_valid():
+ address = address_form.save()
+
+ if address:
+ change_billing_address_in_cart(cart, address)
+ updated = True
+
+ return addresses_form, address_form, updated
+
+
+def get_anonymous_summary_without_shipping_forms(cart, data, country):
+ """Forms initialized with data depending on addresses in cart."""
+ billing_address = cart.billing_address
+
+ if billing_address:
+ address_form, preview = get_address_form(
+ data, country_code=billing_address.country.code,
+ autocomplete_type='billing', instance=billing_address)
+ else:
+ address_form, preview = get_address_form(
+ data, country_code=country.code,
+ autocomplete_type='billing', initial={'country': country})
+
+ return address_form, preview
+
+
+def update_billing_address_in_anonymous_cart(cart, data, country):
+ """Return shipping address choice forms and if an address was updated."""
+ address_form, preview = get_anonymous_summary_without_shipping_forms(
+ cart, data, country)
+ user_form = AnonymousUserBillingForm(data, instance=cart)
+
+ updated = False
+
+ if user_form.is_valid() and address_form.is_valid() and not preview:
+ user_form.save()
+ address = address_form.save()
+ change_billing_address_in_cart(cart, address)
+ updated = True
+
+ return user_form, address_form, updated
+
+
+def get_summary_without_shipping_forms(cart, user_addresses, data, country):
+ """Forms initialized with data depending on addresses in cart."""
+ billing_address = cart.billing_address
+
+ if billing_address and billing_address in user_addresses:
+ address_form, preview = get_address_form(
+ data,
+ autocomplete_type='billing',
+ country_code=billing_address.country.code,
+ initial={'country': billing_address.country})
+ initial_address = billing_address.id
+ elif billing_address:
+ address_form, preview = get_address_form(
+ data,
+ autocomplete_type='billing',
+ country_code=billing_address.country.code,
+ initial={'country': billing_address.country},
+ instance=billing_address)
+ initial_address = AddressChoiceForm.NEW_ADDRESS
+ else:
+ address_form, preview = get_address_form(
+ data,
+ autocomplete_type='billing',
+ country_code=country.code,
+ initial={'country': country})
+ if cart.user and cart.user.default_billing_address:
+ initial_address = cart.user.default_billing_address.id
+ else:
+ initial_address = AddressChoiceForm.NEW_ADDRESS
+
+ addresses_form = AddressChoiceForm(
+ data, addresses=user_addresses, initial={'address': initial_address})
+ return address_form, addresses_form, preview
+
+
+def update_billing_address_in_cart(cart, user_addresses, data, country):
+ """Return shipping address choice forms and if an address was updated."""
+ address_form, addresses_form, preview = (
+ get_summary_without_shipping_forms(
+ cart, user_addresses, data, country))
+
+ updated = False
+
+ if addresses_form.is_valid():
+ use_existing_address = (
+ addresses_form.cleaned_data['address'] !=
+ AddressChoiceForm.NEW_ADDRESS)
+
+ if use_existing_address:
+ address_id = addresses_form.cleaned_data['address']
+ address = Address.objects.get(id=address_id)
+ change_billing_address_in_cart(cart, address)
+ updated = True
+
+ elif address_form.is_valid():
+ address = address_form.save()
+ change_billing_address_in_cart(cart, address)
+ updated = True
+
+ return addresses_form, address_form, updated
+
+
+def change_billing_address_in_cart(cart, address):
+ """Save billing address in cart if changed.
+
+ Remove previously saved address if not connected to any user.
+ """
+ has_address_changed = (
+ not address and cart.billing_address or
+ address and not cart.billing_address or
+ address and cart.billing_address and address != cart.billing_address)
+ if has_address_changed:
+ remove_old_address = (
+ cart.billing_address and (not cart.user or (
+ cart.user and
+ cart.billing_address not in cart.user.addresses.all())))
+ if remove_old_address:
+ cart.billing_address.delete()
+ cart.billing_address = address
+ cart.save(update_fields=['billing_address'])
+
+
+def change_shipping_address_in_cart(cart, address):
+ """Save shipping address in cart if changed.
+
+ Remove previously saved address if not connected to any user.
+ """
+ has_address_changed = (
+ not address and cart.shipping_address or
+ address and not cart.shipping_address or
+ address and cart.shipping_address and address != cart.shipping_address)
+ if has_address_changed:
+ remove_old_address = (
+ cart.shipping_address and (not cart.user or (
+ cart.user and
+ cart.shipping_address not in cart.user.addresses.all())))
+ if remove_old_address:
+ cart.shipping_address.delete()
+ cart.shipping_address = address
+ cart.save(update_fields=['shipping_address'])
+
+
+def get_cart_data_for_checkout(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_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_total': total}
+
+
+def _get_value_voucher_discount_for_cart(voucher, cart):
+ """Calculate discount value for a voucher of value type."""
+ return get_value_voucher_discount(voucher, cart.get_subtotal())
+
+
+def _get_shipping_voucher_discount_for_cart(voucher, cart):
+ """Calculate discount value for a voucher of shipping type."""
+ if not cart.is_shipping_required():
+ msg = pgettext(
+ 'Voucher not applicable',
+ 'Your order does not require shipping.')
+ raise NotApplicable(msg)
+ shipping_method = cart.shipping_method
+ if not shipping_method:
+ msg = pgettext(
+ 'Voucher not applicable',
+ 'Please select a shipping method first.')
+ raise NotApplicable(msg)
+ not_valid_for_country = (
+ voucher.apply_to and shipping_method.country_code != voucher.apply_to)
+ if not_valid_for_country:
+ msg = pgettext(
+ 'Voucher not applicable',
+ 'This offer is only valid in %(country)s.')
+ raise NotApplicable(
+ msg % {'country': voucher.get_apply_to_display()})
+ return get_shipping_voucher_discount(
+ voucher, cart.get_subtotal(), shipping_method.get_total_price())
+
+
+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(cart, voucher.product)]
+ else:
+ prices = [
+ variant_price for _, variant_price in
+ get_category_variants_and_prices(cart, voucher.category)]
+ if not prices:
+ msg = pgettext(
+ 'Voucher not applicable',
+ 'This offer is only valid for selected items.')
+ raise NotApplicable(msg)
+ return get_product_or_category_voucher_discount(voucher, prices)
+
+
+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_cart(voucher, cart)
+ if voucher.type == VoucherType.SHIPPING:
+ 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_cart(
+ voucher, cart)
+ raise NotImplementedError('Unknown discount type')
+
+
+def get_voucher_for_cart(cart, vouchers=None):
+ """Return voucher with voucher code saved in cart if active or None."""
+ if cart.voucher_code is not None:
+ if vouchers is None:
+ vouchers = Voucher.objects.active(date=date.today())
+ try:
+ return vouchers.get(code=cart.voucher_code)
+ except Voucher.DoesNotExist:
+ return None
+ return None
+
+
+def recalculate_cart_discount(cart):
+ """Recalculate `cart.discount` based on the voucher.
+
+ Will clear both voucher and discount if the discount is no longer
+ applicable.
+ """
+ voucher = get_voucher_for_cart(cart)
+ if voucher is not None:
+ try:
+ cart.discount_amount = get_voucher_discount_for_cart(voucher, cart)
+ cart.discount_name = voucher.name
+ cart.save(update_fields=['discount_amount', 'discount_name'])
+ except NotApplicable:
+ remove_voucher_from_cart(cart)
+ else:
+ remove_voucher_from_cart(cart)
+
+
+def remove_voucher_from_cart(cart):
+ """Remove voucher data from cart."""
+ cart.voucher_code = None
+ cart.discount_name = None
+ cart.discount_amount = ZERO_MONEY
+ cart.save(update_fields=[
+ 'voucher_code', 'discount_name', 'discount_amount'])
+
+
+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
+ from ..order.utils import add_variant_to_order
+
+ 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.user:
+ if billing_address not in cart.user.addresses.all():
+ store_user_address(cart.user, billing_address, billing=True)
+ billing_address = billing_address.get_copy()
+
+ if cart.is_shipping_required():
+ shipping_address = cart.shipping_address
+ shipping_method = cart.shipping_method
+ shipping_method_name = smart_text(shipping_method)
+
+ if cart.user and shipping_address not in cart.user.addresses.all():
+ store_user_address(cart.user, shipping_address, shipping=True)
+
+ shipping_address = shipping_address.get_copy()
+ else:
+ shipping_address = None
+ shipping_method = None
+ shipping_method_name = None
+
+ 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:
+ 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)
+
+ if voucher:
+ increase_voucher_usage(voucher)
+
+ if cart.note:
+ order.notes.create(user=order.user, content=cart.note)
+
+ return order
diff --git a/saleor/cart/views/__init__.py b/saleor/cart/views/__init__.py
new file mode 100644
index 0000000000..9f70440ad0
--- /dev/null
+++ b/saleor/cart/views/__init__.py
@@ -0,0 +1,220 @@
+"""Cart and checkout related views."""
+from django.http import JsonResponse
+from django.shortcuts import get_object_or_404, redirect, render
+from django.template.response import TemplateResponse
+
+from ...account.forms import LoginForm
+from ...core.utils import (
+ format_money, get_user_shipping_country, to_local_currency)
+from ...product.models import ProductVariant
+from ...shipping.utils import get_shipment_options
+from ..forms import CartShippingMethodForm, CountryForm, ReplaceCartLineForm
+from ..models import Cart
+from ..utils import (
+ check_product_availability_and_warn, get_cart_data,
+ get_cart_data_for_checkout, get_or_empty_db_cart, get_taxes_for_cart)
+from .discount import add_voucher_form, validate_voucher
+from .shipping import (
+ anonymous_user_shipping_address_view, user_shipping_address_view)
+from .summary import (
+ anonymous_summary_without_shipping, summary_with_shipping_view,
+ summary_without_shipping)
+from .validators import (
+ validate_cart, validate_is_shipping_required, validate_shipping_address,
+ validate_shipping_method)
+
+
+@get_or_empty_db_cart(Cart.objects.for_display())
+@validate_cart
+def checkout_login(request, cart):
+ """Allow the user to log in prior to checkout."""
+ if request.user.is_authenticated:
+ return redirect('checkout:index')
+ ctx = {'form': LoginForm()}
+ return TemplateResponse(request, 'checkout/login.html', ctx)
+
+
+@get_or_empty_db_cart(Cart.objects.for_display())
+@validate_cart
+@validate_is_shipping_required
+def checkout_index(request, cart):
+ """Redirect to the initial step of checkout."""
+ return redirect('checkout:shipping-address')
+
+
+@get_or_empty_db_cart(Cart.objects.for_display())
+@validate_voucher
+@validate_cart
+@validate_is_shipping_required
+@add_voucher_form
+def checkout_shipping_address(request, cart):
+ """Display the correct shipping address step."""
+ if request.user.is_authenticated:
+ return user_shipping_address_view(request, cart)
+ return anonymous_user_shipping_address_view(request, cart)
+
+
+@get_or_empty_db_cart(Cart.objects.for_display())
+@validate_voucher
+@validate_cart
+@validate_is_shipping_required
+@validate_shipping_address
+@add_voucher_form
+def checkout_shipping_method(request, cart):
+ """Display the shipping method selection step."""
+ taxes = get_taxes_for_cart(cart, request.taxes)
+ form = CartShippingMethodForm(
+ request.POST or None, taxes=taxes, instance=cart,
+ initial={'shipping_method': cart.shipping_method})
+
+ if form.is_valid():
+ form.save()
+ return redirect('checkout:summary')
+
+ ctx = get_cart_data_for_checkout(cart, request.discounts, taxes)
+ ctx.update({'shipping_method_form': form})
+ return TemplateResponse(request, 'checkout/shipping_method.html', ctx)
+
+
+@get_or_empty_db_cart(Cart.objects.for_display())
+@validate_voucher
+@validate_cart
+@add_voucher_form
+def checkout_summary(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)
+ if request.user.is_authenticated:
+ return summary_without_shipping(request, cart)
+ return anonymous_summary_without_shipping(request, cart)
+
+
+@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())
+def cart_index(request, cart):
+ """Display cart details."""
+ discounts = request.discounts
+ taxes = request.taxes
+ cart_lines = []
+ check_product_availability_and_warn(request, cart)
+
+ # refresh required to get updated cart lines and it's quantity
+ try:
+ cart = Cart.objects.prefetch_related(
+ 'lines__variant__product__category').get(pk=cart.pk)
+ except Cart.DoesNotExist:
+ pass
+
+ lines = cart.lines.select_related(
+ 'variant__product__product_type',
+ 'variant__product__category')
+ lines = lines.prefetch_related(
+ 'variant__product__images',
+ 'variant__product__product_type__variant_attributes')
+ for line in lines:
+ initial = {'quantity': line.quantity}
+ form = ReplaceCartLineForm(
+ None, cart=cart, variant=line.variant, initial=initial,
+ discounts=discounts, taxes=taxes)
+ cart_lines.append({
+ 'variant': line.variant,
+ 'get_price': line.variant.get_price(discounts, taxes),
+ 'get_total': line.get_total(discounts, taxes),
+ 'form': form})
+
+ default_country = get_user_shipping_country(request)
+ country_form = CountryForm(initial={'country': default_country})
+ default_country_options = get_shipment_options(default_country, taxes)
+
+ cart_data = get_cart_data(
+ cart, default_country_options, request.currency, discounts, taxes)
+ ctx = {
+ 'cart_lines': cart_lines,
+ 'country_form': country_form,
+ 'default_country_options': default_country_options}
+ ctx.update(cart_data)
+
+ return TemplateResponse(request, 'cart/index.html', ctx)
+
+
+@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())
+def cart_shipping_options(request, cart):
+ """Display shipping options to get a price estimate."""
+ country_form = CountryForm(request.POST or None, taxes=request.taxes)
+ if country_form.is_valid():
+ shipments = country_form.get_shipment_options()
+ else:
+ shipments = None
+ ctx = {
+ 'default_country_options': shipments,
+ 'country_form': country_form}
+ cart_data = get_cart_data(
+ cart, shipments, request.currency, request.discounts, request.taxes)
+ ctx.update(cart_data)
+ return TemplateResponse(request, 'cart/_subtotal_table.html', ctx)
+
+
+@get_or_empty_db_cart()
+def update_cart_line(request, cart, variant_id):
+ """Update the line quantities."""
+ if not request.is_ajax():
+ return redirect('checkout:index')
+ variant = get_object_or_404(ProductVariant, pk=variant_id)
+ discounts = request.discounts
+ taxes = request.taxes
+ status = None
+ form = ReplaceCartLineForm(
+ request.POST, cart=cart, variant=variant, discounts=discounts,
+ taxes=taxes)
+ if form.is_valid():
+ form.save()
+ response = {
+ 'variantId': variant_id,
+ 'subtotal': 0,
+ 'total': 0,
+ 'cart': {
+ 'numItems': cart.quantity,
+ 'numLines': len(cart)}}
+ updated_line = cart.get_line(form.cart_line.variant)
+ if updated_line:
+ response['subtotal'] = format_money(
+ updated_line.get_total(discounts, taxes).gross)
+ if cart:
+ 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:
+ response['localTotal'] = format_money(local_cart_total.gross)
+ status = 200
+ elif request.POST is not None:
+ response = {'error': form.errors}
+ status = 400
+ return JsonResponse(response, status=status)
+
+
+@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())
+def cart_summary(request, cart):
+ """Display a cart summary suitable for displaying on all pages."""
+ discounts = request.discounts
+ taxes = request.taxes
+
+ def prepare_line_data(line):
+ first_image = line.variant.get_first_image()
+ return {
+ 'product': line.variant.product,
+ 'variant': line.variant.name,
+ 'quantity': line.quantity,
+ 'image': first_image,
+ 'line_total': line.get_total(discounts, taxes),
+ 'variant_url': line.variant.get_absolute_url()}
+
+ if cart.quantity == 0:
+ data = {'quantity': 0}
+ else:
+ data = {
+ 'quantity': cart.quantity,
+ '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/saleor/cart/checkout/views/discount.py b/saleor/cart/views/discount.py
similarity index 90%
rename from saleor/cart/checkout/views/discount.py
rename to saleor/cart/views/discount.py
index be6b78aec8..831f03d408 100644
--- a/saleor/cart/checkout/views/discount.py
+++ b/saleor/cart/views/discount.py
@@ -7,11 +7,11 @@ from django.template.response import TemplateResponse
from django.utils.translation import pgettext
from django.views.decorators.http import require_POST
-from ....cart.models import Cart
-from ....cart.utils import get_or_empty_db_cart
-from ....discount.models import Voucher
+from ...discount.models import Voucher
from ..forms import CartVoucherForm
-from ..utils import recalculate_cart_discount, remove_voucher_from_cart
+from ..models import Cart
+from ..utils import (
+ get_or_empty_db_cart, recalculate_cart_discount, remove_voucher_from_cart)
def add_voucher_form(view):
@@ -59,7 +59,7 @@ def validate_voucher(view):
'Checkout warning',
'This voucher has expired. Please review your checkout.')
messages.warning(request, msg)
- return redirect('cart:checkout-summary')
+ return redirect('checkout:summary')
return view(request, cart)
return func
diff --git a/saleor/cart/checkout/views/shipping.py b/saleor/cart/views/shipping.py
similarity index 93%
rename from saleor/cart/checkout/views/shipping.py
rename to saleor/cart/views/shipping.py
index 660119b26c..eeb2c44482 100644
--- a/saleor/cart/checkout/views/shipping.py
+++ b/saleor/cart/views/shipping.py
@@ -13,7 +13,7 @@ def anonymous_user_shipping_address_view(request, cart):
cart, request.POST or None, request.country))
if updated:
- return redirect('cart:checkout-shipping-method')
+ return redirect('checkout:shipping-method')
taxes = get_taxes_for_cart(cart, request.taxes)
ctx = get_cart_data_for_checkout(cart, request.discounts, taxes)
@@ -37,7 +37,7 @@ def user_shipping_address_view(request, cart):
cart, user_addresses, request.POST or None, request.country)
if updated:
- return redirect('cart:checkout-shipping-method')
+ return redirect('checkout:shipping-method')
taxes = get_taxes_for_cart(cart, request.taxes)
ctx = get_cart_data_for_checkout(cart, request.discounts, taxes)
diff --git a/saleor/cart/checkout/views/summary.py b/saleor/cart/views/summary.py
similarity index 93%
rename from saleor/cart/checkout/views/summary.py
rename to saleor/cart/views/summary.py
index 13d4d3126d..0e5385b912 100644
--- a/saleor/cart/checkout/views/summary.py
+++ b/saleor/cart/views/summary.py
@@ -3,10 +3,10 @@ from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext, pgettext_lazy
-from ....account.models import Address
-from ....core import analytics
-from ....core.exceptions import InsufficientStock
-from ....order.emails import send_order_confirmation
+from ...account.models import Address
+from ...core import analytics
+from ...core.exceptions import InsufficientStock
+from ...order.emails import send_order_confirmation
from ..forms import CartNoteForm
from ..utils import (
create_order, get_cart_data_for_checkout, get_taxes_for_cart,
@@ -26,12 +26,12 @@ def handle_order_placement(request, cart):
discounts=request.discounts,
taxes=get_taxes_for_cart(cart, request.taxes))
except InsufficientStock:
- return redirect('cart:index')
+ return redirect('checkout:index')
if not order:
msg = pgettext('Checkout warning', 'Please review your checkout.')
messages.warning(request, msg)
- return redirect('cart:checkout-summary')
+ return redirect('checkout:summary')
user = cart.user
cart.delete()
diff --git a/saleor/cart/checkout/views/validators.py b/saleor/cart/views/validators.py
similarity index 83%
rename from saleor/cart/checkout/views/validators.py
rename to saleor/cart/views/validators.py
index 19b4fe75d9..11fdccd5d3 100644
--- a/saleor/cart/checkout/views/validators.py
+++ b/saleor/cart/views/validators.py
@@ -3,7 +3,7 @@ from functools import wraps
from django.core.exceptions import ValidationError
from django.shortcuts import redirect
-from ....shipping.models import ShippingMethodCountry
+from ...shipping.models import ShippingMethodCountry
def validate_cart(view):
@@ -15,7 +15,7 @@ def validate_cart(view):
def func(request, cart):
if cart:
return view(request, cart)
- return redirect('cart:index')
+ return redirect('checkout:index')
return func
@@ -30,11 +30,11 @@ def validate_shipping_address(view):
@wraps(view)
def func(request, cart):
if cart.user_email is None or cart.shipping_address is None:
- return redirect('cart:checkout-shipping-address')
+ return redirect('checkout:shipping-address')
try:
cart.shipping_address.full_clean()
except ValidationError:
- return redirect('cart:checkout-shipping-address')
+ return redirect('checkout:shipping-address')
return view(request, cart)
return func
@@ -50,14 +50,14 @@ def validate_shipping_method(view):
@wraps(view)
def func(request, cart):
if cart.shipping_method is None:
- return redirect('cart:checkout-shipping-method')
+ return redirect('checkout:shipping-method')
country_code = cart.shipping_address.country.code
valid_methods = ShippingMethodCountry.objects.select_related(
'shipping_method').unique_for_country_code(country_code)
if cart.shipping_method not in valid_methods:
cart.shipping_method = None
cart.save()
- return redirect('cart:checkout-shipping-method')
+ return redirect('checkout:shipping-method')
return view(request, cart)
return func
@@ -72,6 +72,6 @@ def validate_is_shipping_required(view):
@wraps(view)
def func(request, cart):
if not cart.is_shipping_required():
- return redirect('cart:checkout-summary')
+ return redirect('checkout:summary')
return view(request, cart)
return func
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 8912a0c4ee..2d9c3d5896 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -10,7 +10,7 @@ from ..cart.utils import set_cart_cookie
from ..core.utils import serialize_decimal
from ..seo.schema.product import product_json_ld
from .filters import ProductCategoryFilter, ProductCollectionFilter
-from .models import Category, Collection
+from .models import Category
from .utils import (
collections_visible_to_user, get_product_images, get_product_list_context,
handle_cart_form, products_for_cart, products_with_details)
diff --git a/saleor/urls.py b/saleor/urls.py
index 52ecbbfb5c..37192dbfed 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -8,7 +8,8 @@ from django.views.i18n import JavaScriptCatalog, set_language
from graphene_django.views import GraphQLView
from .account.urls import urlpatterns as account_urls
-from .cart.urls import urlpatterns as cart_urls
+from .cart.urls import cart_urlpatterns as cart_urls
+from .cart.urls import checkout_urlpatterns as checkout_urls
from .core.sitemaps import sitemaps
from .core.urls import urlpatterns as core_urls
from .dashboard.urls import urlpatterns as dashboard_urls
@@ -34,6 +35,8 @@ non_translatable_urlpatterns = [
translatable_urlpatterns = [
url(r'^', include(core_urls)),
url(r'^cart/', include((cart_urls, 'cart'), namespace='cart')),
+ url(r'^checkout/',
+ include((checkout_urls, 'checkout'), namespace='checkout')),
url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
url(r'^order/', include((order_urls, 'order'), namespace='order')),
url(r'^page/', include((page_urls, 'page'), namespace='page')),
diff --git a/templates/base.html b/templates/base.html
index 9ab795e8aa..f82bdc590e 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -6,7 +6,7 @@
{% load placeholder %}
{% load translate_url from urls %}
-<html lang="{{ LANGUAGE_CODE }}" class="no-js" data-shipping-options-url="{% url 'cart:shipping-options' %}" data-cart-summary-url="{% url 'cart:cart-summary' %}">
+<html lang="{{ LANGUAGE_CODE }}" class="no-js" data-shipping-options-url="{% url 'cart:shipping-options' %}" data-cart-summary-url="{% url 'cart:summary' %}">
<head>
<title>{% block title %}{{ site.name }}{% endblock %}</title>
{% block meta %}
diff --git a/templates/cart/index.html b/templates/cart/index.html
index 0048679fe1..18f7ac6d08 100644
--- a/templates/cart/index.html
+++ b/templates/cart/index.html
@@ -77,7 +77,7 @@
</div>
<div class="row">
<div class="col-md-12">
- <a href="{% url "cart:checkout-login" %}" class="btn primary float-right cart__submit">
+ <a href="{% url "checkout:login" %}" class="btn primary float-right cart__submit">
{% trans "Checkout" context "Cart primary action" %}
</a>
</div>
diff --git a/templates/cart_dropdown.html b/templates/cart_dropdown.html
index 7ba65d11af..c966ea9dc7 100644
--- a/templates/cart_dropdown.html
+++ b/templates/cart_dropdown.html
@@ -54,7 +54,7 @@
<a href="{% url "cart:index" %}" class="btn secondary narrow float-md-right">{% trans "Go to cart" context "Cart dropdown secondary action" %}</a>
</div>
<div class="col-md-5">
- <a href="{% url "cart:checkout-login" %}" class="btn primary narrow float-md-right">{% trans "Checkout" context "Cart dropdown primary action" %}</a>
+ <a href="{% url "checkout:login" %}" class="btn primary narrow float-md-right">{% trans "Checkout" context "Cart dropdown primary action" %}</a>
</div>
</div>
{% else %}
diff --git a/templates/checkout/login.html b/templates/checkout/login.html
index 75bf833b6f..d148e8f6b6 100644
--- a/templates/checkout/login.html
+++ b/templates/checkout/login.html
@@ -14,7 +14,7 @@
data-src="{% static 'images/login-bg.png' %}"
data-srcset="{% static 'images/login-bg.png' %} 1x, {% static 'images/login-bg2x.png' %} 2x">
<p>
- <a href="{% url 'cart:checkout-index' %}" class="btn secondary narrow">
+ <a href="{% url 'checkout:index' %}" class="btn secondary narrow">
{% trans "Continue" context "Checkout login page new users action" %}
</a>
</p>
@@ -22,7 +22,7 @@
</div>
</div>
<div class="col-12 col-md-6 checkout__login__form">
- {% url "cart:checkout-index" as checkout_url %}
+ {% url "checkout:index" as checkout_url %}
<h3>{% trans "Existing customer? Log in." context "Checkout login form title" %}</h3>
{% include "account/partials/login_form.html" with REDIRECT_FIELD_VALUE=checkout_url %}
</div>
diff --git a/templates/checkout/shipping_method.html b/templates/checkout/shipping_method.html
index 96363ecf47..c2a10ad78c 100644
--- a/templates/checkout/shipping_method.html
+++ b/templates/checkout/shipping_method.html
@@ -6,7 +6,7 @@
{% block forms %}
<h3>{% trans "Shipping address" context "Checkout shipping address title" %}</h3>
{% format_address cart.shipping_address %}
- <p><a href="{% url 'cart:checkout-shipping-address' %}">{% trans "Select other address" %}</a></p>
+ <p><a href="{% url 'checkout:shipping-address' %}">{% trans "Select other address" %}</a></p>
<hr>
<form method="post" novalidate>
{% csrf_token %}
diff --git a/templates/checkout/snippets/voucher_form.html b/templates/checkout/snippets/voucher_form.html
index 315240d3e4..5bbf90b69e 100644
--- a/templates/checkout/snippets/voucher_form.html
+++ b/templates/checkout/snippets/voucher_form.html
@@ -4,7 +4,7 @@
{% if form %}
{% if cart.discount_amount %}
- <form action="{% url "cart:checkout-remove-voucher" %}?next={{ request.path }}"
+ <form action="{% url "checkout:remove-voucher" %}?next={{ request.path }}"
method="post"
class="float-left input-btn">
{% csrf_token %}
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 33741bc2f8..a1f432513b 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -15,7 +15,7 @@ from saleor.cart.context_processors import cart_counter
from saleor.cart.models import Cart
from saleor.cart.utils import (
add_variant_to_cart, change_cart_user, find_open_cart_for_user)
-from saleor.cart.views import update
+from saleor.cart.views import update_cart_line
from saleor.core.exceptions import InsufficientStock
from saleor.core.utils.taxes import ZERO_TAXED_MONEY
from saleor.discount.models import Sale
@@ -340,30 +340,26 @@ def test_check_product_availability_and_warn(
assert len(cart) == 0
-def test_add_to_cart_form(monkeypatch):
- cart_lines = []
- cart = Mock(
- get_line=Mock(return_value=Mock(quantity=1)))
- monkeypatch.setattr(
- 'saleor.cart.forms.add_variant_to_cart',
- lambda c, variant, quantity: cart_lines.append(variant))
+def test_add_to_cart_form(cart, product):
+ variant = product.variants.get()
+ add_variant_to_cart(cart, variant, 3)
data = {'quantity': 1}
- form = forms.AddToCartForm(data=data, cart=cart, product=Mock())
+ form = forms.AddToCartForm(data=data, cart=cart, product=product)
- product_variant = Mock(check_quantity=Mock(return_value=None))
- form.get_variant = Mock(return_value=product_variant)
+ form.get_variant = Mock(return_value=variant)
assert form.is_valid()
form.save()
- assert cart_lines == [product_variant]
+ assert cart.lines.count() == 1
+ assert cart.lines.filter(variant=variant).exists()
with pytest.raises(NotImplementedError):
data = {'quantity': 1}
- form = forms.AddToCartForm(data=data, cart=cart, product=Mock())
+ form = forms.AddToCartForm(data=data, cart=cart, product=product)
form.is_valid()
data = {}
- form = forms.AddToCartForm(data=data, cart=cart, product=Mock())
+ form = forms.AddToCartForm(data=data, cart=cart, product=product)
assert not form.is_valid()
@@ -505,7 +501,7 @@ def test_cart_page_with_openexchagerates(
def test_cart_summary_page(settings, client, request_cart_with_item, vatlayer):
settings.DEFAULT_COUNTRY = 'PL'
- response = client.get(reverse('cart:cart-summary'))
+ response = client.get(reverse('cart:summary'))
assert response.status_code == 200
content = response.context
assert content['quantity'] == request_cart_with_item.quantity
@@ -519,7 +515,7 @@ def test_cart_summary_page(settings, client, request_cart_with_item, vatlayer):
def test_cart_summary_page_empty_cart(client, request_cart):
- response = client.get(reverse('cart:cart-summary'))
+ response = client.get(reverse('cart:summary'))
assert response.status_code == 200
data = response.context
assert data['quantity'] == 0
@@ -595,7 +591,7 @@ def test_update_view_must_be_ajax(customer_user, rf):
request = rf.post(reverse('home'))
request.user = customer_user
request.discounts = None
- result = update(request, 1)
+ result = update_cart_line(request, 1)
assert result.status_code == 302
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index c0724beb49..68c4a7e6be 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -8,14 +8,13 @@ from freezegun import freeze_time
from prices import Money, TaxedMoney
from saleor.account.models import Address
-from saleor.cart.checkout import views
-from saleor.cart.checkout.forms import CartVoucherForm
-from saleor.cart.checkout.utils import (
- change_billing_address_in_cart, change_shipping_address_in_cart,
- create_order, get_cart_data_for_checkout, get_taxes_for_cart,
- get_voucher_discount_for_cart, get_voucher_for_cart,
+from saleor.cart import views
+from saleor.cart.forms import CartVoucherForm
+from saleor.cart.utils import (
+ add_variant_to_cart, change_billing_address_in_cart,
+ change_shipping_address_in_cart, create_order, get_cart_data_for_checkout,
+ get_taxes_for_cart, get_voucher_discount_for_cart, get_voucher_for_cart,
recalculate_cart_discount, remove_voucher_from_cart)
-from saleor.cart.utils import add_variant_to_cart
from saleor.core.exceptions import InsufficientStock
from saleor.core.utils.taxes import (
ZERO_MONEY, ZERO_TAXED_MONEY, get_taxes_for_country)
@@ -26,10 +25,10 @@ from .utils import compare_taxes, get_redirect_location
@pytest.mark.parametrize('cart_length, is_shipping_required, redirect_url', [
- (0, True, reverse('cart:index')),
- (0, False, reverse('cart:index')),
- (1, True, reverse('cart:checkout-shipping-address')),
- (1, False, reverse('cart:checkout-summary'))])
+ (0, True, reverse('checkout:index')),
+ (0, False, reverse('checkout:index')),
+ (1, True, reverse('checkout:shipping-address')),
+ (1, False, reverse('checkout:summary'))])
def test_view_checkout_index(
monkeypatch, rf, cart_length, is_shipping_required, redirect_url):
cart = Mock(
@@ -37,10 +36,10 @@ def test_view_checkout_index(
is_shipping_required=Mock(return_value=is_shipping_required))
monkeypatch.setattr(
'saleor.cart.utils.get_cart_from_request', lambda req, qs: cart)
- url = reverse('cart:checkout-index')
+ url = reverse('checkout:index')
request = rf.get(url, follow=True)
- response = views.index_view(request)
+ response = views.checkout_index(request)
assert response.url == redirect_url
@@ -49,16 +48,16 @@ def test_view_checkout_index_authorized_user(
authorized_client, customer_user, request_cart_with_item):
request_cart_with_item.user = customer_user
request_cart_with_item.save()
- url = reverse('cart:checkout-index')
+ url = reverse('checkout:index')
response = authorized_client.get(url, follow=True)
- redirect_url = reverse('cart:checkout-shipping-address')
+ redirect_url = reverse('checkout:shipping-address')
assert response.request['PATH_INFO'] == redirect_url
def test_view_checkout_shipping_address(client, request_cart_with_item):
- url = reverse('cart:checkout-shipping-address')
+ url = reverse('checkout:shipping-address')
data = {
'user_email': '[email protected]',
'first_name': 'John',
@@ -78,7 +77,7 @@ def test_view_checkout_shipping_address(client, request_cart_with_item):
response = client.post(url, data, follow=True)
- redirect_url = reverse('cart:checkout-shipping-method')
+ redirect_url = reverse('checkout:shipping-method')
assert response.request['PATH_INFO'] == redirect_url
assert request_cart_with_item.user_email == '[email protected]'
@@ -87,12 +86,12 @@ def test_view_checkout_shipping_address_authorized_user(
authorized_client, customer_user, request_cart_with_item):
request_cart_with_item.user = customer_user
request_cart_with_item.save()
- url = reverse('cart:checkout-shipping-address')
+ url = reverse('checkout:shipping-address')
data = {'address': customer_user.default_billing_address.pk}
response = authorized_client.post(url, data, follow=True)
- redirect_url = reverse('cart:checkout-shipping-method')
+ redirect_url = reverse('checkout:shipping-method')
assert response.request['PATH_INFO'] == redirect_url
assert request_cart_with_item.user_email == customer_user.email
@@ -101,12 +100,12 @@ def test_view_checkout_shipping_address_without_shipping(
request_cart, product_without_shipping, client):
variant = product_without_shipping.variants.get()
add_variant_to_cart(request_cart, variant)
- url = reverse('cart:checkout-shipping-address')
+ url = reverse('checkout:shipping-address')
response = client.get(url)
assert response.status_code == 302
- assert get_redirect_location(response) == reverse('cart:checkout-summary')
+ assert get_redirect_location(response) == reverse('checkout:summary')
assert not request_cart.user_email
@@ -115,7 +114,7 @@ def test_view_checkout_shipping_method(
request_cart_with_item.shipping_address = address
request_cart_with_item.user_email = '[email protected]'
request_cart_with_item.save()
- url = reverse('cart:checkout-shipping-method')
+ url = reverse('checkout:shipping-method')
data = {'shipping_method': shipping_method.price_per_country.first().pk}
response = client.get(url)
@@ -124,7 +123,7 @@ def test_view_checkout_shipping_method(
response = client.post(url, data, follow=True)
- redirect_url = reverse('cart:checkout-summary')
+ redirect_url = reverse('checkout:summary')
assert response.request['PATH_INFO'] == redirect_url
@@ -135,7 +134,7 @@ def test_view_checkout_shipping_method_authorized_user(
request_cart_with_item.user_email = customer_user.email
request_cart_with_item.shipping_address = address
request_cart_with_item.save()
- url = reverse('cart:checkout-shipping-method')
+ url = reverse('checkout:shipping-method')
data = {'shipping_method': shipping_method.price_per_country.first().pk}
response = authorized_client.get(url)
@@ -144,7 +143,7 @@ def test_view_checkout_shipping_method_authorized_user(
response = authorized_client.post(url, data, follow=True)
- redirect_url = reverse('cart:checkout-summary')
+ redirect_url = reverse('checkout:summary')
assert response.request['PATH_INFO'] == redirect_url
@@ -152,26 +151,26 @@ def test_view_checkout_shipping_method_without_shipping(
request_cart, product_without_shipping, client):
variant = product_without_shipping.variants.get()
add_variant_to_cart(request_cart, variant)
- url = reverse('cart:checkout-shipping-method')
+ url = reverse('checkout:shipping-method')
response = client.get(url)
assert response.status_code == 302
- assert get_redirect_location(response) == reverse('cart:checkout-summary')
+ assert get_redirect_location(response) == reverse('checkout:summary')
def test_view_checkout_shipping_method_without_address(
request_cart_with_item, client):
- url = reverse('cart:checkout-shipping-method')
+ url = reverse('checkout:shipping-method')
response = client.get(url)
assert response.status_code == 302
- redirect_url = reverse('cart:checkout-shipping-address')
+ redirect_url = reverse('checkout:shipping-address')
assert get_redirect_location(response) == redirect_url
-@patch('saleor.cart.checkout.views.summary.send_order_confirmation')
+@patch('saleor.cart.views.summary.send_order_confirmation')
def test_view_checkout_summary(
mock_send_confirmation, client, shipping_method, address,
request_cart_with_item):
@@ -180,7 +179,7 @@ def test_view_checkout_summary(
request_cart_with_item.shipping_method = (
shipping_method.price_per_country.first())
request_cart_with_item.save()
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
data = {'address': 'shipping_address'}
response = client.get(url)
@@ -196,7 +195,7 @@ def test_view_checkout_summary(
mock_send_confirmation.delay.assert_called_once_with(order.pk)
-@patch('saleor.cart.checkout.views.summary.send_order_confirmation')
+@patch('saleor.cart.views.summary.send_order_confirmation')
def test_view_checkout_summary_authorized_user(
mock_send_confirmation, authorized_client, customer_user,
shipping_method, address, request_cart_with_item):
@@ -206,7 +205,7 @@ def test_view_checkout_summary_authorized_user(
request_cart_with_item.shipping_method = (
shipping_method.price_per_country.first())
request_cart_with_item.save()
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
data = {'address': 'shipping_address'}
response = authorized_client.get(url)
@@ -222,7 +221,7 @@ def test_view_checkout_summary_authorized_user(
mock_send_confirmation.delay.assert_called_once_with(order.pk)
-@patch('saleor.cart.checkout.views.summary.send_order_confirmation')
+@patch('saleor.cart.views.summary.send_order_confirmation')
def test_view_checkout_summary_save_language(
mock_send_confirmation, authorized_client, customer_user,
shipping_method, address, request_cart_with_item, settings):
@@ -240,7 +239,7 @@ def test_view_checkout_summary_save_language(
request_cart_with_item.shipping_method = (
shipping_method.price_per_country.first())
request_cart_with_item.save()
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
data = {'address': 'shipping_address'}
response = authorized_client.get(url, HTTP_ACCEPT_LANGUAGE=user_language)
@@ -259,23 +258,23 @@ def test_view_checkout_summary_save_language(
def test_view_checkout_summary_without_address(request_cart_with_item, client):
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
response = client.get(url)
assert response.status_code == 302
- redirect_url = reverse('cart:checkout-shipping-method')
+ redirect_url = reverse('checkout:shipping-method')
assert get_redirect_location(response) == redirect_url
def test_view_checkout_summary_without_shipping_method(
request_cart_with_item, client):
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
response = client.get(url)
assert response.status_code == 302
- redirect_url = reverse('cart:checkout-shipping-method')
+ redirect_url = reverse('checkout:shipping-method')
assert get_redirect_location(response) == redirect_url
@@ -290,7 +289,7 @@ def test_view_checkout_summary_with_invalid_voucher(
shipping_method.price_per_country.first())
request_cart_with_item.save()
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
voucher_url = '{url}?next={url}'.format(url=url)
data = {'discount-voucher': voucher.code}
@@ -323,7 +322,7 @@ def test_view_checkout_summary_with_invalid_voucher_code(
shipping_method.price_per_country.first())
request_cart_with_item.save()
- url = reverse('cart:checkout-summary')
+ url = reverse('checkout:summary')
voucher_url = '{url}?next={url}'.format(url=url)
data = {'discount-voucher': 'invalid-code'}
@@ -341,7 +340,7 @@ def test_view_checkout_summary_remove_voucher(
shipping_method.price_per_country.first())
request_cart_with_item.save()
- remove_voucher_url = reverse('cart:checkout-summary')
+ remove_voucher_url = reverse('checkout:summary')
voucher_url = '{url}?next={url}'.format(url=remove_voucher_url)
data = {'discount-voucher': voucher.code}
@@ -350,7 +349,7 @@ def test_view_checkout_summary_remove_voucher(
assert response.context['cart'].voucher_code == voucher.code
- url = reverse('cart:checkout-remove-voucher')
+ url = reverse('checkout:remove-voucher')
response = client.post(url, follow=True, HTTP_REFERER=remove_voucher_url)
@@ -488,7 +487,7 @@ def test_get_discount_for_cart_shipping_voucher_not_applicable(
def test_get_discount_for_cart_product_voucher_not_applicable(
settings, monkeypatch):
monkeypatch.setattr(
- 'saleor.cart.checkout.utils.get_product_variants_and_prices',
+ 'saleor.cart.utils.get_product_variants_and_prices',
lambda cart, product: [])
voucher = Voucher(
code='unique', type=VoucherType.PRODUCT,
@@ -504,7 +503,7 @@ def test_get_discount_for_cart_product_voucher_not_applicable(
def test_get_discount_for_cart_category_voucher_not_applicable(
settings, monkeypatch):
monkeypatch.setattr(
- 'saleor.cart.checkout.utils.get_category_variants_and_prices',
+ 'saleor.cart.utils.get_category_variants_and_prices',
lambda cart, product: [])
voucher = Voucher(
code='unique', type=VoucherType.CATEGORY,
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
index 9c91cf83b7..05b5f441eb 100644
--- a/tests/test_discounts.py
+++ b/tests/test_discounts.py
@@ -4,7 +4,7 @@ from unittest.mock import Mock
import pytest
from prices import Money, TaxedMoney
-from saleor.cart.checkout.utils import get_voucher_discount_for_cart
+from saleor.cart.utils import get_voucher_discount_for_cart
from saleor.discount import (
DiscountValueType, VoucherApplyToProduct, VoucherType)
from saleor.discount.models import NotApplicable, Sale, Voucher
@@ -97,7 +97,7 @@ def test_products_voucher_checkout_discount_not(
settings, monkeypatch, prices, discount_value, discount_type, apply_to,
expected_value):
monkeypatch.setattr(
- 'saleor.cart.checkout.utils.get_product_variants_and_prices',
+ 'saleor.cart.utils.get_product_variants_and_prices',
lambda cart, product: (
(None, TaxedMoney(
net=Money(price, 'USD'), gross=Money(price, 'USD')))
diff --git a/tests/test_order.py b/tests/test_order.py
index efafc2e3ec..95202cd962 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -9,7 +9,7 @@ from prices import Money, TaxedMoney
from tests.utils import get_redirect_location
from saleor.account.models import User
-from saleor.cart.checkout.utils import create_order
+from saleor.cart.utils import create_order
from saleor.core.utils.taxes import (
DEFAULT_TAX_RATE_NAME, get_tax_rate_by_name, get_taxes_for_country)
from saleor.order import FulfillmentStatus, OrderStatus, models
diff --git a/tests/test_registration.py b/tests/test_registration.py
index b33b43dfcd..917e93437e 100644
--- a/tests/test_registration.py
+++ b/tests/test_registration.py
@@ -112,10 +112,10 @@ def test_signup_view_redirect(client, customer_user):
url = reverse('account:signup')
data = {
'email': '[email protected]', 'password': 'password',
- 'next': reverse('cart:index')}
+ 'next': reverse('checkout:index')}
response = client.post(url, data)
redirect_location = get_redirect_location(response)
- assert redirect_location == reverse('cart:index')
+ assert redirect_location == reverse('checkout:index')
def test_signup_view_fail(client, db, customer_user):