Skip to content

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

Add deliveryOptionsCalculate mutation (#18887)

Maciej Korycinski1c7604753a18
diff --git a/saleor/checkout/delivery_context.py b/saleor/checkout/delivery_context.py
index c3972a292f..135b3c00da 100644
--- a/saleor/checkout/delivery_context.py
+++ b/saleor/checkout/delivery_context.py
@@ -377,26 +377,111 @@ def clear_cc_delivery_method(
return updated_fields
-def _get_refreshed_assigned_delivery_data(
+def is_delivery_changed(
+ first: CheckoutDelivery,
+ second: CheckoutDelivery,
+) -> bool:
+ return (
+ first.name != second.name
+ or first.price != second.price
+ or first.tax_class_id != second.tax_class_id
+ or first.maximum_delivery_days != second.maximum_delivery_days
+ or first.minimum_delivery_days != second.minimum_delivery_days
+ )
+
+
+def _overwrite_assigned_delivery(
+ checkout_info: "CheckoutInfo",
assigned_delivery: CheckoutDelivery | None,
- built_in_shipping_methods_dict: dict[int, ShippingMethodData],
- external_shipping_methods_dict: dict[str, ShippingMethodData],
-) -> ShippingMethodData | None:
- """Get refreshed shipping method data for assigned delivery.
+ refreshed_delivery: CheckoutDelivery | None,
+):
+ """Overwrite assigned delivery.
+
+ Function overwrites the details of assigned delivery with the
+ refreshed data. If refreshed delivery is missing, the assigned one
+ will be marked as invalid.
+ If the tax or price field have been changed the checkout taxes
+ will be marked as invalid.
+ """
+ if not assigned_delivery:
+ return
+
+ # Update current assigned delivery with new details or set
+ # is_valid:False
+ if refreshed_delivery:
+ _create_or_update_checkout_deliveries([refreshed_delivery])
+ else:
+ _invalidate_assigned_delivery(assigned_delivery)
+
+ if _refreshed_assigned_delivery_has_impact_on_prices(
+ assigned_delivery, refreshed_delivery
+ ):
+ from .utils import invalidate_checkout
+
+ invalidate_checkout(
+ checkout_info=checkout_info,
+ lines=checkout_info.lines,
+ manager=checkout_info.manager,
+ recalculate_discount=True,
+ save=True,
+ )
+ return
+
+
+def _restore_assigned_delivery_as_valid(
+ checkout: Checkout,
+ assigned_delivery: CheckoutDelivery,
+):
+ # Database has a constrain on these fields, to keep the same ID of assigned delivery
+ # we need to first delete the delivery that is marked as valid
+ CheckoutDelivery.objects.filter(
+ checkout_id=checkout.pk,
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id,
+ built_in_shipping_method_id=assigned_delivery.built_in_shipping_method_id,
+ is_valid=True,
+ ).exclude(pk=assigned_delivery.pk).delete()
+
+ assigned_delivery.is_valid = True
+ assigned_delivery.save(update_fields=["is_valid"])
+
+
+def _invalidate_assigned_delivery(assigned_delivery: CheckoutDelivery):
+ assigned_delivery.is_valid = False
+ assigned_delivery.save(update_fields=["is_valid"])
+
+
+def _preserve_assigned_delivery(
+ checkout: Checkout,
+ assigned_delivery: CheckoutDelivery | None,
+ refreshed_delivery: CheckoutDelivery | None,
+):
+ """Preserve assigned delivery.
- Returns the updated ShippingMethodData for the assigned delivery method,
- or None if the assigned delivery is no longer valid.
+ Creates a new delivery method if the refreshed delivery has changed and marks the
+ assigned delivery as invalid.
"""
if not assigned_delivery:
- return None
+ return
- if external_shipping_method_id := assigned_delivery.external_shipping_method_id:
- return external_shipping_methods_dict.get(external_shipping_method_id)
+ # If refreshed is missing, mark assigned as invalid
+ if not refreshed_delivery:
+ _invalidate_assigned_delivery(assigned_delivery)
+ return
- if built_in_shipping_method_id := assigned_delivery.built_in_shipping_method_id:
- return built_in_shipping_methods_dict.get(built_in_shipping_method_id)
+ delivery_changed = is_delivery_changed(assigned_delivery, refreshed_delivery)
+ if not delivery_changed and assigned_delivery.is_valid:
+ return
- return None
+ if not delivery_changed and not assigned_delivery.is_valid:
+ _restore_assigned_delivery_as_valid(
+ checkout=checkout,
+ assigned_delivery=assigned_delivery,
+ )
+ if delivery_changed and assigned_delivery.is_valid:
+ _invalidate_assigned_delivery(assigned_delivery)
+ # this call ensures the update happens atomically as part of
+ # preserving the assigned delivery.
+ _create_or_update_checkout_deliveries([refreshed_delivery])
def _refresh_checkout_deliveries(
@@ -421,52 +506,44 @@ def _refresh_checkout_deliveries(
# Always preserve the assigned delivery even if it's no longer available
exclude_from_delete |= Q(pk=assigned_delivery.pk)
- refreshed_delivery_method = _get_refreshed_assigned_delivery_data(
- assigned_delivery,
- built_in_shipping_methods_dict,
- external_shipping_methods_dict,
- )
-
- # Missing refreshed delivery method means that assigned
- # delivery is no more valid.
- if not refreshed_delivery_method:
- assigned_delivery.is_valid = False
- assigned_delivery.save(update_fields=["is_valid"])
-
CheckoutDelivery.objects.filter(
checkout_id=checkout.pk,
).exclude(exclude_from_delete).delete()
if checkout_deliveries:
- CheckoutDelivery.objects.bulk_create(
- checkout_deliveries,
- update_conflicts=True,
- unique_fields=[
- "checkout_id",
- "external_shipping_method_id",
- "built_in_shipping_method_id",
- "is_valid",
- ],
- update_fields=[
- "name",
- "description",
- "price_amount",
- "currency",
- "maximum_delivery_days",
- "minimum_delivery_days",
- "metadata",
- "private_metadata",
- "active",
- "message",
- "updated_at",
- "is_valid",
- "is_external",
- "tax_class_id",
- "tax_class_name",
- "tax_class_metadata",
- "tax_class_private_metadata",
- ],
- )
+ _create_or_update_checkout_deliveries(checkout_deliveries)
+
+
+def _create_or_update_checkout_deliveries(deliveries: list[CheckoutDelivery]):
+ CheckoutDelivery.objects.bulk_create(
+ deliveries,
+ update_conflicts=True,
+ unique_fields=[
+ "checkout_id",
+ "external_shipping_method_id",
+ "built_in_shipping_method_id",
+ "is_valid",
+ ],
+ update_fields=[
+ "name",
+ "description",
+ "price_amount",
+ "currency",
+ "maximum_delivery_days",
+ "minimum_delivery_days",
+ "metadata",
+ "private_metadata",
+ "active",
+ "message",
+ "updated_at",
+ "is_valid",
+ "is_external",
+ "tax_class_id",
+ "tax_class_name",
+ "tax_class_metadata",
+ "tax_class_private_metadata",
+ ],
+ )
def get_available_built_in_shipping_methods_for_checkout_info(
@@ -504,9 +581,8 @@ def get_available_built_in_shipping_methods_for_checkout_info(
def _refreshed_assigned_delivery_has_impact_on_prices(
- assigned_delivery: CheckoutDelivery | None,
- built_in_shipping_methods_dict: dict[int, ShippingMethodData],
- external_shipping_methods_dict: dict[str, ShippingMethodData],
+ assigned_delivery: CheckoutDelivery,
+ refreshed_delivery: CheckoutDelivery | None,
) -> bool:
"""Check if refreshed assigned delivery impacts checkout prices.
@@ -514,29 +590,16 @@ def _refreshed_assigned_delivery_has_impact_on_prices(
such as a change in tax class, price or marking as invalid, this function
returns True. Otherwise, it doesn't impact prices and returns False.
"""
- if not assigned_delivery:
- return False
-
- refreshed_delivery_method = _get_refreshed_assigned_delivery_data(
- assigned_delivery,
- built_in_shipping_methods_dict,
- external_shipping_methods_dict,
- )
- if not refreshed_delivery_method:
+ if not refreshed_delivery:
return True
- refreshed_tax_class_id = (
- refreshed_delivery_method.tax_class.id
- if refreshed_delivery_method.tax_class
- else None
- )
# Different tax class can impact on prices
- if refreshed_tax_class_id != assigned_delivery.tax_class_id:
+ if refreshed_delivery.tax_class_id != assigned_delivery.tax_class_id:
return True
# Different price means that assigned delivery is invalid
- if refreshed_delivery_method.price != assigned_delivery.price:
+ if refreshed_delivery.price != assigned_delivery.price:
return True
return False
@@ -545,6 +608,7 @@ def _refreshed_assigned_delivery_has_impact_on_prices(
def fetch_shipping_methods_for_checkout(
checkout_info: "CheckoutInfo",
requestor: Union["App", "User", None],
+ overwrite_assigned_delivery: bool = True,
) -> Promise[list[CheckoutDelivery]]:
"""Fetch shipping methods for the checkout.
@@ -553,6 +617,11 @@ def fetch_shipping_methods_for_checkout(
shipping methods in the database are updated or removed as needed, while the
checkout's currently assigned shipping method (`assigned_delivery`) is
always preserved, even if it is no longer available.
+
+ `overwrite_assigned_delivery`- controls how the assigned delivery method is updated:
+ - True: updates the assigned delivery method's details and marks taxes as invalid if needed.
+ - False: creates a new delivery method if the refreshed delivery has changed and marks the
+ assigned delivery as invalid.
"""
checkout = checkout_info.checkout
@@ -613,6 +682,23 @@ def fetch_shipping_methods_for_checkout(
)
checkout.save(update_fields=["delivery_methods_stale_at"])
+ refreshed_assigned = None
+ if assigned_delivery:
+ refreshed_assigned = checkout_deliveries.get(
+ assigned_delivery.shipping_method_id
+ )
+ if overwrite_assigned_delivery:
+ _overwrite_assigned_delivery(
+ checkout_info=checkout_info,
+ assigned_delivery=assigned_delivery,
+ refreshed_delivery=refreshed_assigned,
+ )
+ else:
+ _preserve_assigned_delivery(
+ checkout=checkout,
+ assigned_delivery=assigned_delivery,
+ refreshed_delivery=refreshed_assigned,
+ )
_refresh_checkout_deliveries(
checkout=locked_checkout,
assigned_delivery=assigned_delivery,
@@ -621,20 +707,6 @@ def fetch_shipping_methods_for_checkout(
external_shipping_methods_dict=external_shipping_methods_dict,
)
- if _refreshed_assigned_delivery_has_impact_on_prices(
- assigned_delivery,
- built_in_shipping_methods_dict,
- external_shipping_methods_dict,
- ):
- from .utils import invalidate_checkout
-
- invalidate_checkout(
- checkout_info=checkout_info,
- lines=checkout_info.lines,
- manager=checkout_info.manager,
- recalculate_discount=True,
- save=True,
- )
if checkout_deliveries:
return list(
CheckoutDelivery.objects.filter(
diff --git a/saleor/checkout/tests/test_delivery_context.py b/saleor/checkout/tests/test_delivery_context.py
index c90a0e2773..853763e533 100644
--- a/saleor/checkout/tests/test_delivery_context.py
+++ b/saleor/checkout/tests/test_delivery_context.py
@@ -1,3 +1,4 @@
+import datetime
from decimal import Decimal
from unittest import mock
@@ -9,6 +10,7 @@ from promise import Promise
from ...shipping.interface import ExcludedShippingMethod, ShippingMethodData
from ...shipping.models import ShippingMethod
+from ...shipping.utils import convert_shipping_method_data_to_checkout_delivery
from ...webhook.transport.shipping_helpers import to_shipping_app_id
from ..delivery_context import (
DeliveryMethodBase,
@@ -832,7 +834,6 @@ def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_ship
):
# given
shipping_price_amount = Decimal(10)
- shipping_price_amount = Decimal(10)
available_shipping_method = ShippingMethodData(
id=to_shipping_app_id(app, "external-shipping-method-id"),
@@ -886,6 +887,545 @@ def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_ship
assert assigned_delivery.price_amount == new_shipping_price_amount
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_none(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+):
+ # given
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve([])
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = None
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ assert len(shipping_methods) == 1
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery is None
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_invalid_and_refreshed_is_none(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ checkout_delivery,
+ external_app,
+):
+ # given
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve([])
+
+ checkout = checkout_with_item
+
+ assigned_delivery = checkout.shipping_methods.create(
+ external_shipping_method_id=to_shipping_app_id(
+ external_app, "expired-shipping-method-id"
+ ),
+ name="Old External Shipping name",
+ price_amount=Decimal(99),
+ currency="USD",
+ is_external=True,
+ is_valid=False,
+ )
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ assert CheckoutDelivery.objects.count() == 2
+ assert len(shipping_methods) == 1
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assigned_delivery.refresh_from_db()
+ assert not assigned_delivery.is_valid
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_valid_and_refreshed_is_none(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ external_app,
+):
+ # given
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve([])
+
+ checkout = checkout_with_item
+
+ assigned_delivery = checkout.shipping_methods.create(
+ external_shipping_method_id=to_shipping_app_id(
+ external_app, "expired-shipping-method-id"
+ ),
+ name="Old External Shipping name",
+ price_amount=Decimal(99),
+ currency="USD",
+ is_external=True,
+ is_valid=True,
+ )
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ assert CheckoutDelivery.objects.count() == 2
+ assert len(shipping_methods) == 1
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assigned_delivery.refresh_from_db()
+ assert not assigned_delivery.is_valid
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_valid_and_refreshed_unchanged(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ app,
+):
+ # given
+ shipping_price_amount = Decimal(10)
+
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(shipping_price_amount, checkout_with_item.currency),
+ active=True,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [available_shipping_method]
+ )
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ assigned_delivery = convert_shipping_method_data_to_checkout_delivery(
+ available_shipping_method, checkout
+ )
+ assigned_delivery.is_valid = True
+ assigned_delivery.save()
+
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ assert CheckoutDelivery.objects.count() == 2
+ assert len(shipping_methods) == 2
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assigned_delivery.refresh_from_db()
+ assert assigned_delivery.is_valid
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_invalid_and_refreshed_unchanged(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ app,
+):
+ # given
+ shipping_price_amount = Decimal(10)
+
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(shipping_price_amount, checkout_with_item.currency),
+ active=True,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [available_shipping_method]
+ )
+
+ checkout = checkout_with_item
+ assigned_delivery = convert_shipping_method_data_to_checkout_delivery(
+ available_shipping_method, checkout
+ )
+ assigned_delivery.is_valid = False
+ assigned_delivery.save()
+
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ # Invalid assigned delivery should be converted to valid
+ # The assigned delivery's ID should be the same as previously
+ assert CheckoutDelivery.objects.count() == 2
+ assert len(shipping_methods) == 2
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assigned_delivery.refresh_from_db()
+ assert assigned_delivery.is_valid
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_valid_and_refreshed_changed(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ app,
+):
+ # given
+ shipping_price_amount = Money(Decimal(10), checkout_with_item.currency)
+ changed_shipping_price_amount = Money(Decimal(11), checkout_with_item.currency)
+
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=shipping_price_amount,
+ active=True,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+ assigned_delivery = convert_shipping_method_data_to_checkout_delivery(
+ available_shipping_method, checkout_with_item
+ )
+ assigned_delivery.is_valid = True
+ assigned_delivery.save()
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ changed_shipping_method = available_shipping_method
+ changed_shipping_method.price = changed_shipping_price_amount
+ changed_shipping_method.name = "Modified"
+
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [changed_shipping_method]
+ )
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ deliveries = CheckoutDelivery.objects.filter(
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id
+ )
+ assert len(deliveries) == 2
+
+ assigned_delivery.refresh_from_db()
+ assert not assigned_delivery.is_valid
+ assert assigned_delivery.price == shipping_price_amount
+ refreshed_delivery = next(
+ delivery for delivery in deliveries if delivery.id != assigned_delivery.id
+ )
+ assert refreshed_delivery.price == changed_shipping_price_amount
+ assert (
+ refreshed_delivery.external_shipping_method_id
+ == assigned_delivery.external_shipping_method_id
+ )
+ assert refreshed_delivery.is_valid
+
+ assert len(shipping_methods) == 2
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_assigned_is_invalid_and_refreshed_changed(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ app,
+):
+ # given
+ shipping_price_amount = Money(Decimal(10), checkout_with_item.currency)
+ changed_shipping_price_amount = Money(Decimal(11), checkout_with_item.currency)
+
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=shipping_price_amount,
+ active=True,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+ assigned_delivery = convert_shipping_method_data_to_checkout_delivery(
+ available_shipping_method, checkout_with_item
+ )
+ assigned_delivery.is_valid = False
+ assigned_delivery.save()
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ changed_shipping_method = available_shipping_method
+ changed_shipping_method.price = changed_shipping_price_amount
+ changed_shipping_method.name = "Modified"
+
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [changed_shipping_method]
+ )
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ deliveries = CheckoutDelivery.objects.filter(
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id
+ )
+ assert len(deliveries) == 2
+
+ assigned_delivery.refresh_from_db()
+ assert not assigned_delivery.is_valid
+ assert assigned_delivery.price == shipping_price_amount
+ refreshed_delivery = next(
+ delivery for delivery in deliveries if delivery.id != assigned_delivery.id
+ )
+ assert refreshed_delivery.price == changed_shipping_price_amount
+ assert refreshed_delivery.is_valid
+
+ assert len(shipping_methods) == 2
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_preserve_when_refreshed_is_changed_to_match_assigned(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ app,
+):
+ # given
+ shipping_price_amount = Decimal(10)
+
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(shipping_price_amount, checkout_with_item.currency),
+ active=True,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_exclude_shipping_methods.return_value = Promise.resolve([])
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [available_shipping_method]
+ )
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ assigned_delivery = convert_shipping_method_data_to_checkout_delivery(
+ available_shipping_method, checkout
+ )
+ assigned_delivery.is_valid = False
+ assigned_delivery.save()
+
+ CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id,
+ built_in_shipping_method_id=None,
+ name="Modified",
+ price_amount=Decimal(11),
+ currency=checkout.currency,
+ is_valid=True,
+ is_external=True,
+ )
+
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None, overwrite_assigned_delivery=False
+ ).get()
+
+ # then
+ deliveries = CheckoutDelivery.objects.filter(
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id
+ )
+ assert len(deliveries) == 1
+
+ assigned_delivery.refresh_from_db()
+ assert assigned_delivery.is_valid
+
+ assert len(shipping_methods) == 2
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+
def test_assign_delivery_method_to_checkout_delivery_method_to_none(
checkout_with_delivery_method_for_cc, plugins_manager
):
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index da335f691c..68584cc654 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -419,6 +419,11 @@ ShippingErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
)
ShippingErrorCode.doc_category = DOC_CATEGORY_SHIPPING
+DeliveryOptionsCalculateErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
+ shipping_error_codes.DeliveryOptionsCalculateErrorCode
+)
+DeliveryOptionsCalculateErrorCode.doc_category = DOC_CATEGORY_SHIPPING
+
StockErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
warehouse_error_codes.StockErrorCode
)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 8c9c418395..20be8eff00 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -39,6 +39,7 @@ from ..enums import (
CheckoutErrorCode,
CollectionErrorCode,
CustomerBulkUpdateErrorCode,
+ DeliveryOptionsCalculateErrorCode,
DiscountErrorCode,
ExportErrorCode,
ExternalNotificationTriggerErrorCode,
@@ -614,6 +615,15 @@ class ShippingError(Error):
doc_category = DOC_CATEGORY_SHIPPING
+class DeliveryOptionsCalculateError(Error):
+ code = DeliveryOptionsCalculateErrorCode(
+ description="The error code.", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHIPPING
+
+
class PageError(Error):
code = PageErrorCode(description="The error code.", required=True)
attributes = NonNullList(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f5d4177de0..9f8385b30e 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -17783,6 +17783,20 @@ type Mutation {
"""
refundReasonReferenceClear: RefundReasonReferenceTypeClear @doc(category: "Orders")
+ """
+ Calculates available delivery options for a checkout.
+
+ Added in Saleor 3.23.
+
+ Triggers the following webhook events:
+ - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Triggered to fetch external shipping methods.
+ - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Triggered to filter shipping methods.
+ """
+ deliveryOptionsCalculate(
+ """The ID of the checkout."""
+ id: ID!
+ ): DeliveryOptionsCalculate @doc(category: "Shipping") @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS])
+
"""
Manage shipping method's availability in channels.
@@ -23310,6 +23324,40 @@ type RefundReasonReferenceTypeClearError @doc(category: "Shop") {
code: RefundSettingsErrorCode!
}
+"""
+Calculates available delivery options for a checkout.
+
+Added in Saleor 3.23.
+
+Triggers the following webhook events:
+- SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Triggered to fetch external shipping methods.
+- CHECKOUT_FILTER_SHIPPING_METHODS (sync): Triggered to filter shipping methods.
+"""
+type DeliveryOptionsCalculate @doc(category: "Shipping") @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) {
+ """List of the available deliveries."""
+ deliveries: [Delivery!]!
+ errors: [DeliveryOptionsCalculateError!]!
+}
+
+type DeliveryOptionsCalculateError @doc(category: "Shipping") {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: DeliveryOptionsCalculateErrorCode!
+}
+
+enum DeliveryOptionsCalculateErrorCode @doc(category: "Shipping") {
+ GRAPHQL_ERROR
+ NOT_FOUND
+ INVALID
+}
+
"""
Manage shipping method's availability in channels.
diff --git a/saleor/graphql/shipping/mutations/delivery_options_calculate.py b/saleor/graphql/shipping/mutations/delivery_options_calculate.py
new file mode 100644
index 0000000000..eb583380e6
--- /dev/null
+++ b/saleor/graphql/shipping/mutations/delivery_options_calculate.py
@@ -0,0 +1,69 @@
+import graphene
+
+from ....checkout.delivery_context import fetch_shipping_methods_for_checkout
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....webhook.event_types import WebhookEventSyncType
+from ...checkout import types as checkout_types
+from ...core.descriptions import ADDED_IN_323
+from ...core.doc_category import DOC_CATEGORY_SHIPPING
+from ...core.mutations import BaseMutation
+from ...core.types.common import DeliveryOptionsCalculateError, NonNullList
+from ...core.utils import WebhookEventInfo
+from ...plugins.dataloaders import get_plugin_manager_promise
+from ...utils import get_user_or_app_from_context
+
+
+class DeliveryOptionsCalculate(BaseMutation):
+ deliveries = NonNullList(
+ checkout_types.Delivery,
+ required=True,
+ default_value=[],
+ description="List of the available deliveries.",
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the checkout.",
+ required=True,
+ )
+
+ class Meta:
+ description = (
+ "Calculates available delivery options for a checkout." + ADDED_IN_323
+ )
+ doc_category = DOC_CATEGORY_SHIPPING
+ error_type_class = DeliveryOptionsCalculateError
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ description="Triggered to fetch external shipping methods.",
+ ),
+ WebhookEventInfo(
+ type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ description="Triggered to filter shipping methods.",
+ ),
+ ]
+
+ @classmethod
+ def perform_mutation(cls, _root, info, /, *, id): # type: ignore[override]
+ manager = get_plugin_manager_promise(info.context).get()
+ requestor = get_user_or_app_from_context(info.context)
+ checkout = cls.get_node_or_error(
+ info=info, node_id=id, field="id", only_type=checkout_types.Checkout
+ )
+ checkout_lines, _ = fetch_checkout_lines(checkout=checkout)
+ checkout_info = fetch_checkout_info(
+ checkout=checkout,
+ lines=checkout_lines,
+ manager=manager,
+ )
+ return cls(
+ deliveries=fetch_shipping_methods_for_checkout(
+ checkout_info,
+ requestor=requestor,
+ # Using mutation means, that we use new approach for fetching
+ # delivery. In new flow we never modify anything for assigned
+ # delivery
+ overwrite_assigned_delivery=False,
+ )
+ )
diff --git a/saleor/graphql/shipping/schema.py b/saleor/graphql/shipping/schema.py
index 4bda6acb24..44c68d3eff 100644
--- a/saleor/graphql/shipping/schema.py
+++ b/saleor/graphql/shipping/schema.py
@@ -21,6 +21,7 @@ from .mutations import (
ShippingZoneDelete,
ShippingZoneUpdate,
)
+from .mutations.delivery_options_calculate import DeliveryOptionsCalculate
from .mutations.shipping_method_channel_listing_update import (
ShippingMethodChannelListingUpdate,
)
@@ -78,6 +79,7 @@ class ShippingQueries(graphene.ObjectType):
class ShippingMutations(graphene.ObjectType):
+ delivery_options_calculate = DeliveryOptionsCalculate.Field()
shipping_method_channel_listing_update = ShippingMethodChannelListingUpdate.Field()
shipping_price_create = ShippingPriceCreate.Field()
shipping_price_delete = ShippingPriceDelete.Field()
diff --git a/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py b/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py
new file mode 100644
index 0000000000..8421119478
--- /dev/null
+++ b/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py
@@ -0,0 +1,380 @@
+import datetime
+from decimal import Decimal
+from unittest import mock
+
+import graphene
+from django.utils import timezone
+from prices import Money
+from promise import Promise
+
+from .....checkout.delivery_context import fetch_shipping_methods_for_checkout
+from .....checkout.models import Checkout, CheckoutDelivery
+from .....checkout.webhooks.exclude_shipping import (
+ excluded_shipping_methods_for_checkout,
+)
+from .....checkout.webhooks.list_shipping_methods import (
+ list_shipping_methods_for_checkout,
+)
+from .....shipping.error_codes import DeliveryOptionsCalculateErrorCode
+from .....shipping.interface import ShippingMethodData
+from .....shipping.models import ShippingMethod
+from .....webhook.transport.shipping_helpers import to_shipping_app_id
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+DELIVERY_OPTIONS_CALCULATE = """
+mutation DeliveryOptionsCalculate($id: ID!) {
+ deliveryOptionsCalculate(id: $id) {
+ deliveries {
+ id
+ shippingMethod {
+ name
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+def test_used_with_different_type_than_checkout(api_client, address):
+ # given
+ invalid_id = graphene.Node.to_global_id("Address", address.id)
+ variables = {"id": invalid_id}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["data"]["deliveryOptionsCalculate"]["errors"]
+
+ # then
+ assert len(errors) == 1
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == DeliveryOptionsCalculateErrorCode.GRAPHQL_ERROR.name
+
+
+def test_checkout_not_found(api_client):
+ # given
+ assert Checkout.objects.count() == 0
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "Checkout", "00000000-0000-0000-0000-000000000000"
+ )
+ }
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["data"]["deliveryOptionsCalculate"]["errors"]
+
+ # then
+ assert len(errors) == 1
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == DeliveryOptionsCalculateErrorCode.NOT_FOUND.name
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout",
+ wraps=excluded_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetches_external_shipping_methods(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ api_client,
+ checkout_with_item,
+ address,
+ app,
+):
+ # given
+ checkout = checkout_with_item
+ ShippingMethod.objects.all().delete()
+ expected_name = "External Shipping"
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-id"),
+ price=Money(Decimal(10), checkout.currency),
+ name=expected_name,
+ description="External Shipping Description",
+ active=True,
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={},
+ )
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [available_shipping_method]
+ )
+
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["deliveryOptionsCalculate"]
+
+ # then
+ delivery = CheckoutDelivery.objects.get()
+ assert not data["errors"]
+ assert len(data["deliveries"]) == 1
+ assert data["deliveries"][0]["shippingMethod"]["name"] == expected_name
+ assert data["deliveries"][0]["id"] == graphene.Node.to_global_id(
+ "CheckoutDelivery", delivery.pk
+ )
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout",
+ wraps=excluded_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_excluded_shipping_methods_called_for_checkout(
+ mocked_list_shipping_methods,
+ mocked_excluded_shipping_methods_for_checkout,
+ api_client,
+ checkout_with_item,
+ address,
+ app,
+):
+ # given
+ checkout = checkout_with_item
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-id"),
+ price=Money(Decimal(10), checkout.currency),
+ name="External Shipping",
+ description="External Shipping Description",
+ active=True,
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={},
+ )
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [available_shipping_method]
+ )
+
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["deliveryOptionsCalculate"]
+
+ # then
+ assert not data["errors"]
+ mocked_excluded_shipping_methods_for_checkout.assert_called_once()
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout",
+ wraps=excluded_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout",
+ wraps=list_shipping_methods_for_checkout,
+)
+def test_when_checkout_has_stale_deliveries(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ api_client,
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_with_item
+ existing_delivery = checkout_delivery(checkout)
+
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["deliveryOptionsCalculate"]
+
+ # then
+ assert not data["errors"]
+ assert len(data["deliveries"]) == 1
+
+ existing_delivery.refresh_from_db()
+ assert existing_delivery.is_valid
+ assert data["deliveries"][0]["shippingMethod"]["name"] == existing_delivery.name
+ assert CheckoutDelivery.objects.filter(checkout=checkout).count() == 1
+ assert mocked_exclude_shipping_methods.called
+ assert mocked_list_shipping_methods.called
+
+
+ "saleor.graphql.shipping.mutations.delivery_options_calculate.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout",
+ wraps=excluded_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout",
+ wraps=list_shipping_methods_for_checkout,
+)
+def test_refresh_deliveries_when_delivery_methods_stale_at_has_future_date(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ mocked_fetch_shipping_methods,
+ api_client,
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_with_item
+ existing_delivery = checkout_delivery(checkout)
+
+ checkout.shipping_address = address
+ checkout.assigned_delivery = existing_delivery
+ checkout.delivery_methods_stale_at = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.save()
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["deliveryOptionsCalculate"]
+
+ # then
+ assert not data["errors"]
+ assert len(data["deliveries"]) == 1
+
+ existing_delivery.refresh_from_db()
+ assert existing_delivery.is_valid
+ assert data["deliveries"][0]["shippingMethod"]["name"] == existing_delivery.name
+ assert CheckoutDelivery.objects.filter(checkout=checkout).count() == 1
+ assert mocked_fetch_shipping_methods.called
+ assert mocked_list_shipping_methods.called
+ assert mocked_exclude_shipping_methods.called
+
+
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout",
+ wraps=excluded_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout",
+ wraps=list_shipping_methods_for_checkout,
+)
+def test_when_refreshed_delivery_has_different_details(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ api_client,
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_with_item
+ assigned_delivery = checkout_delivery(checkout)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.shipping_address = address
+ checkout.save()
+
+ expected_name = assigned_delivery.name
+ assigned_delivery.name = "PreviousName"
+ assigned_delivery.save()
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["deliveryOptionsCalculate"]
+
+ # then
+ refreshed_delivery = CheckoutDelivery.objects.exclude(id=assigned_delivery.id).get()
+ assigned_delivery.refresh_from_db()
+ assert not assigned_delivery.is_valid
+ assert (
+ assigned_delivery.built_in_shipping_method_id
+ == refreshed_delivery.built_in_shipping_method_id
+ )
+ assert refreshed_delivery.is_valid
+
+ assert not data["errors"]
+ assert len(data["deliveries"]) == 1
+ assert data["deliveries"][0]["id"] == graphene.Node.to_global_id(
+ "CheckoutDelivery", refreshed_delivery.pk
+ )
+ assert data["deliveries"][0]["shippingMethod"]["name"] == expected_name
+
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assert mocked_list_shipping_methods.called
+ assert mocked_exclude_shipping_methods.called
+
+
+ "saleor.graphql.shipping.mutations.delivery_options_calculate.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout",
+ wraps=excluded_shipping_methods_for_checkout,
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout",
+ wraps=list_shipping_methods_for_checkout,
+)
+def test_refresh_deliveries_when_assigned_delivery_is_none(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ mocked_fetch_shipping_methods,
+ api_client,
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_with_item
+ existing_delivery = checkout_delivery(checkout)
+
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ assert not checkout.assigned_delivery
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = api_client.post_graphql(DELIVERY_OPTIONS_CALCULATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["deliveryOptionsCalculate"]
+
+ # then
+ assert not data["errors"]
+ assert len(data["deliveries"]) == 1
+
+ checkout.refresh_from_db()
+ assert not checkout.assigned_delivery
+
+ existing_delivery.refresh_from_db()
+ assert existing_delivery.is_valid
+ assert data["deliveries"][0]["shippingMethod"]["name"] == existing_delivery.name
+ assert CheckoutDelivery.objects.filter(checkout=checkout).count() == 1
+ assert mocked_fetch_shipping_methods.called
+ assert mocked_list_shipping_methods.called
+ assert mocked_exclude_shipping_methods.called
diff --git a/saleor/shipping/error_codes.py b/saleor/shipping/error_codes.py
index df14840794..bde09c4c1f 100644
--- a/saleor/shipping/error_codes.py
+++ b/saleor/shipping/error_codes.py
@@ -10,3 +10,9 @@ class ShippingErrorCode(Enum):
REQUIRED = "required"
UNIQUE = "unique"
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
+
+
+class DeliveryOptionsCalculateErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ INVALID = "invalid"