Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
No longer remove the shipping method of the checkout when invalid
Mira Szewczykc91db1e4cb20
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 72693a82f3..2971372ccd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,9 @@ All notable, unreleased changes to this project will be documented in this file.- Add `SPECIFIC_PRODUCT` type to `VoucherType` - #4344 by @fowczarek- New translations:- Icelandic+- Refactored the backend side of `checkoutCreate` to improve performances and prevent side effects over the user's checkout if the checkout creation was to fail. - #4367 by @NyanKiyoshi+- Refactored the logic of cleaning the checkout shipping method over the API, so users do not lose the shipping method when updating their checkout. If the shipping method becomes invalid, it will be replaced by the cheapest available. - #4367 by @NyanKiyoshi & @szewczykmira+- Refactored process of getting available shipping methods to make it easier to understand and prevent human-made errors. - #4367 by @NyanKiyoshi## 2.7.0diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 90596d4b4f..867bace0b9 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -1009,12 +1009,12 @@ def get_shipping_price_estimate(checkout: Checkout, discounts, country_code):)if shipping_methods is None:- return+ return Noneshipping_methods = shipping_methods.values_list("price", flat=True)if not shipping_methods:- return+ return Noneprices = MoneyRange(start=min(shipping_methods), stop=max(shipping_methods))return tax_interface.apply_taxes_to_shipping_price_range(prices, country_code)diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex e8b662d032..26dc1c3b50 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -43,10 +43,24 @@ from ..shipping.types import ShippingMethodfrom .types import Checkout, CheckoutLine-def clean_shipping_method(checkout, method, discounts, country_code=None, remove=True):- # FIXME Add tests for this function+def clean_shipping_method(+ checkout: models.Checkout,+ method: Optional[models.ShippingMethod],+ discounts,+ *,+ retrieve_alternative=False,+) -> Tuple[Optional[models.ShippingMethod], bool]:+ """Check if current shipping method is valid. If so - return True.+ If current method is invalid, return the cheapest shipping method available.++ Returns:+ - The cheapest shipping method if the selected one is invalid+ - Whether the selected shipping method is valid+ """+if not method:- return None+ # no shipping method was provided, it is valid+ return None, Trueif not checkout.is_shipping_required():raise ValidationError("This checkout does not requires shipping.")@@ -57,19 +71,32 @@ def clean_shipping_method(checkout, method, discounts, country_code=None, remove"shipping address.")- valid_methods = get_valid_shipping_methods(- checkout, discounts, country_code=country_code- )+ valid_methods = get_valid_shipping_methods(checkout, discounts)++ if method not in valid_methods:+ if retrieve_alternative:+ # Return the alternative shipping method+ # to replace the invalid one+ return valid_methods.first(), False+ else:+ # the shipping method is in the valid list,+ # we can return True+ return None, True- if (- valid_methods is None- or method.pk not in valid_methods.values_list("id", flat=True)- and not remove- ):- raise ValidationError("Shipping method cannot be used with this checkout.")+ # There was no alternative, return: we failed+ return None, False- if remove:- checkout.shipping_method = None++def update_checkout_shipping_method_if_invalid(checkout: models.Checkout, discounts):+ new_shipping_method, is_valid = clean_shipping_method(+ checkout=checkout,+ method=checkout.shipping_method,+ discounts=discounts,+ retrieve_alternative=True,+ )++ if new_shipping_method or not is_valid:+ checkout.shipping_method = new_shipping_methodcheckout.save(update_fields=["shipping_method"])@@ -261,13 +288,7 @@ class CheckoutLinesAdd(BaseMutation):quantities = [line.get("quantity") for line in lines]check_lines_quantity(variants, quantities)-- # FIXME test if below function is called- clean_shipping_method(- checkout=checkout,- method=checkout.shipping_method,- discounts=info.context.discounts,- )+ update_checkout_shipping_method_if_invalid(checkout, info.context.discounts)if variants and quantities:for variant, quantity in zip(variants, quantities):@@ -311,13 +332,7 @@ class CheckoutLineDelete(BaseMutation):if line and line in checkout.lines.all():line.delete()- # FIXME test if below function is called- clean_shipping_method(- checkout=checkout,- method=checkout.shipping_method,- discounts=info.context.discounts,- )-+ update_checkout_shipping_method_if_invalid(checkout, info.context.discounts)recalculate_checkout_discount(checkout, info.context.discounts)return CheckoutLineDelete(checkout=checkout)@@ -387,12 +402,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):shipping_address, instance=checkout.shipping_address)- # FIXME test if below function is called- clean_shipping_method(- checkout=checkout,- method=checkout.shipping_method,- discounts=info.context.discounts,- )+ update_checkout_shipping_method_if_invalid(checkout, info.context.discounts)with transaction.atomic():shipping_address.save()@@ -476,13 +486,15 @@ class CheckoutShippingMethodUpdate(BaseMutation):field="shipping_method_id",)- clean_shipping_method(- checkout=checkout,- method=shipping_method,- discounts=info.context.discounts,- remove=False,+ _, shipping_method_is_valid = clean_shipping_method(+ checkout=checkout, method=shipping_method, discounts=info.context.discounts)+ if not shipping_method_is_valid:+ raise ValidationError(+ {"shipping_method": "This shipping method is not applicable."}+ )+checkout.shipping_method = shipping_methodcheckout.save(update_fields=["shipping_method"])recalculate_checkout_discount(checkout, info.context.discounts)diff --git a/saleor/graphql/checkout/utils.py b/saleor/graphql/checkout/utils.pynew file mode 100644index 0000000000..0f0afc4214--- /dev/null+++ b/saleor/graphql/checkout/utils.py@@ -0,0 +1,19 @@+from saleor.shipping.models import ShippingMethod+from ...checkout.utils import get_valid_shipping_methods+from ...checkout.models import Checkout+++def update_shipping_method_checkout(+ checkout: Checkout, discounts, *, country_code=None+) -> ShippingMethod:+ """Check if current shipping method is valid. If so - return it.+ If current method is invalid assign cheapest shipping method available.+ """+ valid_methods = get_valid_shipping_methods(+ checkout, discounts, country_code=country_code+ )++ if checkout.shipping_method in valid_methods:+ return checkout.shipping_method++ return valid_methods.first()diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 70f77424ca..6bf926a549 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -1,19 +1,144 @@import uuid+from unittest import mockfrom unittest.mock import ANY, patchimport grapheneimport pytestfrom django.core.exceptions import ValidationError-from prices import TaxedMoney+from django_countries import countries+from prices import Money, TaxedMoneyfrom saleor.checkout.models import Checkoutfrom saleor.checkout.utils import clean_checkout, is_fully_paidfrom saleor.core.taxes import zero_money+from saleor.graphql.checkout.mutations import (+ clean_shipping_method,+ update_checkout_shipping_method_if_invalid,+)from saleor.graphql.core.utils import str_to_enumfrom saleor.order.models import Orderfrom saleor.payment import PaymentError+from saleor.shipping import ShippingMethodType+from saleor.shipping.models import ShippingMethodfrom tests.api.utils import get_graphql_content++def other_shipping_method(shipping_zone):+ return ShippingMethod.objects.create(+ name="DPD",+ minimum_order_price=Money(0, "USD"),+ type=ShippingMethodType.PRICE_BASED,+ price=Money(9, "USD"),+ shipping_zone=shipping_zone,+ )+++def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(+ checkout_with_single_item, address, shipping_method, other_shipping_method+):+ """If current shipping method applies to new address+ then it doesn't need to be changed."""++ checkout = checkout_with_single_item+ checkout.shipping_address = address++ alternative_method, is_valid_method = clean_shipping_method(+ checkout, shipping_method, None, retrieve_alternative=True+ )+ assert is_valid_method is True+ assert alternative_method is None+++def test_clean_shipping_method_does_nothing_if_no_shipping_method(+ checkout_with_single_item, address, other_shipping_method+):+ """If no shipping method was selected, it shouldn't return an error."""++ checkout = checkout_with_single_item+ checkout.shipping_address = address++ alternative_method, is_valid_method = clean_shipping_method(+ checkout, None, None, retrieve_alternative=True+ )+ assert is_valid_method is True+ assert alternative_method is None++[email protected]("request_alternative_method", (True, False))+def test_clean_shipping_method_invalid_shipping_method_select_cheapest_method(+ checkout_with_single_item,+ address,+ shipping_method,+ other_shipping_method,+ shipping_zone_without_countries,+ request_alternative_method,+):+ """If current shipping method doesn't apply to the current checkout,+ then it needs to be changed, suggest the cheapest one."""++ checkout = checkout_with_single_item+ checkout.shipping_address = address++ shipping_method.shipping_zone = shipping_zone_without_countries+ shipping_method.save(update_fields=["shipping_zone"])++ alternative_method, is_valid_method = clean_shipping_method(+ checkout, shipping_method, None, retrieve_alternative=request_alternative_method+ )+ assert is_valid_method is False++ if request_alternative_method:+ assert alternative_method == other_shipping_method+ else:+ assert alternative_method is None+++def test_clean_shipping_method_invalid_shipping_method_without_alternatives(+ checkout_with_single_item, address, shipping_method+):+ """If current shipping method doesn't apply to the current checkout,+ then it needs to be changed, suggest the cheapest one. But if none are available,+ it should return None as suggestion."""++ shipping_method.shipping_zone.countries = [countries.alpha2("FR")]+ shipping_method.shipping_zone.save(update_fields=["countries"])++ checkout = checkout_with_single_item+ checkout.shipping_address = address++ alternative_method, is_valid_method = clean_shipping_method(+ checkout, shipping_method, None, retrieve_alternative=True+ )+ assert is_valid_method is False+ assert alternative_method is None+++def test_update_checkout_shipping_method_if_invalid(+ checkout_with_single_item,+ address,+ shipping_method,+ other_shipping_method,+ shipping_zone_without_countries,+):+ """If the shipping method is invalid, it should replace it."""++ checkout = checkout_with_single_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method++ shipping_method.shipping_zone = shipping_zone_without_countries+ shipping_method.save(update_fields=["shipping_zone"])++ update_checkout_shipping_method_if_invalid(checkout, None)++ assert checkout.shipping_method == other_shipping_method++ # Ensure the checkout's shipping method was saved+ checkout.refresh_from_db(fields=["shipping_method"])+ assert checkout.shipping_method == other_shipping_method++MUTATION_CHECKOUT_CREATE = """mutation createCheckout($checkoutInput: CheckoutCreateInput!) {checkoutCreate(input: $checkoutInput) {@@ -366,7 +491,13 @@ MUTATION_CHECKOUT_LINES_ADD = """}"""-def test_checkout_lines_add(user_api_client, checkout_with_item, variant):+ "saleor.graphql.checkout.mutations.update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_add(+ mocked_update_shipping_method, user_api_client, checkout_with_item, variant+):checkout = checkout_with_itemline = checkout.lines.first()assert line.quantity == 3@@ -386,6 +517,8 @@ def test_checkout_lines_add(user_api_client, checkout_with_item, variant):assert line.variant == variantassert line.quantity == 1+ mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)+def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, variant):variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)@@ -481,7 +614,13 @@ MUTATION_CHECKOUT_LINES_UPDATE = """"""-def test_checkout_lines_update(user_api_client, checkout_with_item):+ "saleor.graphql.checkout.mutations.update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_update(+ mocked_update_shipping_method, user_api_client, checkout_with_item+):checkout = checkout_with_itemassert checkout.lines.count() == 1line = checkout.lines.first()@@ -506,6 +645,8 @@ def test_checkout_lines_update(user_api_client, checkout_with_item):assert line.variant == variantassert line.quantity == 1+ mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)+def test_checkout_lines_update_invalid_checkout_id(user_api_client):variables = {"checkoutId": "test", "lines": []}@@ -560,7 +701,13 @@ MUTATION_CHECKOUT_LINES_DELETE = """"""-def test_checkout_line_delete(user_api_client, checkout_with_item):+ "saleor.graphql.checkout.mutations.update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_line_delete(+ mocked_update_shipping_method, user_api_client, checkout_with_item+):checkout = checkout_with_itemassert checkout.lines.count() == 1line = checkout.lines.first()@@ -577,6 +724,7 @@ def test_checkout_line_delete(user_api_client, checkout_with_item):assert not data["errors"]checkout.refresh_from_db()assert checkout.lines.count() == 0+ mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)def test_checkout_customer_attach(user_api_client, checkout_with_item, customer_user):@@ -660,8 +808,15 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """}"""+ "saleor.graphql.checkout.mutations.update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)def test_checkout_shipping_address_update(- user_api_client, checkout_with_item, graphql_address_data+ mocked_update_shipping_method,+ user_api_client,+ checkout_with_item,+ graphql_address_data,):checkout = checkout_with_itemassert checkout.shipping_address is None@@ -689,6 +844,7 @@ def test_checkout_shipping_address_update(assert checkout.shipping_address.postal_code == shipping_address["postalCode"]assert checkout.shipping_address.country == shipping_address["country"]assert checkout.shipping_address.city == shipping_address["city"].upper()+ mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)def test_checkout_shipping_address_with_invalid_phone_number_returns_error(@@ -1150,11 +1306,7 @@ def test_checkout_prices(user_api_client, checkout_with_item):)-@patch("saleor.graphql.checkout.mutations.clean_shipping_method")-def test_checkout_shipping_method_update(- mock_clean_shipping, staff_api_client, shipping_method, checkout_with_item-):- query = """+UPDATE_SHIPPING_METHOD_QUERY = """mutation checkoutShippingMethodUpdate($checkoutId:ID!, $shippingMethodId:ID!){checkoutShippingMethodUpdate(@@ -1168,23 +1320,49 @@ def test_checkout_shipping_method_update(}}}- """+"""++[email protected]("is_valid_shipping_method", (True, False))+@patch("saleor.graphql.checkout.mutations.clean_shipping_method")+def test_checkout_shipping_method_update(+ mock_clean_shipping,+ staff_api_client,+ shipping_method,+ checkout_with_item,+ is_valid_shipping_method,+):checkout = checkout_with_item+ query = UPDATE_SHIPPING_METHOD_QUERY+ mock_clean_shipping.return_value = [None, is_valid_shipping_method]+checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)- variables = {"checkoutId": checkout_id, "shippingMethodId": method_id}- response = staff_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutShippingMethodUpdate"]- assert not data["errors"]- assert data["checkout"]["id"] == checkout_id++ response = staff_api_client.post_graphql(+ query, {"checkoutId": checkout_id, "shippingMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]checkout.refresh_from_db()- assert checkout.shipping_method == shipping_method+mock_clean_shipping.assert_called_once_with(- checkout=checkout, method=shipping_method, discounts=ANY, remove=False+ checkout=checkout, method=shipping_method, discounts=ANY)+ if is_valid_shipping_method:+ assert not data["errors"]+ assert data["checkout"]["id"] == checkout_id+ assert checkout.shipping_method == shipping_method+ else:+ assert data["errors"] == [+ {+ "field": "shippingMethod",+ "message": "This shipping method is not applicable.",+ }+ ]+ assert checkout.shipping_method is None+def test_query_checkout_line(checkout_with_item, user_api_client):query = """