Skip to content

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

Simplify checkout structure

Michał Ociepkaaf28ebf47def
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.py
index 1b27253804..e966d67b7c 100644
--- a/saleor/checkout/core.py
+++ b/saleor/checkout/core.py
@@ -1,114 +1,202 @@
-from collections import defaultdict
+from __future__ import unicode_literals
+from functools import wraps
from django.conf import settings
+from django.db import transaction
+from django.forms.models import model_to_dict
from prices import Price
-from satchless.process import ProcessManager
-from .steps import ShippingAddressStep, ShippingMethodStep, SummaryStep
from ..cart import Cart
from ..core import analytics
from ..order.models import Order
+from ..shipping.models import ShippingMethodCountry
+from ..userprofile.models import Address, User
STORAGE_SESSION_KEY = 'checkout_storage'
-class CheckoutStorage(defaultdict):
- modified = False
-
- def __init__(self, *args, **kwargs):
- super(CheckoutStorage, self).__init__(dict, *args, **kwargs)
-
-
-class Checkout(ProcessManager):
- steps = None
+class Checkout(object):
- def __init__(self, request):
- self.request = request
- self.steps = []
- try:
- self.storage = CheckoutStorage(
- request.session[STORAGE_SESSION_KEY])
- except KeyError:
- self.storage = CheckoutStorage()
- self.cart = Cart.for_session_cart(request.cart,
- discounts=request.discounts)
- self.generate_steps(self.cart)
-
- def __iter__(self):
- return iter(self.steps)
+ VERSION = '1.0.0'
+ modified = False
- def generate_steps(self, cart):
+ def __init__(self, cart, user, tracking_code):
self.cart = cart
- if self.is_shipping_required():
- self.shipping_address_step = ShippingAddressStep(
- self.request, self.storage['shipping_address'], checkout=self)
- shipping_address = self.shipping_address_step.address
- self.steps.append(self.shipping_address_step)
- self.shipping_method_step = ShippingMethodStep(
- self.request, self.storage['shipping_method'],
- shipping_address, self.cart, checkout=self)
- self.steps.append(self.shipping_method_step)
- else:
- shipping_address = None
- self.shipping_address_step = None
- self.shipping_method_step = None
-
- summary_step = SummaryStep(self.request, self.storage['summary'],
- shipping_address, checkout=self)
- self.steps.append(summary_step)
-
- def get_total(self, **kwargs):
- zero = Price(0, currency=settings.DEFAULT_CURRENCY)
- cost_iterator = (total_with_shipping
- for shipping, shipping_cost, total_with_shipping
- in self.get_deliveries(**kwargs))
- total = sum(cost_iterator, zero)
- return total
+ self.storage = {'version': self.VERSION}
+ self.tracking_code = tracking_code
+ self.user = user
+
+ @classmethod
+ def from_storage(cls, storage_data, cart, user, tracking_code):
+ checkout = cls(cart, user, tracking_code)
+ checkout.storage = storage_data
+ try:
+ version = checkout.storage['version']
+ except (TypeError, KeyError):
+ version = None
+ if version != cls.VERSION:
+ checkout.storage = {'version': cls.VERSION}
+ return checkout
- def save(self):
- self.request.session[STORAGE_SESSION_KEY] = dict(self.storage)
+ def for_storage(self):
+ return self.storage
def clear_storage(self):
- try:
- del self.request.session[STORAGE_SESSION_KEY]
- except KeyError:
- pass
-
- self.cart.clear()
+ self.storage = None
+ self.modified = True
+ @property
def is_shipping_required(self):
return self.cart.is_shipping_required()
- def get_deliveries(self, **kwargs):
+ @property
+ def deliveries(self):
for partition in self.cart.partition():
- if (self.shipping_address_step and
- self.shipping_method_step.shipping_method):
- shipping_method = self.shipping_method_step.shipping_method
- shipping_cost = shipping_method.get_delivery_total(partition)
+ if self.shipping_method:
+ shipping_cost = self.shipping_method.get_total()
else:
shipping_cost = Price(0, currency=settings.DEFAULT_CURRENCY)
- total_with_shipping = partition.get_total(**kwargs) + shipping_cost
+ total_with_shipping = partition.get_total() + shipping_cost
yield partition, shipping_cost, total_with_shipping
+ @property
+ def shipping_address(self):
+ address_data = self.storage.get('shipping_address')
+ if address_data is None and self.user.is_authenticated():
+ return self.user.default_shipping_address
+ elif address_data is None:
+ address_data = {}
+ if address_data.get('id'):
+ try:
+ return Address.objects.get(id=address_data['id'])
+ except Address.DoesNotExist:
+ return Address()
+ return Address(**address_data)
+
+ @shipping_address.setter
+ def shipping_address(self, address):
+ address_data = model_to_dict(address)
+ address_data['country'] = str(address_data['country'])
+ self.storage['shipping_address'] = address_data
+ self.modified = True
+
+ @property
+ def shipping_method(self):
+ shipping_method_country_id = self.storage.get('shipping_method_country_id')
+ if shipping_method_country_id is not None:
+ try:
+ shipping_method_country = ShippingMethodCountry.objects.get(
+ id=shipping_method_country_id)
+ except ShippingMethodCountry.DoesNotExist:
+ return None
+ shipping_country_code = self.shipping_address.country.code
+ any_country = ShippingMethodCountry.ANY_COUNTRY
+ if (shipping_method_country.country_code == any_country
+ or shipping_method_country.country_code == shipping_country_code):
+ return shipping_method_country
+
+ @shipping_method.setter
+ def shipping_method(self, shipping_method_country):
+ self.storage['shipping_method_country_id'] = shipping_method_country.id
+ self.modified = True
+
+ @property
+ def email(self):
+ return self.storage.get('email')
+
+ @email.setter
+ def email(self, email):
+ self.storage['email'] = email
+ self.modified = True
+
+ @property
+ def billing_address(self):
+ address_data = self.storage.get('billing_address')
+ if address_data is None and self.user.is_authenticated():
+ return self.user.default_billing_address
+ elif address_data is None:
+ address_data = self.storage.get('shipping_address', {})
+ if address_data.get('id'):
+ try:
+ return Address.objects.get(id=address_data['id'])
+ except Address.DoesNotExist:
+ return Address()
+ return Address(**address_data)
+
+ @billing_address.setter
+ def billing_address(self, address):
+ address_data = model_to_dict(address)
+ address_data['country'] = str(address_data['country'])
+ self.storage['billing_address'] = address_data
+ self.modified = True
+
+ @property
+ def is_shipping_same_as_billing(self):
+ return Address.objects.are_identical(self.shipping_address, self.billing_address)
+
+ def _save_address(self, address, is_billing=False, is_shipping=False):
+ if self.user.is_authenticated() and address.id is None:
+ address = User.objects.store_address(
+ self.user, address, shipping=is_shipping, billing=is_billing)
+ elif address.id is None:
+ address.save()
+ return address
+
+ @transaction.atomic
def create_order(self):
- order = Order()
- if self.request.user.is_authenticated():
- order.user = self.request.user
- for step in self.steps:
- step.add_to_order(order)
- if self.request.user.is_authenticated():
- order.anonymous_user_email = ''
- order.tracking_client_id = analytics.get_client_id(self.request)
- order.total = self.get_total()
- order.save()
+ shipping_address = self._save_address(self.shipping_address, is_shipping=True)
+ billing_address = self._save_address(self.billing_address, is_billing=True)
+ if self.user.is_authenticated():
+ order = Order.objects.create(
+ billing_address=billing_address, shipping_address=shipping_address,
+ user=self.user, total=self.get_total(),
+ tracking_client_id=self.tracking_code)
+ else:
+ order = Order.objects.create(
+ billing_address=billing_address, shipping_address=shipping_address,
+ anonymous_user_email=self.email, total=self.get_total(),
+ tracking_client_id=self.tracking_code)
+
+ for partition in self.cart.partition():
+ shipping_required = partition.is_shipping_required()
+ if shipping_required:
+ shipping_price = self.shipping_method.get_total()
+ shipping_method_name = str(self.shipping_method)
+ else:
+ shipping_price = 0
+ shipping_method_name = None
+ group = order.groups.create(
+ shipping_required=shipping_required,
+ shipping_price=shipping_price,
+ shipping_method_name=shipping_method_name)
+ group.add_items_from_partition(partition)
+
return order
- def available_steps(self):
- available = []
- for step in self:
- step.is_step_available = True
- available.append(step)
- if not self.validate_step(step):
- break
- step.is_step_valid = True
- return available
+ def get_total(self):
+ zero = Price(0, currency=settings.DEFAULT_CURRENCY)
+ cost_iterator = (
+ total_with_shipping for shipping, shipping_cost, total_with_shipping
+ in self.deliveries)
+ total = sum(cost_iterator, zero)
+ return total
+
+
+def load_checkout(view):
+ @wraps(view)
+ def func(request):
+ try:
+ session_data = request.session[STORAGE_SESSION_KEY]
+ except KeyError:
+ session_data = ''
+ tracking_code = analytics.get_client_id(request)
+ cart = Cart.for_session_cart(
+ request.cart, discounts=request.discounts)
+ checkout = Checkout.from_storage(
+ session_data, cart, request.user, tracking_code)
+ response = view(request, checkout)
+ if checkout.modified:
+ request.session[STORAGE_SESSION_KEY] = checkout.for_storage()
+ return response
+
+ return func
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index dd17c12d70..755dab545f 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -1,73 +1,77 @@
from django import forms
+from django.template.loader import get_template
+from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
+from django_prices.templatetags.prices_i18n import format_price
+from ..shipping.models import ShippingMethodCountry
+from ..userprofile.models import Address
-class AddressChoiceIterator(forms.models.ModelChoiceIterator):
- def __iter__(self):
- if self.field.copy_choice:
- yield self.field.copy_choice_value, self.field.copy_choice_label
- for obj in self.queryset:
- yield self.choice(obj)
- yield self.field.new_choice_value, self.field.new_choice_label
+class CheckoutAddressField(forms.ChoiceField):
+ widget = forms.RadioSelect()
-class AddressChoiceField(forms.ModelChoiceField):
- copy_choice_value = 'copy'
- copy_choice_label = _('Use shipping address for billing')
- new_choice_value = 'new'
- new_choice_label = _('Enter a new address')
- def __init__(self, queryset, can_copy, *args, **kwargs):
- if queryset or can_copy:
- widget = forms.RadioSelect
- else:
- widget = forms.HiddenInput
- if not can_copy:
- self.copy_choice_value = None
- super(AddressChoiceField, self).__init__(
- widget=widget, queryset=queryset, *args, **kwargs)
- self.widget.field_instance = self
+class ShippingAddressesForm(forms.Form):
- def validate(self, value):
- if not self.is_special_choice(value):
- return super(AddressChoiceField, self).validate(value)
+ NEW_ADDRESS = 'new_address'
+ CHOICES = (
+ (NEW_ADDRESS, _('Enter a new address')),
+ )
- def to_python(self, value):
- if self.is_special_choice(value):
- return value
- else:
- return super(AddressChoiceField, self).to_python(value)
+ address = CheckoutAddressField(choices=CHOICES, initial=NEW_ADDRESS)
- def _get_choices(self):
- if hasattr(self, '_choices'):
- return self._choices
- return AddressChoiceIterator(self)
+ def __init__(self, *args, **kwargs):
+ additional_addresses = kwargs.pop('additional_addresses', [])
+ super(ShippingAddressesForm, self).__init__(*args, **kwargs)
+ address_field = self.fields['address']
+ address_choices = [
+ (address.id, str(address)) for address in additional_addresses]
+ address_field.choices = list(self.CHOICES) + address_choices
- choices = property(_get_choices, forms.ChoiceField._set_choices)
- def is_special_choice(self, value):
- return value in (self.new_choice_value, self.copy_choice_value)
+class BillingAddressesForm(ShippingAddressesForm):
+ NEW_ADDRESS = 'new_address'
+ SHIPPING_ADDRESS = 'shipping_address'
+ CHOICES = (
+ (NEW_ADDRESS, _('Enter a new address')),
+ (SHIPPING_ADDRESS, _('Same as shipping'))
+ )
-class UserAddressesForm(forms.Form):
- def __init__(self, queryset, can_copy=False, *args, **kwargs):
- super(UserAddressesForm, self).__init__(*args, **kwargs)
- self.fields['address'] = AddressChoiceField(queryset=queryset,
- can_copy=can_copy)
+ address = CheckoutAddressField(choices=CHOICES, initial=SHIPPING_ADDRESS)
-class ShippingForm(forms.Form):
- method = forms.ChoiceField(label=_('Shipping method'),
- widget=forms.RadioSelect)
+class ShippingCountryChoiceField(forms.ModelChoiceField):
- def __init__(self, delivery_choices, *args, **kwargs):
- super(ShippingForm, self).__init__(*args, **kwargs)
+ widget = forms.RadioSelect()
+
+ def label_from_instance(self, obj):
+ price_html = format_price(obj.price.gross, obj.price.currency)
+ label = mark_safe('%s %s' % (obj.shipping_method, price_html))
+ return label
+
+
+class ShippingMethodForm(forms.Form):
+
+ method = ShippingCountryChoiceField(
+ queryset=ShippingMethodCountry.objects.select_related(
+ 'shipping_method').order_by('price').all(),
+ label=_('Shipping method'), required=True)
+
+ def __init__(self, country_code, *args, **kwargs):
+ super(ShippingMethodForm, self).__init__(*args, **kwargs)
method_field = self.fields['method']
- method_field.choices = delivery_choices
- if len(delivery_choices) == 1:
- method_field.initial = delivery_choices[0][1]
+ if country_code:
+ queryset = method_field.queryset
+ 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 = None
+
+class AnonymousUserShippingForm(forms.Form):
-class AnonymousEmailForm(forms.Form):
- email = forms.EmailField()
+ email = forms.EmailField(
+ required=True, widget=forms.EmailInput(attrs={'autocomplete': 'shipping email'}))
diff --git a/saleor/checkout/steps.py b/saleor/checkout/steps.py
deleted file mode 100644
index e2022de67b..0000000000
--- a/saleor/checkout/steps.py
+++ /dev/null
@@ -1,292 +0,0 @@
-from __future__ import unicode_literals
-from operator import itemgetter
-
-from django.core.exceptions import ValidationError
-from django.db import models
-from django.db import transaction
-from django.shortcuts import redirect
-from django.utils.translation import ugettext_lazy as _
-from satchless.process import InvalidData
-
-from .forms import ShippingForm, UserAddressesForm
-from ..checkout.forms import AnonymousEmailForm
-from ..core.utils import BaseStep
-from ..delivery import get_delivery_options_for_items
-from ..userprofile.forms import AddressForm
-from ..userprofile.models import Address, User
-
-
-def find_address_book_entry(addresses, address):
- for own_address in addresses:
- if Address.objects.are_identical(address, own_address):
- return own_address
-
-
-class BaseCheckoutStep(BaseStep):
- is_step_valid = False
- is_step_available = False
- forms = {}
-
- def __init__(self, request, storage, checkout):
- super(BaseCheckoutStep, self).__init__(request)
- self.storage = storage
- self.checkout = checkout
-
- @models.permalink
- def get_absolute_url(self):
- return 'checkout:details', (), {'step': str(self)}
-
- def add_to_order(self, order):
- raise NotImplementedError()
-
- def __str__(self):
- return self.step_name
-
-
-class ShippingAddressStep(BaseCheckoutStep):
- template = 'checkout/shipping_address.html'
- title = _('Shipping Address')
- step_name = 'shipping-address'
- is_new_address = True
- addresses = []
-
- def __init__(self, request, storage, checkout):
- super(ShippingAddressStep, self).__init__(request, storage, checkout)
- address_data = storage.get('address', {})
- address = Address(**address_data)
- self.address = address
- self.address_id = storage.get('address_id')
- initial_address = 'new'
- if request.user.is_authenticated():
- self.email = request.user.email
- addresses_queryset = request.user.addresses.all()
- self.addresses = list(addresses_queryset)
- selected_address = find_address_book_entry(self.addresses, address)
- if selected_address:
- address = None
- initial_address = selected_address.id
- elif not address_data:
- default_address = request.user.default_shipping_address
- if default_address:
- initial_address = default_address.id
- elif self.addresses:
- initial_address = self.addresses[0].id
- else:
- email = storage.get('email', '')
- self.email = email
- self.forms['email'] = AnonymousEmailForm(request.POST or None,
- initial={'email': email})
- addresses_queryset = None
-
- self.forms['addresses_form'] = UserAddressesForm(
- data=request.POST or None, queryset=addresses_queryset,
- prefix=self.step_name, initial={'address': initial_address})
- self.forms['new_address'] = AddressForm(
- request.POST or None, prefix=self.step_name, instance=address)
-
- def process(self, extra_context=None):
- context = dict(extra_context or {})
- context['addresses'] = self.addresses
- return super(ShippingAddressStep, self).process(extra_context=context)
-
- def forms_are_valid(self):
- address = None
- addresses_form = self.forms['addresses_form']
- if addresses_form.is_valid():
- choice = addresses_form.cleaned_data['address']
- if choice == 'new':
- new_address_form = self.forms['new_address']
- if new_address_form.is_valid():
- address = Address(**new_address_form.cleaned_data)
- else:
- address = choice
-
- if address:
- own_address = find_address_book_entry(self.addresses, address)
- if own_address:
- self.address = own_address
- self.address_id = own_address.id
- else:
- self.address = address
- self.address_id = None
-
- email_form = self.forms.get('email')
- if email_form:
- valid_email = False
- if email_form.is_valid():
- valid_email = True
- self.email = self.forms['email'].cleaned_data['email']
- return address and valid_email
- return address
-
- def validate(self):
- try:
- self.address.clean_fields()
- except ValidationError as e:
- raise InvalidData(e.messages)
-
- if not self.email:
- raise InvalidData()
-
- def save(self):
- self.storage['email'] = self.email
- self.storage['address'] = Address.objects.as_data(self.address)
- self.storage['address_id'] = self.address_id
-
- def add_to_order(self, order):
- self.address.save()
- order.shipping_address = self.address
- if order.user:
- User.objects.store_address(order.user, self.address, shipping=True)
-
-
-class ShippingMethodStep(BaseCheckoutStep):
- template = 'checkout/shipping_method.html'
- title = _('Shipping Method')
- step_name = 'shipping-method'
-
- def __init__(self, request, storage, shipping_address, cart, checkout):
- super(ShippingMethodStep, self).__init__(request, storage, checkout)
- self.shipping_method = None
- selected_method_name = storage.get('shipping_method')
- available_shipping = [
- {'method': method, 'cost': method.get_delivery_total(cart)}
- for method in get_delivery_options_for_items(
- cart, address=shipping_address)]
-
- shipping_choices = [(shipping['method'].name, shipping['method'].name)
- for shipping in available_shipping]
-
- if available_shipping:
- for shipping in available_shipping:
- if shipping['method'].name == selected_method_name:
- self.shipping_method = shipping['method']
- break
- else:
- cheapest_shipping = min(available_shipping,
- key=itemgetter('cost'))
- selected_method_name = cheapest_shipping['method'].name
- self.available_shipping = available_shipping
- shipping_form = ShippingForm(shipping_choices, request.POST or None,
- initial={'method': selected_method_name})
- self.forms['shipping'] = shipping_form
- self.selected_method_name = selected_method_name
-
- def process(self, extra_context=None):
- context = dict(extra_context or {})
- context['available_shipping'] = self.available_shipping
- context['selected_method_name'] = self.selected_method_name
- return super(ShippingMethodStep, self).process(extra_context=context)
-
- def save(self):
- shipping_form = self.forms['shipping']
- self.storage['shipping_method'] = shipping_form.cleaned_data['method']
-
- def add_to_order(self, order):
- order.shipping_method = self.shipping_method
-
- def validate(self):
- selected_method_name = self.storage.get('shipping_method')
- valid_methods = [d['method'].name for d in self.available_shipping]
- if selected_method_name not in valid_methods:
- raise InvalidData(_('Select a valid shipping method'))
-
-
-class SummaryStep(BaseCheckoutStep):
- template = 'checkout/summary.html'
- title = _('Summary')
- step_name = 'summary'
- addresses = []
- select_copy_shipping_address = True
-
- def __init__(self, request, storage, shipping_address, checkout):
- super(SummaryStep, self).__init__(request, storage, checkout)
- self.billing_address = storage.get('billing_address')
- self.shipping_address = shipping_address
- without_shipping = not checkout.is_shipping_required()
- initial_address = 'copy' if shipping_address else 'new'
- if request.user.is_authenticated():
- queryset = request.user.addresses.all()
- self.addresses = list(queryset)
- default_billing_address = request.user.default_billing_address
- if default_billing_address:
- initial_address = default_billing_address.id
- elif without_shipping and self.addresses:
- initial_address = self.addresses[0].id
- else:
- queryset = None
- if without_shipping:
- self.forms['email'] = AnonymousEmailForm(request.POST or None)
- self.forms['new_address'] = AddressForm(request.POST or None,
- prefix=self.step_name)
- self.forms['addresses_form'] = UserAddressesForm(
- data=request.POST or None, queryset=queryset,
- prefix=self.step_name, initial={'address': initial_address},
- can_copy=shipping_address)
-
- def process(self, extra_context=None):
- context = dict(extra_context or {})
- context['shipping_address'] = self.shipping_address
- context['addresses'] = self.addresses
- context['display_email_form'] = self.forms.get('email')
- response = super(SummaryStep, self).process(context)
-
- if not response:
- with transaction.atomic():
- order = self.checkout.create_order()
- order.create_history_entry()
- order.send_confirmation_email()
- return redirect('order:payment', token=order.token)
- return response
-
- def forms_are_valid(self):
- addresses_form = self.forms['addresses_form']
- new_address_form = self.forms['new_address']
- if addresses_form.is_valid():
- choice = addresses_form.cleaned_data['address']
- if choice == 'copy':
- self.billing_address = self.shipping_address
- elif choice in self.addresses:
- own_address = find_address_book_entry(self.addresses, choice)
- if own_address:
- self.billing_address = own_address
- else:
- self.billing_address = choice
- elif choice == 'new' and new_address_form.is_valid():
- self.billing_address = Address(**new_address_form.cleaned_data)
-
- email_form = self.forms.get('email')
- if email_form:
- return email_form.is_valid() and self.billing_address
- else:
- return self.billing_address
-
- def validate(self):
- raise InvalidData()
-
- def save(self):
- billing_addres_data = Address.objects.as_data(self.billing_address)
- self.storage = {'billing_address': billing_addres_data}
- if self.forms.get('email'):
- self.storage['email'] = self.forms['email'].cleaned_data['email']
-
- def add_to_order(self, order):
- self.billing_address.save()
- order.billing_address = self.billing_address
- if order.user:
- User.objects.store_address(
- order.user, self.billing_address, billing=True)
- order.save()
- method = order.shipping_method
- for partition in self.checkout.cart.partition():
- shipping_required = partition.is_shipping_required()
- if shipping_required and method:
- shipping_price = method.get_delivery_total(partition)
- else:
- shipping_price = 0
- group = order.groups.create(
- shipping_required=shipping_required,
- shipping_price=shipping_price,
- shipping_method=method)
- group.add_items_from_partition(partition)
- self.checkout.clear_storage()
diff --git a/saleor/checkout/templates/checkout/details.html b/saleor/checkout/templates/checkout/details.html
index 3976a81a59..294b0239d3 100644
--- a/saleor/checkout/templates/checkout/details.html
+++ b/saleor/checkout/templates/checkout/details.html
@@ -26,7 +26,7 @@
{% if not user.is_authenticated %}
<p class="alert alert-info">
{% trans "Already have an account?" %}
- <a href="{% url "registration:login" %}?next={% url "checkout:details" step="shipping-address" %}">
+ <a href="{% url "registration:login" %}?next={{ request.get_full_path }}">
{% trans "Sign in" %}
</a>
</p>
@@ -35,29 +35,44 @@
<div class="row">
<div class="col-sm-8">
+ {% block steps_menu %}
<ul class="nav nav-pills nav-justified nav-wizard">
- {% for stepitem in checkout %}
- <li{% if stepitem == step %} class="active"{% endif %}>
- {% if not forloop.first %}
- <div class="nav-wedge"></div>
- {% endif %}
- <a{% if stepitem.is_step_available %} href="{{ stepitem.get_absolute_url }}"{% endif %}>
- {{ stepitem.title }}
- </a>
- {% if not forloop.last %}
- <div class="nav-arrow"></div>
- {% endif %}
- </li>
- {% endfor %}
+ <li>
+ <a href="{% url "cart:index" %}">{% trans "Cart" %}</a>
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-address" %}">{% trans "Shipping address" %}</a>
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-method" %}">{% trans "Shipping method" %}</a>
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:summary" %}">{% trans "Summary" %}</a>
+ </li>
</ul>
-
- <br>
+ {% endblock steps_menu %}
{% block forms %}{% endblock %}
</div>
<div class="col-sm-4">
- {% for delivery, delivery_cost, total_with_delivery in checkout.get_deliveries %}
+ {% if checkout.shipping_address.country %}
+ <div class="panel panel-default">
+ <div class="panel-heading">{% trans "Shipping address" %}</div>
+ <div class="panel-body">
+ {% include "userprofile/snippets/address-details.html" with address=checkout.shipping_address only %}
+ </div>
+ </div>
+ {% endif %}
+
+
+ {% for delivery, delivery_cost, total_with_delivery in checkout.deliveries %}
<div class="panel panel-default">
<div class="panel-heading">
{% blocktrans with number=forloop.counter %}Shipment #{{ number }}{% endblocktrans %}
diff --git a/saleor/checkout/templates/checkout/payment.html b/saleor/checkout/templates/checkout/payment.html
new file mode 100644
index 0000000000..7f2dff997b
--- /dev/null
+++ b/saleor/checkout/templates/checkout/payment.html
@@ -0,0 +1,19 @@
+{% extends "checkout/details.html" %}
+{% load i18n %}
+{% load as_vertical_form from bootstrap %}
+
+
+{% block forms %}
+ <form method="post" novalidate>
+ {% csrf_token %}
+ <h4>{% trans "Payment" %}</h4>
+ <p class="text-right">
+ {{ payment_form|as_vertical_form }}
+
+ {{ billing_address_form|as_vertical_form }}
+ <button type="submit" class="btn btn-primary btn-lg">
+ {% trans "Place order" %}
+ </button>
+ </p>
+ </form>
+{% endblock forms %}
diff --git a/saleor/checkout/templates/checkout/shipping_address.html b/saleor/checkout/templates/checkout/shipping_address.html
index d1f421cb22..3018eadbf6 100644
--- a/saleor/checkout/templates/checkout/shipping_address.html
+++ b/saleor/checkout/templates/checkout/shipping_address.html
@@ -1,18 +1,45 @@
{% extends "checkout/details.html" %}
{% load i18n %}
+{% load as_vertical_form from bootstrap %}
+
+{% block steps_menu %}
+ <ul class="nav nav-pills nav-justified nav-wizard">
+ <li>
+ <a href="{% url "cart:index" %}">{% trans "Cart" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li class="active">
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-address" %}">{% trans "Shipping address" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a>{% trans "Shipping method" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a>{% trans "Summary" %}</a>
+ </li>
+ </ul>
+{% endblock steps_menu %}
{% block forms %}
<form method="post" novalidate>
{% csrf_token %}
- <h4>{% trans "Shipping address" %}</h4>
- <br>
- {% if user.is_authenticated %}
- {% include "checkout/address_form.html" with addresses_form=step.forms.addresses_form %}
+ <h3>{% trans "Shipping address" %}</h3>
+ {% if request.user.is_authenticated %}
+ {% include "checkout/snippets/addresses-form.html" with addresses_form=user_form addresses=additional_addresses address_form=address_form only %}
{% else %}
- {% include "checkout/address_form.html" with addresses_form=step.forms.addresses_form display_email_form=True %}
+ {{ user_form|as_vertical_form }}
+ {% include "userprofile/snippets/address-form.html" with address_form=address_form only %}
{% endif %}
- <br>
+
<p class="text-right">
<button type="submit" class="btn btn-primary btn-lg">
{% trans "Continue to shipping method" %}
diff --git a/saleor/checkout/templates/checkout/shipping_method.html b/saleor/checkout/templates/checkout/shipping_method.html
index 195a04caf0..ece6f226d8 100644
--- a/saleor/checkout/templates/checkout/shipping_method.html
+++ b/saleor/checkout/templates/checkout/shipping_method.html
@@ -2,32 +2,43 @@
{% load i18n %}
{% load gross from prices_i18n %}
+{% load as_vertical_form from bootstrap %}
+
+
+{% block steps_menu %}
+ <ul class="nav nav-pills nav-justified nav-wizard">
+ <li>
+ <a href="{% url "cart:index" %}">{% trans "Cart" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-address" %}">{% trans "Shipping address" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li class="active">
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-method" %}">{% trans "Shipping method" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a>{% trans "Summary" %}</a>
+ </li>
+ </ul>
+{% endblock steps_menu %}
+
{% block forms %}
<form method="post" novalidate>
{% csrf_token %}
- <h4>{% trans "Shipping method" %}</h4>
- <br>
- <div class="row">
- <div class="btn-group-vertical col-sm-12" data-toggle="buttons">
- {% with shipping_form=step.forms.shipping %}
- {% for method in available_shipping %}
- {% with method_name=method.method.name %}
- <label for="{{ shipping_form.method.html_name }}_{{ method_name }}" class="btn btn-default{% if method_name == selected_method_name %} active{% endif %}">
- <strong>{{ method.method }}</strong><br>
- <span class="badge">{% gross method.cost %}</span>
- <input type="radio"
- name="{{ shipping_form.method.html_name }}"
- value="{{ method_name }}"
- id="{{ shipping_form.method.html_name }}_{{ method_name }}"
- {% if method_name == selected_method_name %}checked{% endif %}>
- </label>
- {% endwith %}
- {% endfor %}
- {% endwith %}
- </div>
- </div>
- <br>
+ <h3>{% trans "Shipping method" %}</h3>
+
+ {{ shipping_method_form|as_vertical_form }}
+
<p class="text-right">
<button type="submit" class="btn btn-primary btn-lg">
{% trans "Continue to payment" %}
diff --git a/saleor/checkout/templates/checkout/snippets/addresses-form-panel.html b/saleor/checkout/templates/checkout/snippets/addresses-form-panel.html
new file mode 100644
index 0000000000..158c17ad5b
--- /dev/null
+++ b/saleor/checkout/templates/checkout/snippets/addresses-form-panel.html
@@ -0,0 +1,38 @@
+{% load as_vertical_form from bootstrap %}
+
+<div class="panel panel-default">
+ <div class="panel-heading" role="tab" id="address{{ radio_value }}">
+ <h4 class="radio panel-title">
+ <label role="button" data-toggle="collapse"
+ data-parent="#{{ parent_element_id }}"
+ data-target="#collapse{{ radio_value }}" aria-expanded="true"
+ aria-controls="collapse{{ value }}" for="address_{{ radio_value }}">
+ <input type="radio"
+ name="{{ radio_name }}"
+ value="{{ radio_value }}"
+ id="address_{{ radio_value }}"
+ {% if radio_value == value %}checked{% endif %}>
+ {% if address %}
+ {{ address.full_name }}, {{ address.street_address_1 }} {{ address.street_address_2 }}
+ {{ address.city }}
+ {% else %}
+ {{ label }}
+ {% endif %}
+ </label>
+ </h4>
+ </div>
+ <div id="collapse{{ radio_value }}"
+ class="panel-collapse collapse{% if radio_value == value %} in{% endif %}"
+ role="tabpanel"
+ aria-labelledby="headingOne">
+ {% if address %}
+ <div class="panel-body">
+ {% include "userprofile/snippets/address-details.html" with address=address only %}
+ </div>
+ {% elif address_form %}
+ <div class="panel-body">
+ {% include "userprofile/snippets/address-form.html" with address_form=address_form only %}
+ </div>
+ {% endif %}
+ </div>
+</div>
diff --git a/saleor/checkout/templates/checkout/snippets/addresses-form.html b/saleor/checkout/templates/checkout/snippets/addresses-form.html
new file mode 100644
index 0000000000..02832fcf25
--- /dev/null
+++ b/saleor/checkout/templates/checkout/snippets/addresses-form.html
@@ -0,0 +1,11 @@
+<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
+ {% if addresses_form.SHIPPING_ADDRESS %}
+ {% include "checkout/snippets/addresses-form-panel.html" with parent_element_id="accordion" radio_name=addresses_form.address.html_name radio_value=addresses_form.SHIPPING_ADDRESS label=_('Same as shipping') value=addresses_form.address.value only %}
+ {% endif %}
+ {% for address in addresses %}
+ {% include "checkout/snippets/addresses-form-panel.html" with parent_element_id="accordion" radio_name=addresses_form.address.html_name radio_value=address.id label=address value=addresses_form.address.value address=address only %}
+ {% endfor %}
+ {% if addresses_form.NEW_ADDRESS and address_form %}
+ {% include "checkout/snippets/addresses-form-panel.html" with parent_element_id="accordion" radio_name=addresses_form.address.html_name radio_value=addresses_form.NEW_ADDRESS label=_('Enter a new address') value=addresses_form.address.value address_form=address_form only %}
+ {% endif %}
+</div>
diff --git a/saleor/checkout/templates/checkout/summary.html b/saleor/checkout/templates/checkout/summary.html
index d493809955..5271bbbb96 100644
--- a/saleor/checkout/templates/checkout/summary.html
+++ b/saleor/checkout/templates/checkout/summary.html
@@ -1,14 +1,42 @@
{% extends "checkout/details.html" %}
{% load i18n %}
+{% load as_vertical_form from bootstrap %}
+
+
+{% block steps_menu %}
+ <ul class="nav nav-pills nav-justified nav-wizard">
+ <li>
+ <a href="{% url "cart:index" %}">{% trans "Cart" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-address" %}">{% trans "Shipping address" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li>
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:shipping-method" %}">{% trans "Shipping method" %}</a>
+
+ <div class="nav-arrow"></div>
+ </li>
+ <li class="active">
+ <div class="nav-wedge"></div>
+ <a href="{% url "checkout:summary" %}">{% trans "Summary" %}</a>
+ </li>
+ </ul>
+{% endblock steps_menu %}
{% block forms %}
<form method="post" novalidate>
{% csrf_token %}
- <h4>{% trans "Billing address" %}</h4>
- <br>
- {% include "checkout/address_form.html" with addresses_form=step.forms.addresses_form %}
- <br>
+ <h3>{% trans "Billing address" %}</h3>
+
+ {% include "checkout/snippets/addresses-form.html" with addresses_form=addresses_form addresses=additional_addresses address_form=address_form only %}
+
<p class="text-right">
<button type="submit" class="btn btn-primary btn-lg">
{% trans "Place order" %}
diff --git a/saleor/checkout/urls.py b/saleor/checkout/urls.py
index 1c69658e46..0ee3c66f06 100644
--- a/saleor/checkout/urls.py
+++ b/saleor/checkout/urls.py
@@ -4,6 +4,8 @@ from . import views
urlpatterns = [
- url(r'^$', views.details, kwargs={'step': None}, name='index'),
- url(r'^(?P<step>[a-z0-9-]+)/$', views.details, name='details')
+ url(r'^$', views.index_view, name='index'),
+ url(r'^shipping-address/', views.shipping_address_view, name='shipping-address'),
+ url(r'^shipping-method/', views.shipping_method_view, name='shipping-method'),
+ url(r'^summary/', views.summary_view, name='summary')
]
diff --git a/saleor/checkout/validators.py b/saleor/checkout/validators.py
new file mode 100644
index 0000000000..e753dc45a9
--- /dev/null
+++ b/saleor/checkout/validators.py
@@ -0,0 +1,36 @@
+from functools import wraps
+
+from django.core.exceptions import ValidationError
+from django.shortcuts import redirect
+
+
+def validate_cart(view):
+ @wraps(view)
+ def func(request, checkout):
+ if request.cart:
+ return view(request, checkout)
+ else:
+ return redirect('cart:index')
+ return func
+
+
+def validate_shipping_address(view):
+ @wraps(view)
+ def func(request, checkout):
+ if checkout.email is None or checkout.shipping_address is None:
+ return redirect('checkout:shipping-address')
+ try:
+ checkout.shipping_address.full_clean()
+ except ValidationError:
+ return redirect('checkout:shipping-address')
+ return view(request, checkout)
+ return func
+
+
+def validate_shipping_method(view):
+ @wraps(view)
+ def func(request, checkout):
+ if checkout.shipping_method is None:
+ return redirect('checkout:shipping-method')
+ return view(request, checkout)
+ return func
diff --git a/saleor/checkout/views.py b/saleor/checkout/views.py
index f0d3444e25..b3bc6b6540 100644
--- a/saleor/checkout/views.py
+++ b/saleor/checkout/views.py
@@ -1,27 +1,149 @@
-from django.http.response import Http404
from django.shortcuts import redirect
+from django.template.response import TemplateResponse
+
+
+from .core import load_checkout
+from .forms import (ShippingAddressesForm, AnonymousUserShippingForm,
+ ShippingMethodForm, BillingAddressesForm)
+from .validators import (
+ validate_cart, validate_shipping_address, validate_shipping_method)
+from ..userprofile.forms import AddressForm
+from ..userprofile.models import Address
+
+STORAGE_SESSION_KEY = 'checkout_storage'
+
+
+def get_user_shipping_forms(data, additional_addresses, shipping_address):
+ if shipping_address.id:
+ address_form = AddressForm(data, autocomplete_type='shipping')
+ addresses_form = ShippingAddressesForm(
+ data, additional_addresses=additional_addresses,
+ initial={'address': shipping_address.id})
+ else:
+ address_form = AddressForm(data, instance=shipping_address)
+ addresses_form = ShippingAddressesForm(
+ data, additional_addresses=additional_addresses)
+ if addresses_form.is_valid():
+ if addresses_form.cleaned_data['address'] != ShippingAddressesForm.NEW_ADDRESS:
+ address_id = addresses_form.cleaned_data['address']
+ address = Address.objects.get(id=address_id)
+ return address_form, addresses_form, address
+ elif address_form.is_valid():
+ address = address_form.instance
+ return address_form, addresses_form, address
+ return address_form, addresses_form, None
+
+
+def get_anonymous_user_shipping_forms(data, shipping_address, email):
+ address_form = AddressForm(
+ data, instance=shipping_address, autocomplete_type='shipping')
+ user_form = AnonymousUserShippingForm(data, initial={'email': email})
+ if user_form.is_valid() and address_form.is_valid():
+ address = address_form.instance
+ email = user_form.cleaned_data['email']
+ else:
+ address = None
+ email = None
+ return address_form, user_form, address, email
+
+
+def get_billing_forms(data, additional_addresses, billing_address, shipping_address):
+ if Address.objects.are_identical(billing_address, shipping_address):
+ address_form = AddressForm(data, autocomplete_type='billing')
+ addresses_form = BillingAddressesForm(
+ data, additional_addresses=additional_addresses, initial={
+ 'address': BillingAddressesForm.SHIPPING_ADDRESS})
+ elif billing_address.id is None:
+ address_form = AddressForm(
+ data, instance=billing_address, autocomplete_type='billing')
+ addresses_form = BillingAddressesForm(
+ data, additional_addresses=additional_addresses, initial={
+ 'address': BillingAddressesForm.NEW_ADDRESS})
+ else:
+ address_form = AddressForm(data, autocomplete_type='billing')
+ addresses_form = BillingAddressesForm(
+ data, additional_addresses=additional_addresses, initial={
+ 'address': billing_address.id})
+ if addresses_form.is_valid():
+ address_id = addresses_form.cleaned_data['address']
+ if address_id == BillingAddressesForm.SHIPPING_ADDRESS:
+ return address_form, addresses_form, shipping_address
+ elif address_id != BillingAddressesForm.NEW_ADDRESS:
+ address = additional_addresses.get(id=address_id)
+ return address_form, addresses_form, address
+ elif address_form.is_valid():
+ return address_form, addresses_form, address_form.instance
+ return address_form, addresses_form, None
+
+
+@load_checkout
+@validate_cart
+def index_view(request, checkout):
+ return redirect('checkout:shipping-address')
+
+
+@load_checkout
+@validate_cart
+def shipping_address_view(request, checkout):
+ data = request.POST or None
+ if request.user.is_authenticated():
+ additional_addresses = request.user.addresses.all()
+ email = request.user.email
+ address_form, user_form, address = get_user_shipping_forms(
+ data, additional_addresses, checkout.shipping_address)
+ else:
+ additional_addresses = Address.objects.none()
+ address_form, user_form, address, email = get_anonymous_user_shipping_forms(
+ data, checkout.shipping_address, checkout.email)
+ if address is not None and email is not None:
+ checkout.shipping_address = address
+ checkout.email = email
+ return redirect('checkout:shipping-method')
+ return TemplateResponse(
+ request, 'checkout/shipping_address.html', context={
+ 'address_form': address_form, 'user_form': user_form, 'checkout': checkout,
+ 'additional_addresses': additional_addresses})
+
+
+@load_checkout
+@validate_cart
+@validate_shipping_address
+def shipping_method_view(request, checkout):
+ country_code = checkout.shipping_address.country.code
+ shipping_method_form = ShippingMethodForm(
+ 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})
+
+
+@load_checkout
+@validate_cart
+@validate_shipping_address
+@validate_shipping_method
+def summary_view(request, checkout):
+ user = request.user
+ data = request.POST or None
+ if user.is_authenticated():
+ additional_addresses = user.addresses.all()
+ else:
+ additional_addresses = Address.objects.none()
+ address_form, addresses_form, address = get_billing_forms(
+ data, additional_addresses, checkout.billing_address, checkout.shipping_address)
+ if address is not None:
+ checkout.billing_address = address
+ order = checkout.create_order()
+ checkout.clear_storage()
+ request.cart.clear()
+ order.create_history_entry()
+ order.send_confirmation_email()
+ return redirect('order:payment', token=order.token)
+ return TemplateResponse(
+ request, 'checkout/summary.html', context={
+ 'addresses_form': addresses_form, 'address_form': address_form,
+ 'checkout': checkout, 'additional_addresses': additional_addresses})
+
+
-from .core import Checkout
-from ..cart import Cart
-from ..cart.utils import contains_unavailable_products
-
-
-def details(request, step):
- if not request.cart or contains_unavailable_products(
- Cart.for_session_cart(request.cart, discounts=request.discounts)):
- return redirect('cart:index')
- checkout = Checkout(request)
- if not step:
- return redirect(checkout.get_next_step())
- try:
- step = checkout[step]
- except KeyError:
- raise Http404()
- if step not in checkout.available_steps():
- return redirect(checkout.get_next_step())
- response = step.process(
- extra_context={'checkout': checkout})
- if not response:
- checkout.save()
- return redirect(checkout.get_next_step())
- return response
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 76f12fe70e..46b095d7c9 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -4,16 +4,14 @@ import re
from django import forms
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
-from django.template.response import TemplateResponse
from django.utils.encoding import iri_to_uri, smart_text
-from satchless.process import InvalidData, Step
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
-__all__ = ['BaseStep', 'CategoryChoiceField', 'build_absolute_uri']
+__all__ = ['CategoryChoiceField', 'build_absolute_uri']
absolute_http_url_re = re.compile(r'^https?://', re.I)
@@ -33,47 +31,6 @@ class CategoryChoiceField(forms.ModelChoiceField):
return '%s%s' % (indent, smart_text(obj))
-class BaseStep(Step):
-
- forms = None
- template = ''
- group = None
-
- def __init__(self, request):
- self.request = request
- self.forms = {}
-
- def __nonzero__(self):
- try:
- self.validate()
- except InvalidData:
- return False
- return True
-
- def save(self):
- raise NotImplementedError()
-
- def forms_are_valid(self):
- for form in self.forms.values():
- if not form.is_valid():
- return False
- return True
-
- def validate(self):
- if not self.forms_are_valid():
- raise InvalidData()
-
- def process(self, extra_context=None):
- context = extra_context or {}
- if not self.forms_are_valid() or self.request.method == 'GET':
- context['step'] = self
- return TemplateResponse(self.request, self.template, context)
- self.save()
-
- def get_absolute_url(self):
- raise NotImplementedError()
-
-
def build_absolute_uri(location, is_secure=False):
from django.contrib.sites.models import Site
site = Site.objects.get_current()
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 4df91022af..965b5ba01e 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -110,7 +110,10 @@ class MoveItemsForm(forms.Form):
choice = self.cleaned_data['target_group']
old_group = self.item.delivery_group
if choice == 'new':
- target_group = DeliveryGroup.objects.duplicate_group(old_group)
+ # For new group we are set the same delivery name but with zero price
+ target_group = old_group.order.groups.create(
+ status=old_group.status,
+ shipping_method_name=old_group.shipping_method_name)
else:
target_group = DeliveryGroup.objects.get(pk=choice)
OrderedItem.objects.move_to_group(self.item, target_group, how_many)
diff --git a/saleor/delivery/__init__.py b/saleor/delivery/__init__.py
deleted file mode 100644
index 14c5d475c0..0000000000
--- a/saleor/delivery/__init__.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from __future__ import unicode_literals
-
-from django.conf import settings
-from django.utils.encoding import python_2_unicode_compatible
-from prices import Price
-from satchless.item import ItemSet
-
-
-class BaseDelivery(ItemSet):
- group = None
- name = ''
-
- def __iter__(self):
- return iter(self.group)
-
- def get_delivery_total(self, **kwargs):
- return Price(0, currency=settings.DEFAULT_CURRENCY)
-
- def get_total_with_delivery(self):
- return self.group.get_total() + self.get_delivery_total()
-
-
-@python_2_unicode_compatible
-class DummyShipping(BaseDelivery):
- name = 'dummy_shipping'
-
- def __str__(self):
- return 'Dummy shipping'
-
- def get_delivery_total(self, items, **kwargs):
- weight = sum(
- line.product.get_weight() * line.quantity for line in items)
- return Price(weight, currency=settings.DEFAULT_CURRENCY)
-
-
-def get_delivery_options_for_items(items, **kwargs):
- if 'address' in kwargs:
- yield DummyShipping()
- else:
- raise ValueError('Unknown delivery type')
-
-
-def get_delivery(name):
- return DummyShipping()
diff --git a/saleor/order/migrations/0010_auto_20160119_0541.py b/saleor/order/migrations/0010_auto_20160119_0541.py
new file mode 100644
index 0000000000..5b0b2f6b90
--- /dev/null
+++ b/saleor/order/migrations/0010_auto_20160119_0541.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.1 on 2016-01-19 11:41
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0009_auto_20151201_0820'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='deliverygroup',
+ name='shipping_method',
+ ),
+ migrations.RemoveField(
+ model_name='deliverygroup',
+ name='shipping_required',
+ ),
+ migrations.RemoveField(
+ model_name='order',
+ name='shipping_method',
+ ),
+ migrations.AddField(
+ model_name='deliverygroup',
+ name='shipping_method_name',
+ field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index d91708af49..a53090b8b0 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -9,8 +9,6 @@ from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
-from django.forms.models import model_to_dict
-from django.shortcuts import get_list_or_404
from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy
@@ -20,9 +18,7 @@ from payments.models import BasePayment
from prices import Price
from satchless.item import ItemLine, ItemSet
-from ..cart import CartLine
from ..core.utils import build_absolute_uri
-from ..delivery import get_delivery
from ..product.models import Product, ProductVariant
from ..userprofile.models import Address
@@ -57,11 +53,7 @@ class Order(models.Model, ItemSet):
editable=False)
shipping_address = models.ForeignKey(Address, related_name='+',
editable=False, null=True)
- shipping_method = models.CharField(
- pgettext_lazy('Order field', 'Delivery method'),
- max_length=255, blank=True)
- anonymous_user_email = models.EmailField(blank=True, default='',
- editable=False)
+ anonymous_user_email = models.EmailField(blank=True, default='', editable=False)
token = models.CharField(
pgettext_lazy('Order field', 'token'), max_length=36, unique=True)
total_net = PriceField(
@@ -112,7 +104,7 @@ class Order(models.Model, ItemSet):
def get_total(self):
return self.total
-
+
@property
def billing_full_name(self):
return '%s %s' % (self.billing_first_name, self.billing_last_name)
@@ -166,15 +158,6 @@ class Order(models.Model, ItemSet):
self.total_tax = Price(price.tax, currency=price.currency)
-class DeliveryGroupManager(models.Manager):
-
- def duplicate_group(self, group):
- data = model_to_dict(group)
- data['id'] = None
- data['status'] = 'new'
- return group.order.groups.create(**data)
-
-
class DeliveryGroup(models.Model, ItemSet):
STATUS_CHOICES = (
('new',
@@ -187,22 +170,15 @@ class DeliveryGroup(models.Model, ItemSet):
pgettext_lazy('Delivery group field', 'delivery status'),
max_length=32, default='new', choices=STATUS_CHOICES)
order = models.ForeignKey(Order, related_name='groups', editable=False)
- shipping_required = models.BooleanField(
- pgettext_lazy('Delivery group field', 'shipping required'),
- default=True)
shipping_price = PriceField(
pgettext_lazy('Delivery group field', 'shipping price'),
- currency=settings.DEFAULT_CURRENCY, max_digits=12,
- decimal_places=4,
- default=0,
- editable=False)
- shipping_method = models.CharField(max_length=255, default='',
- db_index=True, blank=True)
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4,
+ default=0, editable=False)
+ shipping_method_name = models.CharField(
+ max_length=255, null=True, default=None, blank=True, editable=False)
tracking_number = models.CharField(max_length=255, default='', blank=True)
last_updated = models.DateTimeField(null=True, auto_now=True)
- objects = DeliveryGroupManager()
-
def __str__(self):
return pgettext_lazy(
'Delivery group str', 'Shipment #%s') % self.pk
@@ -215,6 +191,10 @@ class DeliveryGroup(models.Model, ItemSet):
return iter(self.items.all())
return super(DeliveryGroup, self).__iter__()
+ @property
+ def shipping_required(self):
+ return self.shipping_method_name is not None
+
def change_status(self, status):
self.status = status
self.save()
@@ -238,21 +218,6 @@ class DeliveryGroup(models.Model, ItemSet):
stock=stock,
stock_location=stock.location if stock else None)
- def update_delivery_cost(self):
- if self.order.is_shipping_required():
- delivery = get_delivery(self.order.shipping_method)
- skus = [line.product_sku for line in self]
- variants = get_list_or_404(
- ProductVariant.objects.select_related('product'), sku__in=skus)
- variants_map = {variant.sku: variant for variant in variants}
- items = []
- for line in self:
- data = {'product': variants_map[line.product_sku],
- 'quantity': line.get_quantity()}
- items.append(CartLine(**data))
- self.shipping_price = delivery.get_delivery_total(items)
- self.save()
-
def get_total_quantity(self):
return sum([item.get_quantity() for item in self])
@@ -286,11 +251,8 @@ class OrderedItemManager(models.Manager):
item.save()
else:
item.delete()
- if source_group.get_total_quantity():
- source_group.update_delivery_cost()
- else:
+ if not source_group.get_total_quantity():
source_group.delete()
- target_group.update_delivery_cost()
if not order.get_items():
order.change_status('cancelled')
@@ -338,7 +300,6 @@ class OrderedItem(models.Model, ItemLine):
order = self.delivery_group.order
self.quantity = new_quantity
self.save()
- self.delivery_group.update_delivery_cost()
if not self.delivery_group.get_total_quantity():
self.delivery_group.delete()
if not order.get_items():
diff --git a/saleor/settings.py b/saleor/settings.py
index 7fa39ffe70..3d33c5aceb 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -135,6 +135,7 @@ INSTALLED_APPS = [
'saleor.order',
'saleor.registration',
'saleor.dashboard',
+ 'saleor.shipping',
# External apps
'versatileimagefield',
diff --git a/saleor/userprofile/forms.py b/saleor/userprofile/forms.py
index d82dd8fe54..316e770961 100644
--- a/saleor/userprofile/forms.py
+++ b/saleor/userprofile/forms.py
@@ -27,8 +27,14 @@ class AddressForm(forms.ModelForm):
exclude = []
def __init__(self, *args, **kwargs):
+ autocomplete_type = kwargs.pop('autocomplete_type', None)
super(AddressForm, self).__init__(*args, **kwargs)
autocomplete_dict = defaultdict(
lambda: 'off', self.AUTOCOMPLETE_MAPPING)
for field_name, field in self.fields.items():
- field.widget.attrs['autocomplete'] = autocomplete_dict[field_name]
+ if autocomplete_type:
+ autocomplete = '%s %s' % (
+ autocomplete_type, autocomplete_dict[field_name])
+ else:
+ autocomplete = autocomplete_dict[field_name]
+ field.widget.attrs['autocomplete'] = autocomplete
diff --git a/saleor/userprofile/models.py b/saleor/userprofile/models.py
index 738d92a882..63ab84de26 100644
--- a/saleor/userprofile/models.py
+++ b/saleor/userprofile/models.py
@@ -67,9 +67,15 @@ class Address(models.Model):
objects = AddressManager()
- def __str__(self):
+ @property
+ def full_name(self):
return '%s %s' % (self.first_name, self.last_name)
+ def __str__(self):
+ if self.company_name:
+ return '%s - %s' % (self.company_name, self.full_name)
+ return self.full_name
+
def __repr__(self):
return (
'Address(first_name=%r, last_name=%r, company_name=%r, '
@@ -109,6 +115,7 @@ class UserManager(BaseUserManager):
changed = True
if changed:
user.save()
+ return entry
@python_2_unicode_compatible
diff --git a/saleor/userprofile/templates/userprofile/address-edit.html b/saleor/userprofile/templates/userprofile/address-edit.html
index ef64a78616..455d259486 100644
--- a/saleor/userprofile/templates/userprofile/address-edit.html
+++ b/saleor/userprofile/templates/userprofile/address-edit.html
@@ -1,6 +1,5 @@
{% extends "base.html" %}
-{% load as_vertical_form from bootstrap %}
{% load i18n %}
{% block title %}{% trans "Edit Address" %} — {{ block.super }}{% endblock %}
@@ -21,44 +20,8 @@
<form action="." method="post">
{% csrf_token %}
<h4>{% trans "Address" %}</h4>
-
<br>
-
- <div class="row">
- <div class="col-sm-6">
- {{ address_form.first_name|as_vertical_form }}
- </div>
- <div class="col-sm-6">
- {{ address_form.last_name|as_vertical_form }}
- </div>
- </div>
- {{ address_form.company_name|as_vertical_form }}
- <div class="row">
- <div class="col-sm-8">
- {{ address_form.street_address_1|as_vertical_form }}
- </div>
- <div class="col-sm-4">
- {{ address_form.street_address_2|as_vertical_form }}
- </div>
- </div>
- <div class="row">
- <div class="col-sm-6">
- {{ address_form.city|as_vertical_form }}
- </div>
- <div class="col-sm-6">
- {{ address_form.city_area|as_vertical_form }}
- </div>
- </div>
- <div class="row">
- <div class="col-sm-8">
- {{ address_form.country_area|as_vertical_form }}
- </div>
- <div class="col-sm-4">
- {{ address_form.postal_code|as_vertical_form }}
- </div>
- </div>
- {{ address_form.country|as_vertical_form }}
- {{ address_form.phone|as_vertical_form }}
+ {% include "userprofile/snippets/address-form.html" %}
<p class="text-right">
<button type="submit" class="btn btn-primary">{% trans "Save changes" %}</button>
</p>
diff --git a/saleor/userprofile/templates/userprofile/snippets/address-form.html b/saleor/userprofile/templates/userprofile/snippets/address-form.html
new file mode 100644
index 0000000000..3b3baf790a
--- /dev/null
+++ b/saleor/userprofile/templates/userprofile/snippets/address-form.html
@@ -0,0 +1,37 @@
+{% load as_vertical_form from bootstrap %}
+
+<div class="row">
+ <div class="col-sm-6">
+ {{ address_form.first_name|as_vertical_form }}
+ </div>
+ <div class="col-sm-6">
+ {{ address_form.last_name|as_vertical_form }}
+ </div>
+</div>
+{{ address_form.company_name|as_vertical_form }}
+<div class="row">
+ <div class="col-sm-8">
+ {{ address_form.street_address_1|as_vertical_form }}
+ </div>
+ <div class="col-sm-4">
+ {{ address_form.street_address_2|as_vertical_form }}
+ </div>
+</div>
+<div class="row">
+ <div class="col-sm-6">
+ {{ address_form.city|as_vertical_form }}
+ </div>
+ <div class="col-sm-6">
+ {{ address_form.city_area|as_vertical_form }}
+ </div>
+</div>
+<div class="row">
+ <div class="col-sm-8">
+ {{ address_form.country_area|as_vertical_form }}
+ </div>
+ <div class="col-sm-4">
+ {{ address_form.postal_code|as_vertical_form }}
+ </div>
+</div>
+{{ address_form.country|as_vertical_form }}
+{{ address_form.phone|as_vertical_form }}