Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add price & weight based shipping
Pacu2a68be9e48259
diff --git a/docs/architecture.rst b/docs/architecture.rstindex 59d76c9b93..1d28deddc0 100644--- a/docs/architecture.rst+++ b/docs/architecture.rst@@ -13,6 +13,7 @@ Architecturearchitecture/translationsarchitecture/searcharchitecture/payments+ architecture/shippingsarchitecture/settingsarchitecture/pagearchitecture/gdprdiff --git a/docs/architecture/shippings.rst b/docs/architecture/shippings.rstnew file mode 100644index 0000000000..3938793529--- /dev/null+++ b/docs/architecture/shippings.rst@@ -0,0 +1,43 @@+Shippings+=========++Saleor uses the concept of Shipping Zones and Shipping Methods to fulfill the shipping process.++Shipping Zones+--------------++The countries that you ship to are known as the shipping zones. Each ``ShippingZone`` includes ``ShippingMethods`` that apply to customers whose shipping address is within the shipping zone.++Each ``ShippingZone`` can contain several countries inside, but the country might belong to a maximum of one ``ShippingZone``.++Some examples of the ``ShippingZones`` could be `European Union`, `North America`, `Germany` etc.++Shipping Methods+----------------++``ShippingMethods`` are the methods you'll use to get customers' orders to them.+You can offer several ones within one ``ShippingZone`` to ensure the varieties of delivery speed and costs at the checkout.++Each ``ShippmentMethod`` could be one of the two types:++- ``PRICE_BASED``+ Those methods can be used only when the order price is within the certain range, eg. from 0 to 50$, 50$ and up etc.++- ``WEGHT_BASED``+ Same as the ``PRICE_BASED``, but with the total order's weight in mind.++These methods allow you to cover most of the basic use cases, eg.++- Listing several methods with different prices and shipping time for different countries.++- Offering a free (or discounted) shipping on orders above certain price threshold.++- Increasing the shipping price for heavy orders.++Weight+------++Weight is used to calculate the ``WEIGHT_BASED`` shipping price.++Weight is defined on the ``ProductType`` level and can be overridden+for each ``Product`` and each ``ProductVariant`` within a ``Product``.diff --git a/requirements.in b/requirements.inindex 62c8c18b40..80e4750414 100644--- a/requirements.in+++ b/requirements.in@@ -13,6 +13,7 @@ django-filter==1.1django-fsm>=2.6.0django-graphql-jwt>=0.1.9django-impersonate>=1.3+django-measurement==3.0.0django-mptt>=0.7.1django-payments>=0.12.1django-phonenumber-field>=1.3.0diff --git a/requirements.txt b/requirements.txtindex e0e4abcced..7b21743cae 100644--- a/requirements.txt+++ b/requirements.txt@@ -8,13 +8,13 @@ amqp==2.3.2 # via kombuaniso8601==3.0.2 # via grapheneasn1crypto==0.24.0 # via cryptographyatomicwrites==1.1.5 # via pytest-attrs==17.4.0 # via pytest+attrs==18.1.0 # via pytestbabel==2.6.0billiard==3.5.0.4 # via celery-bleach==2.1.3-boto3==1.7.78-botocore==1.10.78 # via boto3, s3transfer-braintree==3.39.1 # via django-payments+bleach==2.1.4+boto3==1.7.79+botocore==1.10.79 # via boto3, s3transfer+braintree==3.47.0 # via django-paymentscairocffi==0.9.0 # via cairosvg, weasyprintcairosvg==2.1.3celery[redis]==4.2.1@@ -26,6 +26,7 @@ cssselect2==0.2.1 # via cairosvg, weasyprintdefusedxml==0.5.0 # via cairosvg, python3-openid, social-auth-coredj-database-url==0.5.0dj-email-url==0.1.0+django-appconf==1.0.2 # via django-measurementdjango-babel==0.6.2django-bootstrap4==0.0.6django-cache-url==3.0.0@@ -40,6 +41,7 @@ django-fsm==2.6.0django-graphql-jwt==0.1.10django-impersonate==1.3django-js-asset==1.1.0 # via django-mptt+django-measurement==3.0.0django-mptt==0.9.1django-payments==0.12.3django-phonenumber-field==2.0.0@@ -53,10 +55,10 @@ django-storages==1.6.6django-templated-email==2.2.0django-versatileimagefield==1.9django-webpack-loader==0.6.0-django==2.0.8+django==2.1docutils==0.14 # via botocoreelasticsearch-dsl==5.4.0-elasticsearch==5.5.2+elasticsearch==5.5.3faker==0.9.0freezegun==0.3.10google-i18n-address==2.3.2@@ -74,7 +76,9 @@ kombu==4.2.1 # via celerymarkdown==2.6.11maxminddb-geolite2==2018.703maxminddb==1.4.1+measurement==2.0.1 # via django-measurementmore-itertools==4.3.0 # via pytest+mpmath==1.0.0 # via sympymultidict==4.3.1 # via yarloauthlib==2.1.0 # via requests-oauthlib, social-auth-corepdfrw==0.4 # via weasyprint@@ -104,16 +108,17 @@ requests==2.19.1rx==1.6.1 # via graphql-cores3transfer==0.1.13 # via boto3singledispatch==3.4.0.3 # via graphene-django-six==1.11.0 # via bleach, cryptography, django-templated-email, elasticsearch-dsl, faker, freezegun, graphene, graphene-django, graphql-core, graphql-relay, html5lib, more-itertools, promise, purl, pytest, python-dateutil, singledispatch, social-auth-app-django, social-auth-core, vcrpy+six==1.11.0 # via bleach, cryptography, django-templated-email, elasticsearch-dsl, faker, freezegun, graphene, graphene-django, graphql-core, graphql-relay, html5lib, measurement, more-itertools, promise, purl, pytest, python-dateutil, singledispatch, social-auth-app-django, social-auth-core, vcrpysocial-auth-app-django==2.1.0social-auth-core==1.7.0 # via social-auth-app-djangosqlparse==0.2.4 # via django-debug-toolbar-stripe==1.77.1 # via django-payments+stripe==2.5.0 # via django-paymentssuds-jurko==0.6 # via django-payments+sympy==1.2 # via measurementtext-unidecode==1.2tinycss2==0.6.1 # via cairosvg, cssselect2, weasyprinttyping==3.6.4 # via google-measurement-protocol, prices, promise-urllib3==1.22 # via elasticsearch, requests+urllib3==1.23 # via elasticsearch, requestsuwsgi==2.0.17.1 ; platform_system != "Windows"vcrpy==1.13.0vine==1.1.4 # via amqpdiff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex 40852c2f66..716a23e951 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -12,10 +12,10 @@ from django_countries.fields import LazyTypedChoiceFieldfrom ..core.exceptions import InsufficientStockfrom ..core.i18n import COUNTRY_CODE_CHOICESfrom ..core.utils import format_money-from ..core.utils.taxes import display_gross_prices+from ..core.utils.taxes import display_gross_prices, get_taxed_shipping_pricefrom ..discount.models import NotApplicable, Voucherfrom ..shipping.models import ShippingMethod-from ..shipping.utils import get_shipment_options, get_taxed_shipping_price+from ..shipping.utils import shipping_price_estimatefrom .models import Cart@@ -46,12 +46,10 @@ class AddToCartForm(forms.Form):'Add to cart form error','Sorry. This product is currently out of stock.'),'variant-does-not-exists': pgettext_lazy(- 'Add to cart form error',- 'Oops. We could not find that product.'),+ 'Add to cart form error', 'Oops. We could not find that product.'),'insufficient-stock': npgettext_lazy('Add to cart form error',- 'Only %d remaining in stock.',- 'Only %d remaining in stock.')}+ 'Only %d remaining in stock.', 'Only %d remaining in stock.')}def __init__(self, *args, **kwargs):self.cart = kwargs.pop('cart')@@ -161,18 +159,20 @@ class ReplaceCartLineForm(AddToCartForm):class CountryForm(forms.Form):"""Country selection form."""+ country = LazyTypedChoiceField(+ label=pgettext_lazy('Country form field label', 'Country'),+ choices=COUNTRY_CODE_CHOICES)def __init__(self, *args, **kwargs):self.taxes = kwargs.pop('taxes', {})super().__init__(*args, **kwargs)- self.fields['country'] = LazyTypedChoiceField(- label=pgettext_lazy('Country form field label', 'Country'),- choices=COUNTRY_CODE_CHOICES)- def get_shipment_options(self):- """Return a list of shipping methods for the selected country."""+ def shipping_price_estimate(self, price, weight):+ """Return a shipping price range for given order for the selected+ country.+ """code = self.cleaned_data['country']- return get_shipment_options(code, self.taxes)+ return shipping_price_estimate(price, weight, code, self.taxes)class AnonymousUserShippingForm(forms.ModelForm):@@ -257,10 +257,8 @@ class ShippingMethodChoiceField(forms.ModelChoiceField):class CartShippingMethodForm(forms.ModelForm):- """Cart shipping method form."""shipping_method = ShippingMethodChoiceField(- queryset=ShippingMethod.objects.prefetch_related(- 'shipping_zone').order_by('price'),+ queryset=ShippingMethod.objects.all(),label=pgettext_lazy('Shipping method form field label', 'Shipping method'),empty_label=None)@@ -273,8 +271,10 @@ class CartShippingMethodForm(forms.ModelForm):taxes = kwargs.pop('taxes')super().__init__(*args, **kwargs)country_code = self.instance.shipping_address.country.code- qs = self.fields['shipping_method'].queryset.filter(- shipping_zone__countries__contains=country_code)+ qs = ShippingMethod.objects.applicable_shipping_methods(+ price=self.instance.get_subtotal().gross,+ weight=self.instance.get_total_weight(),+ country_code=country_code)self.fields['shipping_method'].queryset = qsself.fields['shipping_method'].taxes = taxesdiff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex abfc30c025..4396a76648 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -8,6 +8,7 @@ from django.db import modelsfrom django.utils.encoding import smart_strfrom django_prices.models import MoneyFieldfrom jsonfield import JSONField+from measurement.measures import Massfrom ..account.models import Addressfrom ..core.utils.taxes import ZERO_TAXED_MONEY@@ -94,8 +95,14 @@ class Cart(models.Model):"""Return the total cost of the cart."""return (self.get_subtotal(discounts, taxes)- + self.get_shipping_price(taxes)- - self.discount_amount)+ + self.get_shipping_price(taxes) - self.discount_amount)++ def get_total_weight(self):+ # Cannot use `sum` as it parses an empty Weight to an int+ weights = Mass(kg=0)+ for line in self:+ weights += line.variant.get_weight()+ return weightsdef get_line(self, variant):"""Return a line matching the given variant and data if any."""@@ -129,8 +136,7 @@ class CartLine(models.Model):return NotImplementedreturn (- self.variant == other.variant and- self.quantity == other.quantity)+ self.variant == other.variant and self.quantity == other.quantity)def __ne__(self, other):return not self == other # pragma: no coverdiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 8a80ca7a1c..d4da44fa57 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -25,7 +25,7 @@ from ..discount.utils import (get_products_voucher_discount, get_shipping_voucher_discount,get_value_voucher_discount, increase_voucher_usage)from ..order.models import Order-from ..shipping.models import ShippingZone+from ..shipping import ShippingMethodTypefrom .forms import (AddressChoiceForm, AnonymousUserBillingForm, AnonymousUserShippingForm,BillingAddressChoiceForm)@@ -761,27 +761,51 @@ def get_taxes_for_cart(cart, default_taxes):return default_taxes-def check_shipping_method(cart):- """Check if shipping method is valid for the cart and remove (if not)."""- country_code = cart.shipping_address.country.code- # There should be only one ShippingZone per country- valid_shipping_zone = ShippingZone.objects.filter(- countries__contains=country_code).first()+def value_in_range(minimum, maximum, value):+ """Check if value is in the certain range.+ If the maximum in None, then there's no upper limit."""+ if maximum is None:+ return value >= minimum+ return value >= minimum and value <= maximum- shipping_outside_the_shipping_zone = (- cart.shipping_method and- cart.shipping_method.shipping_zone != valid_shipping_zone)- # TODO here we should check price based shipping /weight based shipping- shipping_method_not_applicable = False- if any([- not valid_shipping_zone, shipping_outside_the_shipping_zone,- shipping_method_not_applicable]):- cart.shipping_method = None- cart.save()++def shipping_method_applicable(price, weight, method):+ """Checks if all shipping method requirements are fullfilled+ (eg. minimum order value or maximum order weight).+ """+ if method.type == ShippingMethodType.PRICE_BASED:+ return value_in_range(+ minimum=method.minimum_order_price,+ maximum=method.maximum_order_price, value=price)+ return value_in_range(+ minimum=method.minimum_order_weight,+ maximum=method.maximum_order_weight, value=weight)+++def check_shipping_method(cart, taxes, discounts):+ """Check if shipping method is valid and remove (if not)."""+ if not cart.shipping_method:return False+ shipping_outside_the_shipping_zone = (+ cart.shipping_address.country.code not in+ cart.shipping_method.shipping_zone.countries)+ if shipping_outside_the_shipping_zone:+ return clear_shipping_method(cart)++ shipping_method_is_valid = shipping_method_applicable(+ price=cart.get_subtotal(discounts, taxes).gross,+ weight=cart.get_total_weight(), method=cart.shipping_method)+ if not shipping_method_is_valid:+ return clear_shipping_method(cart)return True+def clear_shipping_method(cart):+ cart.shipping_method = None+ cart.save(update_fields=['shipping_method'])+ return False++def _process_voucher_data_for_order(cart):"""Fetch, process and return voucher/discount data from cart."""vouchers = Voucher.objects.active(date=date.today()).select_for_update()@@ -820,7 +844,8 @@ def _process_shipping_data_for_order(cart, taxes):'shipping_address': shipping_address,'shipping_method': cart.shipping_method,'shipping_method_name': smart_text(cart.shipping_method),- 'shipping_price': cart.get_shipping_price(taxes)}+ 'shipping_price': cart.get_shipping_price(taxes),+ 'weight': cart.get_total_weight()}def _process_user_data_for_order(cart):diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex 030b2a8983..e256470b17 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -7,7 +7,7 @@ from ...account.forms import LoginFormfrom ...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 ...shipping.utils import shipping_price_estimatefrom ..forms import CartShippingMethodForm, CountryForm, ReplaceCartLineFormfrom ..models import Cartfrom ..utils import (@@ -64,7 +64,7 @@ def checkout_shipping_address(request, cart):def checkout_shipping_method(request, cart):"""Display the shipping method selection step."""taxes = get_taxes_for_cart(cart, request.taxes)- check_shipping_method(cart)+ check_shipping_method(cart, request.taxes, request.discounts)form = CartShippingMethodForm(request.POST or None, taxes=taxes, instance=cart,@@ -128,14 +128,17 @@ def cart_index(request, cart):default_country = get_user_shipping_country(request)country_form = CountryForm(initial={'country': default_country})- default_country_options = get_shipment_options(default_country, taxes)+ shipping_price_range = shipping_price_estimate(+ price=cart.get_subtotal(discounts, taxes).gross,+ weight=cart.get_total_weight(), country_code=default_country,+ taxes=taxes)cart_data = get_cart_data(- cart, default_country_options, request.currency, discounts, taxes)+ cart, shipping_price_range, request.currency, discounts, taxes)ctx = {'cart_lines': cart_lines,'country_form': country_form,- 'default_country_options': default_country_options}+ 'shipping_price_range': shipping_price_range}ctx.update(cart_data)return TemplateResponse(request, 'checkout/index.html', ctx)@@ -146,14 +149,17 @@ 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()+ shipping_price_range = country_form.shipping_price_estimate(+ price=cart.get_subtotal(request.discounts, request.taxes).gross,+ weight=cart.get_total_weight())else:- shipments = None+ shipping_price_range = Nonectx = {- 'default_country_options': shipments,+ 'shipping_price_range': shipping_price_range,'country_form': country_form}cart_data = get_cart_data(- cart, shipments, request.currency, request.discounts, request.taxes)+ cart, shipping_price_range, request.currency, request.discounts,+ request.taxes)ctx.update(cart_data)return TemplateResponse(request, 'checkout/_subtotal_table.html', ctx)diff --git a/saleor/checkout/views/validators.py b/saleor/checkout/views/validators.pyindex cce64e511d..044bfa062b 100644--- a/saleor/checkout/views/validators.py+++ b/saleor/checkout/views/validators.py@@ -49,7 +49,7 @@ def validate_shipping_method(view):"""@wraps(view)def func(request, cart):- if not cart.shipping_method or not check_shipping_method(cart):+ if not check_shipping_method(cart, request.taxes, request.discounts):return redirect('checkout:shipping-method')return view(request, cart)return funcdiff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 5ab00c5a9b..4fcaba734b 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -12,6 +12,7 @@ from django.template.defaultfilters import slugifyfrom django_countries.fields import Countryfrom faker import Factoryfrom faker.providers import BaseProvider+from measurement.measures import Massfrom payments import PaymentStatusfrom prices import Money@@ -32,7 +33,7 @@ from ...product.models import (ProductImage, ProductType, ProductVariant)from ...product.thumbnails import create_product_thumbnailsfrom ...product.utils.attributes import get_name_from_attributes-from ...shipping.models import ShippingMethod, ShippingZone+from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZonefrom ...shipping.utils import get_taxed_shipping_pricefake = Factory.create()@@ -136,7 +137,8 @@ def create_product_type_with_attributes(name, schema):variant_attributes_schema = schema.get('variant_attributes', {})is_shipping_required = schema.get('is_shipping_required', True)product_type = get_or_create_product_type(- name=name, is_shipping_required=is_shipping_required)+ name=name, is_shipping_required=is_shipping_required,+ weight=fake.weight())product_attributes = create_attributes_and_values(product_attributes_schema)variant_attributes = create_attributes_and_values(@@ -241,6 +243,9 @@ class SaleorProvider(BaseProvider):return Money(fake.pydecimal(2, 2, positive=True), settings.DEFAULT_CURRENCY)+ def weight(self):+ return Mass(kg=fake.pydecimal(1, 2, positive=True))+fake.add_provider(SaleorProvider)@@ -287,7 +292,8 @@ def create_product(**kwargs):'name': fake.company(),'price': fake.money(),'description': '\n\n'.join(description),- 'seo_description': strip_html_and_truncate(description[0], 300)}+ 'seo_description': strip_html_and_truncate(description[0], 300),+ 'weight': fake.weight() if random.randint(0, 1) else None}defaults.update(kwargs)return Product.objects.create(**defaults)@@ -296,7 +302,8 @@ def create_variant(product, **kwargs):defaults = {'product': product,'quantity': fake.random_int(1, 50),- 'quantity_allocated': fake.random_int(1, 50)}+ 'quantity_allocated': fake.random_int(1, 50),+ 'weight': fake.weight() if random.randint(0, 1) else None}defaults.update(kwargs)variant = ProductVariant(**defaults)if 'cost_price' not in kwargs:@@ -461,6 +468,10 @@ def create_fake_order(discounts, taxes):order.total = sum([line.get_total() for line in lines], order.shipping_price)+ weight = Mass(kg=0)+ for line in order:+ weight += line.variant.get_weight()+ order.weight = weightorder.save()create_fulfillments(order)@@ -500,14 +511,19 @@ def create_product_sales(how_many=5):yield 'Sale: %s' % (sale,)-def create_shipping_zone(shipping_methods_names, countries, shipping_zone_name):+def create_shipping_zone(+ shipping_methods_names, countries, shipping_zone_name):shipping_zone = ShippingZone.objects.get_or_create(name=shipping_zone_name, defaults={'countries': countries})[0]- shipping_methods = [+ ShippingMethod.objects.bulk_create([ShippingMethod(- name=name, price=fake.money(), shipping_zone=shipping_zone)- for name in shipping_methods_names]- ShippingMethod.objects.bulk_create(shipping_methods)+ name=name, price=fake.money(), shipping_zone=shipping_zone,+ type=(+ ShippingMethodType.PRICE_BASED if random.randint(0, 1)+ else ShippingMethodType.WEIGHT_BASED),+ minimum_order_price=fake.money(), maximum_order_price=None,+ minimum_order_weight=fake.weight(), maximum_order_weight=None)+ for name in shipping_methods_names])return 'Shipping Zone: %s' % shipping_zonediff --git a/saleor/core/utils/taxes.py b/saleor/core/utils/taxes.pyindex 258b9c5075..f9d83f253f 100644--- a/saleor/core/utils/taxes.py+++ b/saleor/core/utils/taxes.py@@ -83,3 +83,10 @@ def display_gross_prices():def charge_taxes_on_shipping():return Site.objects.get_current().settings.charge_taxes_on_shipping+++def get_taxed_shipping_price(shipping_price, taxes):+ """Calculate shipping price based on settings and taxes."""+ if not charge_taxes_on_shipping():+ taxes = None+ return apply_tax_to_price(taxes, DEFAULT_TAX_RATE_NAME, shipping_price)diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 07dd290323..0dfb4f7fd1 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -147,7 +147,6 @@ class OrderRemoveCustomerForm(forms.ModelForm):class OrderShippingForm(forms.ModelForm):"""Set shipping name and shipping price in an order."""- #FIXMEshipping_method = AjaxSelect2ChoiceField(queryset=ShippingMethod.objects.all(), min_input=0,label=pgettext_lazy(diff --git a/saleor/dashboard/shipping/forms.py b/saleor/dashboard/shipping/forms.pyindex c6fce3e0db..010b65d866 100644--- a/saleor/dashboard/shipping/forms.py+++ b/saleor/dashboard/shipping/forms.py@@ -1,7 +1,8 @@from django import formsfrom django.utils.translation import pgettext_lazy-from ...shipping.models import ShippingZone, ShippingMethod+from ...shipping import ShippingMethodType+from ...shipping.models import ShippingMethod, ShippingZonedef currently_used_countries(shipping_zone_pk=None):@@ -19,8 +20,7 @@ class ShippingZoneForm(forms.ModelForm):model = ShippingZoneexclude = ['shipping_methods']labels = {- 'name': pgettext_lazy(- 'Shippment Zone field name', 'Zone Name'),+ 'name': pgettext_lazy('Shippment Zone field name', 'Zone Name'),'countries': pgettext_lazy('List of countries to pick from', 'Countries')}help_texts = {@@ -39,7 +39,6 @@ class ShippingZoneForm(forms.ModelForm):self.instance.pk if self.instance else None))def clean_countries(self):- #TODO testmecountries = self.cleaned_data.get('countries')if not countries:return@@ -50,7 +49,7 @@ class ShippingZoneForm(forms.ModelForm):'countries','Countries already exists in another ''shipping zone: %(list_of_countries)s' % {- 'list_of_countries': ''.join(duplicated_countries)})+ 'list_of_countries': ', '.join(duplicated_countries)})return countries@@ -58,11 +57,25 @@ class ShippingMethodForm(forms.ModelForm):class Meta:model = ShippingMethod- exclude = ['shipping_zone']+ exclude = ['shipping_zone', 'type']labels = {+ 'name': pgettext_lazy('Shipping Method name', 'Name'),+ 'price': pgettext_lazy('Currency amount', 'Price')}+ help_texts = {'name': pgettext_lazy(- 'Shipping Method name', 'Name'),- 'type': pgettext_lazy(- 'Shipping Method type', 'Type'),- 'price': pgettext_lazy(- 'Currency amount', 'Price')}+ 'Shipping method name help text',+ 'Customers will see this at the checkout.')}++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ if self.instance.type == ShippingMethodType.WEIGHT_BASED:+ del self.fields['minimum_order_price']+ del self.fields['maximum_order_price']+ else:+ del self.fields['minimum_order_weight']+ del self.fields['maximum_order_weight']+ self.fields['minimum_order_price'].required = False+ self.fields['maximum_order_price'].widget.attrs['placeholder'] = \+ pgettext_lazy(+ 'Placeholder for maximum order price set to unlimited',+ 'No limit')diff --git a/saleor/dashboard/shipping/urls.py b/saleor/dashboard/shipping/urls.pyindex 14ed62eb6b..33f7b9b922 100644--- a/saleor/dashboard/shipping/urls.py+++ b/saleor/dashboard/shipping/urls.py@@ -12,9 +12,9 @@ urlpatterns = [url(r'^(?P<pk>\d+)/delete/$',views.shipping_zone_delete, name='shipping-zone-delete'),- url(r'^(?P<shipping_zone_pk>\d+)/shipping_method/add/$',+ url(r'^(?P<shipping_zone_pk>\d+)/shipping/add/(?P<type>price|weight)/$',views.shipping_method_add, name='shipping-method-add'),- url(r'^(?P<shipping_zone_pk>\d+)/shipping_method/(?P<shipping_method_pk>\d+)/update/$',+ url(r'^(?P<shipping_zone_pk>\d+)/shipping/(?P<shipping_method_pk>\d+)/update/$', # noqaviews.shipping_method_edit, name='shipping-method-edit'),- url(r'^(?P<shipping_zone_pk>\d+)/shipping_method/(?P<shipping_method_pk>\d+)/delete/$',+ url(r'^(?P<shipping_zone_pk>\d+)/shipping/(?P<shipping_method_pk>\d+)/delete/$', # noqaviews.shipping_method_delete, name='shipping-method-delete')]diff --git a/saleor/dashboard/shipping/views.py b/saleor/dashboard/shipping/views.pyindex f085a93ef2..6bab671ec7 100644--- a/saleor/dashboard/shipping/views.py+++ b/saleor/dashboard/shipping/views.py@@ -60,8 +60,11 @@ def shipping_zone_edit(request, pk):@permission_required('shipping.manage_shipping')def shipping_zone_details(request, pk):zone = get_object_or_404(ShippingZone, pk=pk)- shipping_methods = zone.shipping_methods.all()- ctx = {'shipping_zone': zone, 'shipping_methods': shipping_methods}+ price_based = zone.shipping_methods.price_based()+ weight_based = zone.shipping_methods.weight_based()+ ctx = {+ 'shipping_zone': zone, 'price_based': price_based,+ 'weight_based': weight_based}return TemplateResponse(request, 'dashboard/shipping/detail.html', ctx)@@ -85,9 +88,10 @@ def shipping_zone_delete(request, pk):@staff_member_required@permission_required('shipping.manage_shipping')-def shipping_method_add(request, shipping_zone_pk):+def shipping_method_add(request, shipping_zone_pk, type):shipping_zone = get_object_or_404(ShippingZone, pk=shipping_zone_pk)- shipping_method = ShippingMethod(shipping_zone_id=shipping_zone_pk)+ shipping_method = ShippingMethod(+ shipping_zone_id=shipping_zone_pk, type=type)form = ShippingMethodForm(request.POST or None, instance=shipping_method)if form.is_valid():shipping_method = form.save()@@ -101,7 +105,7 @@ def shipping_method_add(request, shipping_zone_pk):'form': form, 'shipping_zone': shipping_zone,'shipping_method': shipping_method}return TemplateResponse(- request, 'dashboard/shipping/rate/form.html', ctx)+ request, 'dashboard/shipping/methods/form.html', ctx)@staff_member_required@@ -110,7 +114,8 @@ def shipping_method_edit(request, shipping_zone_pk, shipping_method_pk):shipping_zone = get_object_or_404(ShippingZone, pk=shipping_zone_pk)shipping_method = get_object_or_404(ShippingMethod, pk=shipping_method_pk)- form = ShippingMethodForm(request.POST or None, instance=shipping_method)+ form = ShippingMethodForm(+ request.POST or None, instance=shipping_method)if form.is_valid():country = form.save()msg = pgettext_lazy(@@ -123,7 +128,7 @@ def shipping_method_edit(request, shipping_zone_pk, shipping_method_pk):'form': form, 'shipping_zone': shipping_zone,'shipping_method': shipping_method}return TemplateResponse(- request, 'dashboard/shipping/rate/form.html', ctx)+ request, 'dashboard/shipping/methods/form.html', ctx)@staff_member_requireddiff --git a/saleor/order/models.py b/saleor/order/models.pyindex 55924d8ab2..b6686ee8e9 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -9,7 +9,9 @@ from django.db.models import F, Max, Sumfrom django.urls import reversefrom django.utils.timezone import nowfrom django.utils.translation import pgettext_lazy+from django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField, TaxedMoneyField+from measurement.measures import Weightfrom payments import PaymentStatus, PurchasedItemfrom payments.models import BasePaymentfrom prices import Money, TaxedMoney@@ -92,7 +94,9 @@ class Order(models.Model):max_length=255, default='', blank=True)display_gross_prices = models.BooleanField(default=True)customer_note = models.TextField(blank=True, default='')-+ weight = MeasurementField(+ measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,+ default=0)objects = OrderQueryset.as_manager()class Meta:diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex b90efa97c5..6bb0df8d1f 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -83,11 +83,11 @@ def update_order_prices(order, discounts):line.unit_price = line.variant.get_price(discounts, taxes)line.tax_rate = get_tax_rate_by_name(line.variant.product.tax_rate, taxes)- line.save()+ line.save(update_fields=['unit_price', 'tax_rate'])if order.shipping_method:order.shipping_price = order.shipping_method.get_total_price(taxes)- order.save()+ order.save(update_fields=['shipping_price'])recalculate_order(order)@@ -182,7 +182,7 @@ def change_order_line_quantity(line, new_quantity):"""Change the quantity of ordered items in a order line."""if new_quantity:line.quantity = new_quantity- line.save()+ line.save(update_fields=['quantity'])else:line.delete()diff --git a/saleor/product/models.py b/saleor/product/models.pyindex c5ee1e63f0..05732e2794 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -10,8 +10,10 @@ from django.urls import reversefrom django.utils.encoding import smart_textfrom django.utils.text import slugifyfrom django.utils.translation import pgettext_lazy+from django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyFieldfrom django_prices.templatetags import prices_i18n+from measurement.measures import Weightfrom mptt.managers import TreeManagerfrom mptt.models import MPTTModelfrom prices import TaxedMoneyRange@@ -78,6 +80,9 @@ class ProductType(models.Model):is_shipping_required = models.BooleanField(default=False)tax_rate = models.CharField(max_length=128, default=DEFAULT_TAX_RATE_NAME, blank=True)+ weight = MeasurementField(+ measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,+ default=0)class Meta:app_label = 'product'@@ -116,6 +121,9 @@ class Product(SeoModel):charge_taxes = models.BooleanField(default=True)tax_rate = models.CharField(max_length=128, default=DEFAULT_TAX_RATE_NAME, blank=True)+ weight = MeasurementField(+ measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,+ blank=True, null=True)objects = ProductQuerySet.as_manager()translated = TranslationProxy()@@ -210,7 +218,9 @@ class ProductVariant(models.Model):cost_price = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES, blank=True, null=True)-+ weight = MeasurementField(+ measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,+ blank=True, null=True)translated = TranslationProxy()class Meta:@@ -243,6 +253,11 @@ class ProductVariant(models.Model):self.product.tax_rate or self.product.product_type.tax_rate)return apply_tax_to_price(taxes, tax_rate, price)+ def get_weight(self):+ return (+ self.weight or self.product.weight or+ self.product.product_type.weight)+def get_absolute_url(self):slug = self.product.get_slug()product_id = self.product.iddiff --git a/saleor/settings.py b/saleor/settings.pyindex e4922189d2..3b2b02d640 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -218,6 +218,7 @@ INSTALLED_APPS = ['versatileimagefield','django_babel','bootstrap4',+ 'django_measurement','django_prices','django_prices_openexchangerates','django_prices_vatlayer',@@ -309,6 +310,7 @@ LOGIN_URL = '/account/login/'DEFAULT_COUNTRY = os.environ.get('DEFAULT_COUNTRY', 'US')DEFAULT_CURRENCY = os.environ.get('DEFAULT_CURRENCY', 'USD')DEFAULT_DECIMAL_PLACES = get_currency_fraction(DEFAULT_CURRENCY)+DEFAULT_WEIGHT_UNITS = [('kg', 'kg'), ('lb', 'lb')]AVAILABLE_CURRENCIES = [DEFAULT_CURRENCY]COUNTRIES_OVERRIDE = {'EU': pgettext_lazy(diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex f3a15b95cf..c2399f4c8a 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -1,14 +1,41 @@from django.conf import settingsfrom django.db import models+from django.db.models import Qfrom django.utils.safestring import mark_safefrom django.utils.translation import pgettext_lazyfrom django_countries.fields import CountryField+from django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField+from measurement.measures import Weightfrom prices import MoneyRangefrom . import ShippingMethodTypefrom ..core.utils import format_money-from ..shipping.utils import get_taxed_shipping_price+from ..core.utils.taxes import get_taxed_shipping_price+++def applicable_weight_based_methods(weight, qs):+ """Returns weight based ShippingMethods that can be applied to an order+ with given total weight.+ """+ qs = qs.weight_based()+ min_weight_matched = Q(minimum_order_weight__lte=weight)+ no_weight_limit = Q(maximum_order_weight__isnull=True)+ max_weight_matched = Q(maximum_order_weight__gte=weight)+ return qs.filter(+ min_weight_matched & (no_weight_limit | max_weight_matched))+++def applicable_price_based_methods(price, qs):+ """Returns price based ShippingMethods that can be applied to an order+ with given price total.+ """+ qs = qs.price_based()+ min_price_matched = Q(minimum_order_price__lte=price)+ no_price_limit = Q(maximum_order_price__isnull=True)+ max_price_matched = Q(maximum_order_price__gte=price)+ return qs.filter(+ min_price_matched & (no_price_limit | max_price_matched))class ShippingZone(models.Model):@@ -41,21 +68,67 @@ class ShippingZone(models.Model):'Permission description', 'Manage shipping.')),)+class ShippingMethodQueryset(models.QuerySet):+ def price_based(self):+ return self.filter(type=ShippingMethodType.PRICE_BASED)++ def weight_based(self):+ return self.filter(type=ShippingMethodType.WEIGHT_BASED)++ def applicable_shipping_methods(self, price, weight, country_code):+ """Returns ShippingMethods that can be used on an order with+ shippment to given country(code), that are applicable to given+ price & weight total.+ """+ qs = self.prefetch_related('shipping_zone').order_by('price')+ qs = qs.filter(shipping_zone__countries__contains=country_code)+ price_based_methods = applicable_price_based_methods(price, qs)+ weight_based_methods = applicable_weight_based_methods(+ weight, qs)+ return price_based_methods | weight_based_methods++class ShippingMethod(models.Model):name = models.CharField(max_length=100)- type = models.CharField(- max_length=30, choices=ShippingMethodType.CHOICES,- default=ShippingMethodType.WEIGHT_BASED)+ type = models.CharField(max_length=30, choices=ShippingMethodType.CHOICES)price = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)shipping_zone = models.ForeignKey(ShippingZone, related_name='shipping_methods',on_delete=models.CASCADE)+ minimum_order_price = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0, blank=True)+ maximum_order_price = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES, blank=True, null=True)+ minimum_order_weight = MeasurementField(+ measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,+ default=0)+ maximum_order_weight = MeasurementField(+ measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,+ blank=True, null=True)++ objects = ShippingMethodQueryset.as_manager()def __str__(self):return self.name+ def __repr__(self):+ if self.type == ShippingMethodType.PRICE_BASED:+ minimum = '%s%s' % (+ self.minimum_order_price.amount,+ self.minimum_order_price.currency)+ max_price = self.maximum_order_price+ maximum = (+ '%s%s' % (max_price.amount, max_price.currency)+ if max_price else 'no limit')+ return 'ShippingMethod(type=%s min=%s, max=%s)' % (+ self.type, minimum, maximum)+ return 'ShippingMethod(type=%s weight_range=(%s)' % (+ self.type, self.get_weight_type_display())+def get_total_price(self, taxes=None):return get_taxed_shipping_price(self.price, taxes)@@ -63,3 +136,33 @@ class ShippingMethod(models.Model):price_html = format_money(self.price)label = mark_safe('%s %s' % (self, price_html))return label++ def get_weight_type_display(self):+ if self.maximum_order_weight is None:+ return pgettext_lazy(+ 'Applies to orders heavier than the threshold',+ '%(minimum_order_weight)s and up') % {+ 'minimum_order_weight': self.minimum_order_weight}+ return pgettext_lazy(+ 'Applies to orders of total weight within this range',+ '%(minimum_order_weight)s to %(maximum_order_weight)s' % {+ 'minimum_order_weight': self.minimum_order_weight,+ 'maximum_order_weight': self.maximum_order_weight})++ def get_price_type_display(self):+ if self.maximum_order_price is None:+ return pgettext_lazy(+ 'Applies to orders more expensive than the min value',+ '%(minimum_order_price)s and up') % {+ 'minimum_order_price': format_money(+ self.minimum_order_price)}+ return pgettext_lazy(+ 'Applies to order valued within this price range',+ '%(minimum_order_price)s to %(maximum_order_price)s') % {+ 'minimum_order_price': format_money(self.minimum_order_price),+ 'maximum_order_price': format_money(self.maximum_order_price)}++ def get_type_display(self):+ if self.type == ShippingMethodType.PRICE_BASED:+ return self.get_price_type_display()+ return self.get_weight_type_display()diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex a07ef32f89..88c7af2949 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -1,25 +1,16 @@from prices import MoneyRange-from ..core.utils.taxes import (- DEFAULT_TAX_RATE_NAME, apply_tax_to_price, charge_taxes_on_shipping)+from ..core.utils.taxes import get_taxed_shipping_price+from .models import ShippingMethod-def get_taxed_shipping_price(price, taxes):- """Calculate shipping price based on settings and taxes."""- charge_taxes = charge_taxes_on_shipping()- if not charge_taxes:- taxes = None- return apply_tax_to_price(taxes, DEFAULT_TAX_RATE_NAME, price)---def get_shipment_options(country_code, taxes):- from .models import ShippingMethod- shipping_methods = ShippingMethod.objects.prefetch_related(- 'shipping_zone')- shipping_methods = shipping_methods.filter(- shipping_zone__countries__contains=country_code)- if shipping_methods:- shipping_methods = shipping_methods.values_list('price', flat=True)- prices = MoneyRange(- start=min(shipping_methods), stop=max(shipping_methods))- return get_taxed_shipping_price(prices, taxes)+def shipping_price_estimate(price, weight, country_code, taxes):+ """Returns estimated price range for shipping for given order."""+ shipping_methods = ShippingMethod.objects.applicable_shipping_methods(+ price, weight, country_code)+ shipping_methods = shipping_methods.values_list('price', flat=True)+ if not shipping_methods:+ return+ prices = MoneyRange(+ start=min(shipping_methods), stop=max(shipping_methods))+ return get_taxed_shipping_price(prices, taxes)diff --git a/templates/checkout/_subtotal_table.html b/templates/checkout/_subtotal_table.htmlindex 848b110d5e..04a9a4c1a8 100644--- a/templates/checkout/_subtotal_table.html+++ b/templates/checkout/_subtotal_table.html@@ -39,8 +39,8 @@<div class="row"><div class="col-md-12 col-12 text-right"><p class="cart__delivery-info__price">- {% if default_country_options %}- {% price_range default_country_options %}+ {% if shipping_price_range %}+ {% price_range shipping_price_range %}{% endif %}</p></div>diff --git a/templates/dashboard/order/modal/edit_shipping.html b/templates/dashboard/order/modal/edit_shipping.htmlindex b15aaea586..8f0a0496db 100644--- a/templates/dashboard/order/modal/edit_shipping.html+++ b/templates/dashboard/order/modal/edit_shipping.html@@ -13,7 +13,7 @@{% block content %}<div class="col s12">- {{ form.shipping_zone|materializecss }}+ {{ form.shipping_method|materializecss }}</div>{% endblock %}diff --git a/templates/dashboard/shipping/detail.html b/templates/dashboard/shipping/detail.htmlindex decbecd97e..d80d6a7319 100644--- a/templates/dashboard/shipping/detail.html+++ b/templates/dashboard/shipping/detail.html@@ -1,8 +1,6 @@{% extends 'dashboard/base.html' %}{% load i18n %}-{% load price from taxed_prices %}-{% load staticfiles %}{% block title %}{{ shipping_zone }} - {{ block.super }}@@ -53,54 +51,9 @@</div></div></div>-- <div class="col m12 l9">- <div class="card">- <div class="card-content">- <span class="card-title">- {% trans "Shipping methods" context "Title of the per-country shipping price list" %}- </span>- </div>- <div class="data-table-header-action">- <a href="{% url 'dashboard:shipping-method-add' shipping_zone_pk=shipping_zone.pk %}" class="btn-data-table btn-flat waves-effect">- {% trans "Add" %}- </a>- </div>- <div class="data-table-container">- <table class="bordered highlight responsive data-table">- <thead>- <tr>- <th>- {% trans "Name" context "Header of the per-country shipping price list" %}- </th>- <th>- {% trans "Price" context "Header of the per-country shipping price list" %}- </th>- </tr>- </thead>- <tbody>- {% for country in shipping_methods %}- <tr>- <td>{{ country.name }}</td>- <td>{% price country.price %}</td>- <td class="right-align">- <a href="{% url 'dashboard:shipping-method-edit' shipping_zone_pk=shipping_zone.pk shipping_method_pk=country.pk %}" class="btn-flat waves-effect">- {% trans 'Edit' context 'Attribute choice value edit action' %}- </a>- <a class="btn-flat waves-effect modal-trigger-custom" href="#base-modal" data-href="{% url 'dashboard:shipping-method-delete' shipping_zone_pk=shipping_zone.pk shipping_method_pk=country.pk %}">- {% trans 'Remove' context 'Attribute choice value remove action' %}- </a>- </td>- </tr>- {% empty %}- <tr>- <td colspan="2">{% trans "No shipping prices" context "Empty list of per-country shipping prices" %}</td>- </tr>- {% endfor %}- </tbody>- </table>- </div>- </div>- </div>+ {% trans "Price based shipping" context "Title of the shipping methods list" as price_based_header %}+ {% trans "Weight based shipping" context "Title of the shipping methods list" as weight_based_header %}+ {% include "dashboard/shipping/methods/_shipping_methods_table.html" with type='price' header=price_based_header shipping_methods=price_based %}+ {% include "dashboard/shipping/methods/_shipping_methods_table.html" with type='weight' header=weight_based_header shipping_methods=weight_based %}</div>{% endblock %}diff --git a/templates/dashboard/shipping/methods/_shipping_methods_table.html b/templates/dashboard/shipping/methods/_shipping_methods_table.htmlnew file mode 100644index 0000000000..62e2efbb63--- /dev/null+++ b/templates/dashboard/shipping/methods/_shipping_methods_table.html@@ -0,0 +1,55 @@+{% load i18n %}+{% load price from taxed_prices %}++<div class="col m12 l9">+ <div class="card">+ <div class="card-content">+ <span class="card-title">+ {{ header }}+ </span>+ </div>+ <div class="data-table-header-action">+ <a href="{% url 'dashboard:shipping-method-add' type=type shipping_zone_pk=shipping_zone.pk %}" class="btn-data-table btn-flat waves-effect">+ {% trans "Add" %}+ </a>+ </div>+ <div class="data-table-container">+ <table class="bordered highlight responsive data-table">+ <thead>+ <tr>+ <th>+ {% trans "Name" context "Header of the shipping methods list" %}+ </th>+ <th>+ {% trans "Range" context "Header of the shipping methods list" %}+ </th>+ <th>+ {% trans "Price" context "Header of the shipping methods list" %}+ </th>+ </tr>+ </thead>+ <tbody>+ {% for shipping in shipping_methods %}+ <tr>+ <td>{{ shipping.name }}</td>+ <td>{{ shipping.get_type_display }}</td>+ <td>{% price shipping.price %}</td>+ <td class="right-align">+ <a href="{% url 'dashboard:shipping-method-edit' shipping_zone_pk=shipping_zone.pk shipping_method_pk=shipping.pk %}" class="btn-flat waves-effect">+ {% trans 'Edit' context 'Attribute choice value edit action' %}+ </a>+ <a class="btn-flat waves-effect modal-trigger-custom" href="#base-modal" data-href="{% url 'dashboard:shipping-method-delete' shipping_zone_pk=shipping_zone.pk shipping_method_pk=shipping.pk %}">+ {% trans 'Remove' context 'Attribute choice value remove action' %}+ </a>+ </td>+ </tr>+ {% empty %}+ <tr>+ <td colspan="2">{% trans "No shipping methods" context "Empty list of shipping methods prices" %}</td>+ </tr>+ {% endfor %}+ </tbody>+ </table>+ </div>+ </div>+</div>diff --git a/templates/dashboard/shipping/rate/form.html b/templates/dashboard/shipping/methods/form.htmlsimilarity index 100%rename from templates/dashboard/shipping/rate/form.htmlrename to templates/dashboard/shipping/methods/form.htmldiff --git a/tests/dashboard/test_shipping.py b/tests/dashboard/test_shipping.pyindex 52d31f3aed..48df506229 100644--- a/tests/dashboard/test_shipping.py+++ b/tests/dashboard/test_shipping.py@@ -1,8 +1,32 @@from django.urls import reversefrom prices import Money--from saleor.shipping.models import ShippingZone, ShippingMethod+from saleor.dashboard.shipping.forms import (+ ShippingMethodForm, ShippingZoneForm, currently_used_countries)from saleor.shipping import ShippingMethodType+from saleor.shipping.models import ShippingMethod, ShippingZone+++def test_currently_used_countries():+ zone_1 = ShippingZone.objects.create(name='Zone 1', countries=['PL'])+ zone_2 = ShippingZone.objects.create(name='Zone 2', countries=['DE'])+ result = currently_used_countries(zone_1.pk)+ assert list(result)[0][0] == 'DE'+++def test_shipping_zone_form():+ zone_1 = ShippingZone.objects.create(name='Zone 1', countries=['PL'])+ zone_2 = ShippingZone.objects.create(name='Zone 2', countries=['DE'])+ form = ShippingZoneForm(+ instance=zone_1, data={'name': 'Zone 1', 'countries': ['PL']})++ assert 'DE' not in [+ code for code, name in form.fields['countries'].choices]+ assert form.is_valid()++ form = ShippingZoneForm(+ instance=zone_1, data={'name': 'Zone 2', 'countries': ['DE']})+ assert not form.is_valid()+ assert 'countries' in form.errorsdef test_shipping_zone_list(admin_client, shipping_zone):@@ -59,8 +83,9 @@ def test_shipping_zone_delete(admin_client, shipping_zone):def test_shipping_method_add(admin_client, shipping_zone):assert ShippingMethod.objects.count() == 1- url = reverse('dashboard:shipping-method-add',- kwargs={'shipping_zone_pk': shipping_zone.pk})+ url = reverse(+ 'dashboard:shipping-method-add', kwargs={+ 'shipping_zone_pk': shipping_zone.pk, 'type': 'price'})data = {'name': 'DHL', 'price': '50', 'shipping_zone': shipping_zone.pk,'type': ShippingMethodType.PRICE_BASED}@@ -71,8 +96,9 @@ def test_shipping_method_add(admin_client, shipping_zone):def test_shipping_method_add_not_valid(admin_client, shipping_zone):assert ShippingMethod.objects.count() == 1- url = reverse('dashboard:shipping-method-add',- kwargs={'shipping_zone_pk': shipping_zone.pk})+ url = reverse(+ 'dashboard:shipping-method-add', kwargs={+ 'shipping_zone_pk': shipping_zone.pk, 'type': 'price'})data = {}response = admin_client.post(url, data, follow=True)assert response.status_code == 200diff --git a/tests/test_cart.py b/tests/test_cart.pyindex 63746d1e21..a53a66c772 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -19,7 +19,7 @@ from saleor.checkout.views import update_cart_line, clear_cartfrom saleor.core.exceptions import InsufficientStockfrom saleor.core.utils.taxes import ZERO_TAXED_MONEYfrom saleor.discount.models import Sale-from saleor.shipping.utils import get_shipment_options+from saleor.shipping.utils import shipping_price_estimate@pytest.fixture()@@ -627,7 +627,7 @@ def test_get_or_create_db_cart(customer_user, db, rf):def test_get_cart_data(request_cart_with_item, shipping_zone, vatlayer):- shipment_option = get_shipment_options('PL', vatlayer)+ shipment_option = shipping_price_estimate('PL', vatlayer)cart_data = utils.get_cart_data(request_cart_with_item, shipment_option, 'USD', None, vatlayer)assert cart_data['cart_total'] == TaxedMoney(@@ -637,7 +637,7 @@ def test_get_cart_data(request_cart_with_item, shipping_zone, vatlayer):def test_get_cart_data_no_shipping(request_cart_with_item, vatlayer):- shipment_option = get_shipment_options('PL', vatlayer)+ shipment_option = shipping_price_estimate('PL', vatlayer)cart_data = utils.get_cart_data(request_cart_with_item, shipment_option, 'USD', None, vatlayer)cart_total = cart_data['cart_total']diff --git a/tests/test_shipping.py b/tests/test_shipping.pyindex 5765abe415..86f2fdedf2 100644--- a/tests/test_shipping.py+++ b/tests/test_shipping.py@@ -4,7 +4,13 @@ import pytestfrom prices import Money, TaxedMoneyfrom saleor.core.utils import format_money-from saleor.shipping.utils import get_taxed_shipping_price+from saleor.core.utils.taxes import get_taxed_shipping_price+from saleor.shipping.models import ShippingMethod, ShippingMethodType+from measurement.measures import Mass+++def money(amount):+ return Money(amount, 'USD')@pytest.mark.parametrize('price, charge_taxes, expected_price', [@@ -41,3 +47,84 @@ def test_shipping_get_ajax_label(shipping_zone):'shipping_method': shipping_method,'price': format_money(shipping_method.price)}assert label == proper_label+++ 'price, min_price, max_price, shipping_included', (+ (money(10), money(10), money(20), True), # price equal min price+ (money(10), money(1), money(10), True), # price equal max price+ (money(9), money(10), money(15), False), # price just below min price+ (money(10), money(1), money(9), False), # price just above max price+ (money(10000000), money(1), None, True), # no max price limit+ (money(10), money(5), money(15), True))) # regular case+def test_applicable_shipping_methods_price(+ shipping_zone, price, min_price, max_price, shipping_included):+ method = shipping_zone.shipping_methods.create(+ minimum_order_price=min_price, maximum_order_price=max_price,+ type=ShippingMethodType.PRICE_BASED)+ assert 'PL' in shipping_zone.countries+ result = ShippingMethod.objects.applicable_shipping_methods(+ price=price, weight=Mass(kg=0), country_code='PL')+ assert (method in result) == shipping_included+++ 'weight, min_weight, max_weight, shipping_included', (+ (Mass(kg=1), Mass(kg=1), Mass(kg=2), True), # equal min weight+ (Mass(kg=10), Mass(kg=1), Mass(kg=10), True), # equal max weight+ (Mass(kg=5), Mass(kg=8), Mass(kg=15), False), # below min weight+ (Mass(kg=10), Mass(kg=1), Mass(kg=9), False), # above max weight+ (Mass(kg=10000000), Mass(kg=1), None, True), # no max weight limit+ (Mass(kg=10), Mass(kg=5), Mass(kg=15), True))) # regular case+def test_applicable_shipping_methods_weight(+ weight, min_weight, max_weight, shipping_included, shipping_zone):+ method = shipping_zone.shipping_methods.create(+ minimum_order_weight=min_weight, maximum_order_weight=max_weight,+ type=ShippingMethodType.WEIGHT_BASED)+ assert 'PL' in shipping_zone.countries+ result = ShippingMethod.objects.applicable_shipping_methods(+ price=money(0), weight=weight, country_code='PL')+ assert (method in result) == shipping_included+++def test_applicable_shipping_methods_country_code_outside_shipping_zone(+ shipping_zone):+ method = shipping_zone.shipping_methods.create(+ minimum_order_price=money(1), maximum_order_price=money(10),+ type=ShippingMethodType.PRICE_BASED)+ shipping_zone.countries = ['DE']+ shipping_zone.save()+ result = ShippingMethod.objects.applicable_shipping_methods(+ price=money(5), weight=Mass(kg=0), country_code='PL')+ assert method not in result+++def test_applicable_shipping_methods_proper_shipping_method_type(+ shipping_zone):+ """Case when shipping suits the price requirements of the weight type+ shipping method and the other way around.+ """+ price_method = shipping_zone.shipping_methods.create(+ minimum_order_price=money(1), maximum_order_price=money(10),+ minimum_order_weight=Mass(kg=100),+ type=ShippingMethodType.WEIGHT_BASED)+ weight_method = shipping_zone.shipping_methods.create(+ minimum_order_weight=Mass(kg=1), maximum_order_weight=Mass(kg=10),+ minimum_order_price=1000, type=ShippingMethodType.PRICE_BASED)+ result = ShippingMethod.objects.applicable_shipping_methods(+ price=money(5), weight=Mass(kg=5), country_code='PL')+ assert price_method not in result+ assert weight_method not in result+++def test_applicable_shipping_methods(shipping_zone):+ price_method = shipping_zone.shipping_methods.create(+ minimum_order_price=money(1), maximum_order_price=money(10),+ type=ShippingMethodType.PRICE_BASED)+ weight_method = shipping_zone.shipping_methods.create(+ minimum_order_weight=Mass(kg=1), maximum_order_weight=Mass(kg=10),+ type=ShippingMethodType.WEIGHT_BASED)+ result = ShippingMethod.objects.applicable_shipping_methods(+ price=money(5), weight=Mass(kg=5), country_code='PL')+ assert price_method in result+ assert weight_method in result