Skip to content

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

Simplify checkout method validation

NyanKiyoshi04c3e17c61fa
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 867bace0b9..71c2bc813f 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -384,27 +384,6 @@ def check_variant_in_stock(
return new_quantity, line
-def update_or_create_checkout_line(
- checkout, variant, new_quantity, line: CheckoutLine = None
-):
- """Updates the quantity of a given checkout line to a given quantity.
- If the line doesn't exist, it will be created."""
-
- if line is None:
- line = checkout.lines.filter(variant=variant).first()
-
- if new_quantity == 0:
- if line is not None:
- line.delete()
- elif line is None:
- checkout.lines.create(checkout=checkout, variant=variant, quantity=new_quantity)
- else:
- line.quantity = new_quantity
- line.save(update_fields=["quantity"])
-
- update_checkout_quantity(checkout)
-
-
def add_variant_to_checkout(
checkout, variant, quantity=1, replace=False, check_quantity=True
):
@@ -422,7 +401,18 @@ def add_variant_to_checkout(
check_quantity=check_quantity,
)
- update_or_create_checkout_line(checkout, variant, new_quantity, line=line)
+ if line is None:
+ line = checkout.lines.filter(variant=variant).first()
+
+ if new_quantity == 0 and line is not None:
+ line.delete()
+ elif line is None:
+ checkout.lines.create(checkout=checkout, variant=variant, quantity=new_quantity)
+ elif new_quantity > 0:
+ line.quantity = new_quantity
+ line.save(update_fields=["quantity"])
+
+ update_checkout_quantity(checkout)
def get_shipping_address_forms(checkout, user_addresses, data, country):
@@ -984,7 +974,7 @@ def remove_voucher_from_checkout(checkout: Checkout):
def get_valid_shipping_methods(checkout: Checkout, discounts, country_code=None):
return applicable_shipping_methods(
checkout,
- price=calculate_checkout_subtotal(checkout, discounts).gross.amount,
+ price=calculate_checkout_subtotal(checkout, discounts).gross,
country_code=country_code,
)
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 26dc1c3b50..49b71c8f1e 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -23,7 +23,6 @@ from ...checkout.utils import (
recalculate_checkout_discount,
remove_promo_code_from_checkout,
remove_voucher_from_checkout,
- update_or_create_checkout_line,
)
from ...core import analytics
from ...core.exceptions import InsufficientStock
@@ -44,23 +43,16 @@ from .types import Checkout, CheckoutLine
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
+ checkout: models.Checkout, method: Optional[models.ShippingMethod], discounts
+) -> bool:
+ """
+ Check if current shipping method is valid. If so - return True.
+ It returns whether the selected shipping method is valid
"""
if not method:
# no shipping method was provided, it is valid
- return None, True
+ return True
if not checkout.is_shipping_required():
raise ValidationError("This checkout does not requires shipping.")
@@ -72,31 +64,17 @@ def clean_shipping_method(
)
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
-
- # There was no alternative, return: we failed
- return None, False
+ return method in valid_methods
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,
+ is_valid = clean_shipping_method(
+ checkout=checkout, method=checkout.shipping_method, discounts=discounts
)
- if new_shipping_method or not is_valid:
- checkout.shipping_method = new_shipping_method
+ if not is_valid:
+ cheapest_alternative = get_valid_shipping_methods(checkout, discounts).first()
+ checkout.shipping_method = cheapest_alternative
checkout.save(update_fields=["shipping_method"])
@@ -216,7 +194,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):
shipping_address = cleaned_input.get("shipping_address")
billing_address = cleaned_input.get("billing_address")
- # FIXME: check if we actually need a shipping address
if shipping_address:
shipping_address.save()
instance.shipping_address = shipping_address.get_copy()
@@ -232,7 +209,10 @@ class CheckoutCreate(ModelMutation, I18nMixin):
# Update/create checkout lines
if variants and quantities:
for variant, quantity in zip(variants, quantities):
- update_or_create_checkout_line(instance, variant, quantity)
+ try:
+ add_variant_to_checkout(instance, variant, quantity)
+ except InsufficientStock as exc:
+ raise ValidationError(f"Insufficient product stock: {exc.item}")
@classmethod
def perform_mutation(cls, _root, info, **data):
@@ -292,7 +272,12 @@ class CheckoutLinesAdd(BaseMutation):
if variants and quantities:
for variant, quantity in zip(variants, quantities):
- add_variant_to_checkout(checkout, variant, quantity, replace=replace)
+ try:
+ add_variant_to_checkout(
+ checkout, variant, quantity, replace=replace
+ )
+ except InsufficientStock as exc:
+ raise ValidationError(f"Insufficient product stock: {exc.item}")
recalculate_checkout_discount(checkout, info.context.discounts)
@@ -486,7 +471,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
field="shipping_method_id",
)
- _, shipping_method_is_valid = clean_shipping_method(
+ shipping_method_is_valid = clean_shipping_method(
checkout=checkout, method=shipping_method, discounts=info.context.discounts
)
diff --git a/saleor/graphql/checkout/utils.py b/saleor/graphql/checkout/utils.py
deleted file mode 100644
index 0f0afc4214..0000000000
--- a/saleor/graphql/checkout/utils.py
+++ /dev/null
@@ -1,19 +0,0 @@
-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/saleor/order/utils.py b/saleor/order/utils.py
index 18d1e4f354..62fc606bd2 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -378,4 +378,4 @@ def sum_order_totals(qs):
def get_valid_shipping_methods(order: Order):
- return applicable_shipping_methods(order, price=order.get_subtotal().gross.amount)
+ return applicable_shipping_methods(order, price=order.get_subtotal().gross)
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 9dbd7dfea9..726bdf05f6 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -45,8 +45,6 @@ def _applicable_price_based_methods(price, qs):
def _get_price_type_display(min_price, max_price):
- from ..core.utils import format_money
-
if max_price is None:
return pgettext_lazy(
"Applies to orders more expensive than the min value",
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 6bf926a549..84b0f63822 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -5,7 +5,6 @@ from unittest.mock import ANY, patch
import graphene
import pytest
from django.core.exceptions import ValidationError
-from django_countries import countries
from prices import Money, TaxedMoney
from saleor.checkout.models import Checkout
@@ -43,11 +42,8 @@ def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(
checkout = checkout_with_single_item
checkout.shipping_address = address
- alternative_method, is_valid_method = clean_shipping_method(
- checkout, shipping_method, None, retrieve_alternative=True
- )
+ is_valid_method = clean_shipping_method(checkout, shipping_method, [])
assert is_valid_method is True
- assert alternative_method is None
def test_clean_shipping_method_does_nothing_if_no_shipping_method(
@@ -58,60 +54,8 @@ def test_clean_shipping_method_does_nothing_if_no_shipping_method(
checkout = checkout_with_single_item
checkout.shipping_address = address
- alternative_method, is_valid_method = clean_shipping_method(
- checkout, None, None, retrieve_alternative=True
- )
+ is_valid_method = clean_shipping_method(checkout, None, [])
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(
@@ -1334,7 +1278,7 @@ def test_checkout_shipping_method_update(
):
checkout = checkout_with_item
query = UPDATE_SHIPPING_METHOD_QUERY
- mock_clean_shipping.return_value = [None, is_valid_shipping_method]
+ mock_clean_shipping.return_value = 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)