Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Rework checkout process to use ShippingZones
Pacu241fa3a1300f9
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex 4351adeafc..5bb1c10dd2 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -7,13 +7,13 @@ from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExistfrom django.utils.encoding import smart_textfrom django.utils.safestring import mark_safefrom django.utils.translation import npgettext_lazy, pgettext_lazy-from django_countries.fields import LazyTypedChoiceField, countries+from django_countries.fields import LazyTypedChoiceFieldfrom ..core.exceptions import InsufficientStockfrom ..core.utils import format_moneyfrom ..core.utils.taxes import display_gross_pricesfrom ..discount.models import NotApplicable, Voucher-from ..shipping.models import ShippingMethodCountry+from ..shipping.models import ShippingRatefrom ..shipping.utils import get_shipment_options, get_taxed_shipping_pricefrom .models import Cart@@ -161,13 +161,14 @@ class ReplaceCartLineForm(AddToCartForm):class CountryForm(forms.Form):"""Country selection form."""- country = LazyTypedChoiceField(- label=pgettext_lazy('Country form field label', 'Country'),- choices=countries)-def __init__(self, *args, **kwargs):+ from ..shipping.utils import country_choices+self.taxes = kwargs.pop('taxes', {})super().__init__(*args, **kwargs)+ self.fields['country'] = LazyTypedChoiceField(+ label=pgettext_lazy('Country form field label', 'Country'),+ choices=country_choices())def get_shipment_options(self):"""Return a list of shipping methods for the selected country."""@@ -252,19 +253,18 @@ class ShippingCountryMethodChoiceField(forms.ModelChoiceField):else:price = price.netprice_html = format_money(price)- label = mark_safe('%s %s' % (obj.shipping_method, price_html))+ label = mark_safe('%s %s' % (obj.name, price_html))return label-class CartShippingMethodForm(forms.ModelForm):+class CartShippingRateForm(forms.ModelForm):"""Cart shipping method form."""-shipping_method = ShippingCountryMethodChoiceField(- queryset=ShippingMethodCountry.objects.select_related(- 'shipping_method').order_by('price').all(),+ queryset=ShippingRate.objects.prefetch_related(+ 'shipping_zone').order_by('price'),label=pgettext_lazy('Shipping method form field label', 'Shipping method'),- required=True)+ empty_label=None)class Meta:model = Cart@@ -273,19 +273,16 @@ class CartShippingMethodForm(forms.ModelForm):def __init__(self, *args, **kwargs):taxes = kwargs.pop('taxes')super().__init__(*args, **kwargs)- method_field = self.fields['shipping_method']- method_field.taxes = taxes-country_code = self.instance.shipping_address.country.code- if country_code:- queryset = method_field.queryset- method_field.queryset = queryset.unique_for_country_code(- country_code)+ qs = self.fields['shipping_method'].queryset.filter(+ shipping_zone__countries__contains=country_code)+ self.fields['shipping_method'].queryset = qs+ self.fields['shipping_method'].taxes = taxesif self.initial.get('shipping_method') is None:- self.initial['shipping_method'] = method_field.queryset.first()-- method_field.empty_label = None+ shipping_methods = qs.all()+ if shipping_methods:+ self.initial['shipping_method'] = shipping_methods[0]class CartNoteForm(forms.ModelForm):diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex c5e476f235..54af7ae6eb 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -11,7 +11,7 @@ from jsonfield import JSONFieldfrom ..account.models import Addressfrom ..core.utils.taxes import ZERO_TAXED_MONEY-from ..shipping.models import ShippingMethodCountry+from ..shipping.models import ShippingRateCENTS = Decimal('0.01')@@ -50,7 +50,7 @@ class Cart(models.Model):Address, related_name='+', editable=False, null=True,on_delete=models.SET_NULL)shipping_method = models.ForeignKey(- ShippingMethodCountry, blank=True, null=True, related_name='carts',+ ShippingRate, blank=True, null=True, related_name='carts',on_delete=models.SET_NULL)note = models.TextField(blank=True, default='')discount_amount = MoneyField(diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 66863cf52c..7d61779917 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 ShippingMethodCountry+from ..shipping.models import ShippingZonefrom .forms import (AddressChoiceForm, AnonymousUserBillingForm, AnonymousUserShippingForm,BillingAddressChoiceForm)@@ -764,9 +764,12 @@ def get_taxes_for_cart(cart, default_taxes):def check_shipping_method(cart):"""Check if shipping method is valid for address and remove (if not)."""country_code = cart.shipping_address.country.code- valid_methods = ShippingMethodCountry.objects.select_related(- 'shipping_method').unique_for_country_code(country_code)- if cart.shipping_method not in valid_methods:+ # There should be only one ShippingZone per country+ valid_shipping_zone = ShippingZone.objects.filter(+ countries__contains=country_code).get()+ if (+ cart.shipping_method and+ cart.shipping_method.shipping_zone.get() != valid_shipping_zone):cart.shipping_method = Nonecart.save()return Falsediff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex 7bc8ea8f51..d1e6b92378 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -8,7 +8,7 @@ from ...core.utils import (format_money, get_user_shipping_country, to_local_currency)from ...product.models import ProductVariantfrom ...shipping.utils import get_shipment_options-from ..forms import CartShippingMethodForm, CountryForm, ReplaceCartLineForm+from ..forms import CartShippingRateForm, CountryForm, ReplaceCartLineFormfrom ..models import Cartfrom ..utils import (check_product_availability_and_warn, check_shipping_method, get_cart_data,@@ -65,10 +65,11 @@ def checkout_shipping_method(request, cart):"""Display the shipping method selection step."""taxes = get_taxes_for_cart(cart, request.taxes)check_shipping_method(cart)- form = CartShippingMethodForm(++ form = CartShippingRateForm(request.POST or None, taxes=taxes, instance=cart,initial={'shipping_method': cart.shipping_method})-+ import pdb; pdb.set_trace()if form.is_valid():form.save()return redirect('checkout:summary')diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex c8d7429584..8e8bd8a842 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -9,6 +9,7 @@ from django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.core.files import Filefrom django.template.defaultfilters import slugify+from django_countries import countriesfrom django_countries.fields import Countryfrom faker import Factoryfrom faker.providers import BaseProvider@@ -32,7 +33,8 @@ 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 ANY_COUNTRY, ShippingMethod+from ...shipping.models import (+ ANY_COUNTRY, ShippingMethod, ShippingRate, ShippingZone)from ...shipping.utils import get_taxed_shipping_pricefake = Factory.create()@@ -508,6 +510,23 @@ def create_product_sales(how_many=5):def create_shipping_methods():+ django_countries = [code for code, name in countries]+ shipping_zone = ShippingZone.objects.create(+ name='European countries', countries=django_countries[::2])+ #FIXME we should make sure that no country will be placed in two ShippingZones++ for i in range(4):+ shipping_zone.shipping_methods.add(+ ShippingRate.objects.create(+ name=fake.company(),+ price=fake.money()))+ shipping_zone = ShippingZone.objects.create(+ name='European countries', countries=django_countries[1::2])+ for i in range(4):+ shipping_zone.shipping_methods.add(+ ShippingRate.objects.create(+ name=fake.company(),+ price=fake.money()))shipping_method = ShippingMethod.objects.create(name='UPC')shipping_method.price_per_country.create(price=fake.money())yield 'Shipping method #%d' % shipping_method.iddiff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.pyindex 70530d0aed..761ea0365e 100644--- a/saleor/dashboard/discount/forms.py+++ b/saleor/dashboard/discount/forms.py@@ -7,12 +7,11 @@ from django.utils.translation import pgettext_lazyfrom django_prices.forms import MoneyFieldfrom mptt.forms import TreeNodeMultipleChoiceField-from ...core.i18n import ANY_COUNTRY, COUNTRY_CODE_CHOICESfrom ...core.utils.taxes import ZERO_MONEYfrom ...discount import DiscountValueTypefrom ...discount.models import Sale, Voucherfrom ...product.models import Category, Product-from ...shipping.models import ShippingMethodCountry+from ...shipping.utils import country_choicesfrom ..forms import AjaxSelect2MultipleChoiceFieldMinAmountSpent = MoneyField(@@ -128,19 +127,6 @@ class VoucherForm(forms.ModelForm):return code-def country_choices():- country_codes = ShippingMethodCountry.objects.all()- country_codes = country_codes.values_list('country_code', flat=True)- country_codes = list(country_codes.distinct())- if ANY_COUNTRY in country_codes:- return COUNTRY_CODE_CHOICES- country_dict = dict(COUNTRY_CODE_CHOICES)- country_choices = [- (country_code, country_dict[country_code])- for country_code in country_codes]- return country_choices--class ShippingVoucherForm(forms.ModelForm):min_amount_spent = MinAmountSpentcountries = forms.MultipleChoiceField(diff --git a/saleor/dashboard/templatetags/utils.py b/saleor/dashboard/templatetags/utils.pyindex 478f94c0eb..9301ed7f98 100644--- a/saleor/dashboard/templatetags/utils.py+++ b/saleor/dashboard/templatetags/utils.py@@ -48,8 +48,8 @@ def render_image_choice(field):return {'field': field, 'choices_with_images': choices}[email protected]_tag('dashboard/includes/_pagination.html',- takes_context=True)[email protected]_tag(+ 'dashboard/includes/_pagination.html', takes_context=True)def paginate(context, page_obj, num_of_pages=5):context['page_obj'] = page_objcontext['n_forward'] = num_of_pages + 1diff --git a/saleor/order/models.py b/saleor/order/models.pyindex f971585dbb..df5f7bb10b 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -20,7 +20,7 @@ from ..core.models import BaseNotefrom ..core.utils import build_absolute_urifrom ..core.utils.taxes import ZERO_TAXED_MONEYfrom ..discount.models import Voucher-from ..shipping.models import ShippingMethodCountry+from ..shipping.models import ShippingRateclass OrderQueryset(models.QuerySet):@@ -59,7 +59,7 @@ class Order(models.Model):on_delete=models.SET_NULL)user_email = models.EmailField(blank=True, default='')shipping_method = models.ForeignKey(- ShippingMethodCountry, blank=True, null=True, related_name='orders',+ ShippingRate, blank=True, null=True, related_name='orders',on_delete=models.SET_NULL)shipping_price_net = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,diff --git a/saleor/shipping/__init__.py b/saleor/shipping/__init__.pyindex e69de29bb2..ccfb788654 100644--- a/saleor/shipping/__init__.py+++ b/saleor/shipping/__init__.py@@ -0,0 +1,16 @@+from django.utils.translation import pgettext_lazy+++class ShippingRateType:+ PRICE_BASED = 'price'+ WEIGHT_BASED = 'weight'++ CHOICES = [+ (PRICE_BASED, pgettext_lazy(+ 'Type of shipping',+ 'Price based shipping'+ )),+ (WEIGHT_BASED, pgettext_lazy(+ 'Type of shipping',+ 'Weight based shipping'+ ))]diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex 98100f58c0..c2259d1d95 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -6,14 +6,47 @@ from django.db import modelsfrom django.db.models import Qfrom django.utils.safestring import mark_safefrom django.utils.translation import pgettext_lazy+from django_countries.fields import CountryFieldfrom django_prices.models import MoneyFieldfrom prices import MoneyRange+from . import ShippingRateTypefrom ..core.i18n import ANY_COUNTRY, COUNTRY_CODE_CHOICESfrom ..core.utils import format_moneyfrom ..shipping.utils import get_taxed_shipping_price+class ShippingRate(models.Model):+ name = models.CharField(max_length=100)+ type = models.CharField(+ max_length=30, choices=ShippingRateType.CHOICES,+ default=ShippingRateType.WEIGHT_BASED)+ price = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)++ def __str__(self):+ return self.name++ def get_total_price(self, taxes=None):+ return get_taxed_shipping_price(self.price, taxes)+++class ShippingZone(models.Model):+ name = models.CharField(max_length=100)+ countries = CountryField(multiple=True)+ shipping_methods = models.ManyToManyField(+ ShippingRate, blank=True, related_name='shipping_zone')++ def __str__(self):+ return self.name++ class Meta:+ permissions = ((+ 'manage_shipping', pgettext_lazy(+ 'Permission description', 'Manage shipping.')),)++class ShippingMethod(models.Model):name = models.CharField(max_length=100)diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex e1ce1902ec..d4fed67a2a 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -13,14 +13,37 @@ def get_taxed_shipping_price(price, taxes):def get_shipment_options(country_code, taxes):- from .models import ShippingMethodCountry- shipping_methods_qs = ShippingMethodCountry.objects.select_related(- 'shipping_method')- shipping_methods = shipping_methods_qs.filter(country_code=country_code)- if not shipping_methods.exists():- shipping_methods = shipping_methods_qs.filter(country_code='')- if shipping_methods:- shipping_methods = shipping_methods.values_list('price', flat=True)+ from .models import ShippingRate+ from ..core.i18n import ANY_COUNTRY, COUNTRY_CODE_CHOICES++ shipping_rates = ShippingRate.objects.prefetch_related(+ 'shipping_zone')+ shipping_rates = shipping_rates.filter(+ shipping_zone__countries__contains=country_code)+ if not shipping_rates.exists():+ shipping_rates = shipping_rates.filter(+ shipping_zone__countries__contains=ANY_COUNTRY)+ if shipping_rates:+ shipping_rates = shipping_rates.values_list('price', flat=True)prices = MoneyRange(- start=min(shipping_methods), stop=max(shipping_methods))+ start=min(shipping_rates), stop=max(shipping_rates))return get_taxed_shipping_price(prices, taxes)+++def country_choices():+ from .models import ShippingZone+ from ..core.i18n import ANY_COUNTRY, COUNTRY_CODE_CHOICES+ country_codes = []+ shipping_zones = ShippingZone.objects.all()+ for shipping_zone in shipping_zones:+ for country in shipping_zone.countries:+ country_codes.append(country.code)+ country_codes = set(country_codes)++ if ANY_COUNTRY in country_codes:+ return COUNTRY_CODE_CHOICES+ country_dict = dict(COUNTRY_CODE_CHOICES)+ country_choices = [+ (country_code, country_dict[country_code])+ for country_code in country_codes]+ return country_choicesdiff --git a/tests/dashboard/test_discounts.py b/tests/dashboard/test_discounts.pyindex 51c20df99e..602465ee09 100644--- a/tests/dashboard/test_discounts.py+++ b/tests/dashboard/test_discounts.py@@ -7,14 +7,10 @@ import pytestfrom django.urls import reversefrom prices import Money, TaxedMoney-from saleor.core.i18n import ANY_COUNTRY, COUNTRY_CODE_CHOICES-from saleor.core.utils import get_country_name_by_code-from saleor.dashboard.discount.forms import country_choicesfrom saleor.dashboard.order.utils import get_voucher_discount_for_orderfrom saleor.discount import DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Sale, Voucherfrom saleor.product.models import Collection-from saleor.shipping.models import ShippingMethodCountrydef test_sales_list(admin_client, sale):@@ -195,15 +191,3 @@ def test_ajax_voucher_list(admin_client, voucher):assert response.status_code == 200assert resp_decoded == {'results': vouchers_list}---def test_country_choices(shipping_method):- any_country_shipping_method = ShippingMethodCountry.objects.filter(- country_code=ANY_COUNTRY)- assert any_country_shipping_method.exists()- assert country_choices() == COUNTRY_CODE_CHOICES-- any_country_shipping_method.delete()- ShippingMethodCountry.objects.create(- country_code='PL', price=10, shipping_method=shipping_method)- assert country_choices() == [('PL', get_country_name_by_code('PL'))]diff --git a/tests/test_shipping.py b/tests/test_shipping.pyindex 8ceb8ddfbf..e651e6dad7 100644--- a/tests/test_shipping.py+++ b/tests/test_shipping.py@@ -1,10 +1,12 @@from unittest.mock import Mockimport pytest-from prices import Money, TaxedMoney-from saleor.core.utils import format_money-from saleor.shipping.utils import get_taxed_shipping_price+from prices import Money, TaxedMoney+from saleor.core.i18n import ANY_COUNTRY, COUNTRY_CODE_CHOICES+from saleor.core.utils import format_money, get_country_name_by_code+from saleor.shipping.models import ShippingMethodCountry+from saleor.shipping.utils import country_choices, get_taxed_shipping_price@pytest.mark.parametrize('price, charge_taxes, expected_price', [@@ -42,3 +44,15 @@ def test_shipping_get_ajax_label(shipping_method):'country_code_display': method.get_country_code_display(),'price': format_money(method.price)}assert label == proper_label+++def test_country_choices(shipping_method):+ any_country_shipping_method = ShippingMethodCountry.objects.filter(+ country_code=ANY_COUNTRY)+ assert any_country_shipping_method.exists()+ assert country_choices() == COUNTRY_CODE_CHOICES++ any_country_shipping_method.delete()+ ShippingMethodCountry.objects.create(+ country_code='PL', price=10, shipping_method=shipping_method)+ assert country_choices() == [('PL', get_country_name_by_code('PL'))]