Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve checkout code
Patryk Zawadzki18a01a881539
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.pyindex f08c8bf02d..1084c0790b 100644--- a/saleor/checkout/core.py+++ b/saleor/checkout/core.py@@ -1,3 +1,4 @@+"""Checkout session state management."""from __future__ import unicode_literalsfrom functools import wraps@@ -25,6 +26,10 @@ STORAGE_SESSION_KEY = 'checkout_storage'class Checkout(object):"""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 incompatiblecheckout structures.@@ -46,7 +51,7 @@ class Checkout(object):@classmethoddef from_storage(cls, storage_data, cart, user, tracking_code):- """Restores a previously serialized checkout session.+ """Restore a previously serialized checkout session.`storage_data` is the value previously returned by`Checkout.for_storage()`.@@ -62,13 +67,14 @@ class Checkout(object):return checkoutdef for_storage(self):- """Serializes a checkout session to allow persistence.+ """Serialize a checkout session to allow persistence.The session can later be restored using `Checkout.from_storage()`."""return self.storagedef clear_storage(self):+ """Discard the entire state."""self.storage = Noneself.modified = True@@ -85,10 +91,19 @@ class Checkout(object):@propertydef is_shipping_required(self):+ """Return `True` if this checkout session needs shipping."""return self.cart.is_shipping_required()@propertydef deliveries(self):+ """Return the cart split into delivery groups.++ Generates tuples consisting of a partition, its shipping cost and its+ total cost.++ Each partition is a list of tuples containing the cart line, its unit+ price and the line total.+ """for partition in self.cart.partition():if self.shipping_method and partition.is_shipping_required():shipping_cost = self.shipping_method.get_total()@@ -107,6 +122,7 @@ class Checkout(object):@propertydef shipping_address(self):+ """Return a shipping address if any."""if self._shipping_address is None:address = self._get_address_from_storage('shipping_address')if address is None and self.user.is_authenticated:@@ -124,6 +140,7 @@ class Checkout(object):@propertydef shipping_method(self):+ """Return a shipping method if any."""if self._shipping_method is None:shipping_address = self.shipping_addressif shipping_address is None:@@ -152,6 +169,7 @@ class Checkout(object):@propertydef email(self):+ """Return the customer email if any."""return self.storage.get('email')@email.setter@@ -161,6 +179,7 @@ class Checkout(object):@propertydef billing_address(self):+ """Return the billing addres if any."""address = self._get_address_from_storage('billing_address')if address is not None:return address@@ -179,6 +198,7 @@ class Checkout(object):@propertydef discount(self):+ """Return a discount if any."""value = self.storage.get('discount_value')currency = self.storage.get('discount_currency')name = self.storage.get('discount_name')@@ -208,6 +228,7 @@ class Checkout(object):@propertydef voucher_code(self):+ """Return a discount voucher code if any."""return self.storage.get('voucher_code')@voucher_code.setter@@ -223,6 +244,7 @@ class Checkout(object):@propertydef is_shipping_same_as_billing(self):+ """Return `True` if shipping and billing addresses are identical."""return Address.objects.are_identical(self.shipping_address, self.billing_address)@@ -233,20 +255,26 @@ class Checkout(object):self.user, address, shipping=is_shipping,billing=is_billing)- def _get_address_copy(self, address):- address.user = None- address.pk = None- address.save()- return address-def _save_order_billing_address(self):- return self._get_address_copy(self.billing_address)+ return Address.objects.copy(self.billing_address)def _save_order_shipping_address(self):- return self._get_address_copy(self.shipping_address)+ return Address.objects.copy(self.shipping_address)@transaction.atomicdef 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 languagevoucher = self._get_voucher(vouchers=Voucher.objects.active().select_for_update())if self.voucher_code is not None and voucher is None:@@ -315,6 +343,11 @@ class Checkout(object):return Nonedef recalculate_discount(self):+ """Recalculate `self.discount` based on the voucher.++ Will clear both voucher and discount if the discount is no longer+ applicable.+ """voucher = self._get_voucher()if voucher is not None:try:@@ -327,6 +360,7 @@ class Checkout(object):del self.voucher_codedef get_subtotal(self):+ """Calculate order total without shipping."""zero = Price(0, currency=settings.DEFAULT_CURRENCY)cost_iterator = (total - shipping_cost@@ -335,6 +369,7 @@ class Checkout(object):return totaldef get_total(self):+ """Calculate order total with shipping."""zero = Price(0, currency=settings.DEFAULT_CURRENCY)cost_iterator = (total@@ -343,6 +378,7 @@ class Checkout(object):return total if self.discount is None else self.discount.apply(total)def get_total_shipping(self):+ """Calculate shipping total."""zero = Price(0, currency=settings.DEFAULT_CURRENCY)cost_iterator = (shipping_cost@@ -352,6 +388,13 @@ class Checkout(object):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, checkout, cart)`.+ """+ # 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):diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex 9a7491b3d9..4d11583673 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -1,3 +1,4 @@+"""Checkout-related forms."""from django import formsfrom django.utils.safestring import mark_safefrom django.utils.translation import pgettext_lazy@@ -7,17 +8,18 @@ from ..shipping.models import ShippingMethodCountryclass CheckoutAddressField(forms.ChoiceField):+ """Like a choice field but uses a radio group instead of a dropdown."""widget = forms.RadioSelect()class ShippingAddressesForm(forms.Form):+ """Shipping address form."""NEW_ADDRESS = 'new_address'- CHOICES = (+ CHOICES = [(NEW_ADDRESS, pgettext_lazy(- 'Shipping addresses form choice', 'Enter a new address')),- )+ 'Shipping addresses form choice', 'Enter a new address'))]address = CheckoutAddressField(label=pgettext_lazy('Shipping addresses form field label', 'Address'),@@ -29,44 +31,56 @@ class ShippingAddressesForm(forms.Form):address_field = self.fields['address']address_choices = [(address.id, str(address)) for address in additional_addresses]- address_field.choices = list(self.CHOICES) + address_choices+ address_field.choices = self.CHOICES + address_choicesclass BillingAddressesForm(ShippingAddressesForm):+ """Billing address form."""NEW_ADDRESS = 'new_address'SHIPPING_ADDRESS = 'shipping_address'- CHOICES = (+ CHOICES = [(NEW_ADDRESS, pgettext_lazy('Billing addresses form choice', 'Enter a new address')),(SHIPPING_ADDRESS, pgettext_lazy(- 'Billing addresses form choice', 'Same as shipping'))- )+ 'Billing addresses form choice', 'Same as shipping'))]address = CheckoutAddressField(choices=CHOICES, initial=SHIPPING_ADDRESS)class BillingWithoutShippingAddressForm(ShippingAddressesForm):+ """Billing address form when shipping is not required.- pass+ Same as the default shipping address as in this came "billing same as+ shipping" option does not make sense.+ """+# FIXME: why is this called a country choice field?class ShippingCountryChoiceField(forms.ModelChoiceField):+ """Shipping method choice field.++ Uses a radio group instead of a dropdown and includes estimated shipping+ prices.+ """widget = forms.RadioSelect()def label_from_instance(self, obj):+ """Return a friendly label for the shipping method."""price_html = format_price(obj.price.gross, obj.price.currency)label = mark_safe('%s %s' % (obj.shipping_method, price_html))return labelclass ShippingMethodForm(forms.Form):+ """Shipping method form."""method = ShippingCountryChoiceField(queryset=ShippingMethodCountry.objects.select_related('shipping_method').order_by('price').all(),- label=pgettext_lazy('Shipping method form field label', 'Shipping method'),+ label=pgettext_lazy(+ 'Shipping method form field label', 'Shipping method'),required=True)def __init__(self, country_code, *args, **kwargs):@@ -74,21 +88,26 @@ class ShippingMethodForm(forms.Form):method_field = self.fields['method']if country_code:queryset = method_field.queryset- method_field.queryset = queryset.unique_for_country_code(country_code)+ method_field.queryset = queryset.unique_for_country_code(+ country_code)if self.initial.get('method') is None:method_field.initial = method_field.queryset.first()method_field.empty_label = Noneclass AnonymousUserShippingForm(forms.Form):+ """Additional shipping information form for users who are not logged in."""email = forms.EmailField(- required=True, widget=forms.EmailInput(attrs={'autocomplete': 'shipping email'}),+ required=True, widget=forms.EmailInput(+ attrs={'autocomplete': 'shipping email'}),label=pgettext_lazy('Shipping form field label', 'Email'))class AnonymousUserBillingForm(forms.Form):+ """Additional billing information form for users who are not logged in."""email = forms.EmailField(- required=True, widget=forms.EmailInput(attrs={'autocomplete': 'billing email'}),+ required=True, widget=forms.EmailInput(+ attrs={'autocomplete': 'billing email'}),label=pgettext_lazy('Billing form field label', 'Email'))diff --git a/saleor/checkout/urls.py b/saleor/checkout/urls.pyindex 87af3473f3..a4c4ba92dd 100644--- a/saleor/checkout/urls.py+++ b/saleor/checkout/urls.py@@ -12,5 +12,4 @@ urlpatterns = [url(r'^summary/', views.summary_view, name='summary'),url(r'^remove_voucher/', views.discount.remove_voucher_view,name='remove-voucher'),- url(r'^login/', views.login, name='login'),-]+ url(r'^login/', views.login, name='login')]diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex 7dedf00d14..68c059af72 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -19,6 +19,7 @@ from ...registration.forms import LoginForm@validate_cart@validate_is_shipping_requireddef index_view(request, checkout):+ """Redirect to the initial step of checkout."""return redirect('checkout:shipping-address')@@ -28,6 +29,7 @@ def index_view(request, checkout):@validate_is_shipping_required@add_voucher_formdef shipping_address_view(request, checkout):+ """Display the correct shipping address step."""if request.user.is_authenticated:return user_shipping_address_view(request, checkout)return anonymous_user_shipping_address_view(request, checkout)@@ -40,14 +42,19 @@ def shipping_address_view(request, checkout):@validate_shipping_address@add_voucher_formdef shipping_method_view(request, checkout):+ """Display the shipping method selection step."""country_code = checkout.shipping_address.country.codeshipping_method_form = ShippingMethodForm(- country_code, request.POST or None, initial={'method': checkout.shipping_method})+ country_code, request.POST or None,+ initial={'method': checkout.shipping_method})if shipping_method_form.is_valid():checkout.shipping_method = shipping_method_form.cleaned_data['method']return redirect('checkout:summary')- return TemplateResponse(request, 'checkout/shipping_method.html', context={- 'shipping_method_form': shipping_method_form, 'checkout': checkout})+ return TemplateResponse(+ request, 'checkout/shipping_method.html',+ context={+ 'shipping_method_form': shipping_method_form,+ 'checkout': checkout})@load_checkout@@ -55,6 +62,7 @@ def shipping_method_view(request, checkout):@validate_cart@add_voucher_formdef summary_view(request, checkout):+ """Display the correct order summary."""if checkout.is_shipping_required:view = validate_shipping_address(summary_with_shipping_view)view = validate_shipping_method(view)@@ -68,12 +76,8 @@ def summary_view(request, checkout):@load_checkout@validate_cartdef login(request, checkout):- """- Allows user to choose if he wants to login before checkout or continue- as an anonymous user- """+ """Allow the user to log in prior to checkout."""if request.user.is_authenticated:return redirect('checkout:index')form = LoginForm()- ctx = {'form': form}- return TemplateResponse(request, 'checkout/login.html', ctx)+ return TemplateResponse(request, 'checkout/login.html', {'form': form})diff --git a/saleor/checkout/views/discount.py b/saleor/checkout/views/discount.pyindex 960f906cf6..816f60f264 100644--- a/saleor/checkout/views/discount.py+++ b/saleor/checkout/views/discount.py@@ -12,6 +12,7 @@ from ...discount.models import Voucherdef add_voucher_form(view):+ """Decorate a view injecting a voucher form and handling its submission."""@wraps(view)def func(request, checkout):prefix = 'discount'@@ -41,6 +42,11 @@ def add_voucher_form(view):def validate_voucher(view):+ """Decorate a view making it check whether a discount voucher is valid.++ If the voucher is invalid it will be removed and the user will be+ redirected to the checkout summary view.+ """@wraps(view)def func(request, checkout, cart):if checkout.voucher_code:@@ -61,6 +67,7 @@ def validate_voucher(view):@require_POST@load_checkoutdef remove_voucher_view(request, checkout, cart):+ """Clear the discount and remove the voucher."""next_url = request.GET.get('next', request.META['HTTP_REFERER'])del checkout.discountdel checkout.voucher_codediff --git a/saleor/checkout/views/shipping.py b/saleor/checkout/views/shipping.pyindex fbbde11c2b..13d8dc6441 100644--- a/saleor/checkout/views/shipping.py+++ b/saleor/checkout/views/shipping.py@@ -7,7 +7,7 @@ from ...userprofile.models import Addressdef anonymous_user_shipping_address_view(request, checkout):-+ """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,autocomplete_type='shipping',@@ -28,6 +28,11 @@ def anonymous_user_shipping_address_view(request, checkout):def user_shipping_address_view(request, 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 Noneadditional_addresses = request.user.addresses.all()checkout.email = request.user.email@@ -54,7 +59,8 @@ def user_shipping_address_view(request, checkout):data, additional_addresses=additional_addresses)if addresses_form.is_valid() and not preview:- if addresses_form.cleaned_data['address'] != ShippingAddressesForm.NEW_ADDRESS:+ if (addresses_form.cleaned_data['address'] !=+ ShippingAddressesForm.NEW_ADDRESS):address_id = addresses_form.cleaned_data['address']checkout.shipping_address = Address.objects.get(id=address_id)return redirect('checkout:shipping-method')@@ -64,4 +70,5 @@ def user_shipping_address_view(request, checkout):return TemplateResponse(request, 'checkout/shipping_address.html', context={'address_form': address_form, 'user_form': addresses_form,- 'checkout': checkout, 'additional_addresses': additional_addresses})+ 'checkout': checkout,+ 'additional_addresses': additional_addresses})diff --git a/saleor/checkout/views/summary.py b/saleor/checkout/views/summary.pyindex ea274aded2..e985a1fb85 100644--- a/saleor/checkout/views/summary.py+++ b/saleor/checkout/views/summary.py@@ -11,7 +11,9 @@ from ...userprofile.models import Addressdef create_order(checkout):- """Finalizes a checkout session.+ """Finalize a checkout session and create an order.++ This is a helper function.`checkout` is a `saleor.checkout.core.Checkout` instance."""@@ -26,14 +28,20 @@ def create_order(checkout):def handle_order_placement(request, checkout):- order, success_redirect = create_order(checkout)+ """Try to create an order and redirect the user as necessary.++ This is a helper function.+ """+ order, redirect = create_order(checkout)if not order:msg = pgettext('Checkout warning', 'Please review your checkout.')messages.warning(request, msg)- return success_redirect+ return redirect-def get_billing_forms_with_shipping(data, addresses, billing_address, shipping_address):+def get_billing_forms_with_shipping(+ data, addresses, billing_address, shipping_address):+ """Get billing form based on a the current billing and shipping data."""if Address.objects.are_identical(billing_address, shipping_address):address_form, preview = get_address_form(data, country_code=shipping_address.country.code,@@ -73,6 +81,10 @@ def get_billing_forms_with_shipping(data, addresses, billing_address, shipping_adef summary_with_shipping_view(request, checkout):+ """Display order summary with billing forms for a logged in user.++ Will create an order if all data is valid.+ """if request.user.is_authenticated:additional_addresses = request.user.addresses.all()else:@@ -87,10 +99,15 @@ def summary_with_shipping_view(request, checkout):return TemplateResponse(request, 'checkout/summary.html', context={'addresses_form': addresses_form, 'address_form': address_form,- 'checkout': checkout, 'additional_addresses': additional_addresses})+ 'checkout': checkout,+ 'additional_addresses': additional_addresses})def anonymous_summary_without_shipping(request, checkout):+ """Display order summary with billing forms for an unauthorized user.++ Will create an order if all data is valid.+ """user_form = AnonymousUserBillingForm(request.POST or None, initial={'email': checkout.email})billing_address = checkout.billing_address@@ -113,6 +130,10 @@ def anonymous_summary_without_shipping(request, checkout):def summary_without_shipping(request, checkout):+ """Display order summary for cases where shipping is not required.++ Will create an order if all data is valid.+ """billing_address = checkout.billing_addressuser_addresses = request.user.addresses.all()if billing_address and billing_address.id:@@ -127,7 +148,8 @@ def summary_without_shipping(request, checkout):elif billing_address:address_form, preview = get_address_form(request.POST or None, autocomplete_type='billing',- instance=billing_address, country_code=billing_address.country.code)+ instance=billing_address,+ country_code=billing_address.country.code)addresses_form = BillingWithoutShippingAddressForm(request.POST or None, additional_addresses=user_addresses)else:diff --git a/saleor/checkout/views/validators.py b/saleor/checkout/views/validators.pyindex b6fb6d931d..95fa3020e3 100644--- a/saleor/checkout/views/validators.py+++ b/saleor/checkout/views/validators.py@@ -5,6 +5,15 @@ 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, checkout, cart)` to+ `func(request, checkout)`.++ If the cart is empty redirects to the cart details.+ """@wraps(view)def func(request, checkout, cart):if cart:@@ -15,6 +24,13 @@ def validate_cart(view):def validate_shipping_address(view):+ """Decorate a view making it require a valid shipping address.++ Expects to be decorated with `@validate_cart`.++ If either the shipping address or customer email is empty redirects to the+ shipping address step.+ """@wraps(view)def func(request, checkout):if checkout.email is None or checkout.shipping_address is None:@@ -28,6 +44,12 @@ def validate_shipping_address(view):def validate_shipping_method(view):+ """Decorate a view making it require a shipping method.++ Expects to be decorated with `@validate_cart`.++ If the method is missing redirects to the shipping method step.+ """@wraps(view)def func(request, checkout):if checkout.shipping_method is None:@@ -37,6 +59,12 @@ def validate_shipping_method(view):def validate_is_shipping_required(view):+ """Decorate a view making it check if checkout needs shipping.++ Expects to be decorated with `@validate_cart`.++ If shipping is not needed redirects to the summary step.+ """@wraps(view)def func(request, checkout):if not checkout.is_shipping_required:diff --git a/saleor/userprofile/models.py b/saleor/userprofile/models.pyindex c073e1ab78..825dbbc3e3 100644--- a/saleor/userprofile/models.py+++ b/saleor/userprofile/models.py@@ -14,17 +14,28 @@ from ..search import indexclass AddressManager(models.Manager):def as_data(self, address):+ """Return the address as a dict suitable for passing as kwargs.++ Result does not contain the primary key or an associated user.+ """data = model_to_dict(address, exclude=['id', 'user'])if isinstance(data['country'], Country):data['country'] = data['country'].codereturn datadef are_identical(self, addr1, addr2):+ """Return `True` if `addr1` and `addr2` are the same address."""data1 = self.as_data(addr1)data2 = self.as_data(addr2)return data1 == data2+ def copy(self, address):+ """Return a new instance of the same address."""+ data = self.as_data(address)+ return self.model.objects.create(**data)+def store_address(self, user, address):+ """Add the address to a user's address book if not already present."""data = self.as_data(address)address, dummy_created = user.addresses.get_or_create(**data)return address@@ -92,24 +103,27 @@ class Address(models.Model):class UserManager(BaseUserManager):- def create_user(self, email, password=None, is_staff=False,- is_active=True, username='', **extra_fields):- 'Creates a User with the given username, email and password'+ def create_user(+ self, email, password=None, is_staff=False, is_active=True,+ **extra_fields):+ """Create a user instance with the given email and password."""email = UserManager.normalize_email(email)- user = self.model(email=email, is_active=is_active,- is_staff=is_staff, **extra_fields)+ user = self.model(+ email=email, is_active=is_active, is_staff=is_staff,+ **extra_fields)if password:user.set_password(password)user.save()return userdef create_superuser(self, email, password=None, **extra_fields):- return self.create_user(email, password, is_staff=True,- is_superuser=True, **extra_fields)+ return self.create_user(+ email, password, is_staff=True, is_superuser=True, **extra_fields)class User(PermissionsMixin, AbstractBaseUser, index.Indexed):- email = models.EmailField(pgettext_lazy('User field', 'email'), unique=True)+ email = models.EmailField(+ pgettext_lazy('User field', 'email'), unique=True)addresses = models.ManyToManyField(Address, blank=True,verbose_name=pgettext_lazy('User field', 'addresses'))