Skip to content

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

Fix: checkout deliveries invalidation (#19228)

Lukasz Ostrowskic66efabd1599
diff --git a/saleor/checkout/delivery_context.py b/saleor/checkout/delivery_context.py
index e8c638d122..68a9da61e1 100644
--- a/saleor/checkout/delivery_context.py
+++ b/saleor/checkout/delivery_context.py
@@ -425,6 +425,17 @@ def _restore_assigned_delivery_as_valid(
def _invalidate_assigned_delivery(assigned_delivery: CheckoutDelivery):
+ # The unique constraint `unique_for_checkout` allows at most one row per
+ # (checkout, shipping_method, is_valid) tuple. A stale invalid sibling may
+ # already exist for the same shipping method, so remove it before flipping
+ # the flag to avoid a duplicate key violation.
+ CheckoutDelivery.objects.filter(
+ checkout_id=assigned_delivery.checkout_id,
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id,
+ built_in_shipping_method_id=assigned_delivery.built_in_shipping_method_id,
+ is_valid=False,
+ ).exclude(pk=assigned_delivery.pk).delete()
+
assigned_delivery.is_valid = False
assigned_delivery.save(update_fields=["is_valid"])
diff --git a/saleor/checkout/tests/test_delivery_context.py b/saleor/checkout/tests/test_delivery_context.py
index 93e305297b..16de9922fb 100644
--- a/saleor/checkout/tests/test_delivery_context.py
+++ b/saleor/checkout/tests/test_delivery_context.py
@@ -1563,3 +1563,169 @@ def test_is_valid_delivery_method(
delivery_method_info = checkout_info.get_delivery_method_info()
assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_invalidates_assigned_when_stale_invalid_sibling_exists(
+ checkout_with_item, plugins_manager, address, settings
+):
+ """Test that it deletes duplicate rows when invalidating delivery method.
+
+ Regression test: the unique constraint `unique_for_checkout` allows at most
+ one row per (checkout, shipping_method, is_valid). When a stale invalid
+ row already exists for the same shipping method as the assigned (valid)
+ delivery, invalidating the assigned row used to raise IntegrityError
+ because it would collide with the stale sibling.
+ """
+
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = (
+ timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ available_shipping_method = ShippingMethod.objects.get()
+ non_applicable_shipping_method_id = available_shipping_method.id + 1
+
+ assigned_delivery = checkout.deliveries.create(
+ built_in_shipping_method_id=non_applicable_shipping_method_id,
+ name="Nonexisting Shipping Method",
+ price_amount=Decimal(99),
+ currency="USD",
+ is_valid=True,
+ )
+ stale_invalid_sibling = checkout.deliveries.create(
+ built_in_shipping_method_id=non_applicable_shipping_method_id,
+ name="Nonexisting Shipping Method",
+ price_amount=Decimal(99),
+ currency="USD",
+ is_valid=False,
+ )
+ 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
+ ).get()
+
+ # then
+ assert len(shipping_methods) == 1
+
+ assigned_delivery.refresh_from_db()
+ assert assigned_delivery.is_valid is False
+
+ assert not CheckoutDelivery.objects.filter(pk=stale_invalid_sibling.pk).exists()
+
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "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_preserve_invalidates_when_stale_invalid_sibling_exists(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+ app,
+):
+ """Ensure it preserves existing delivery methods when they don't conflict.
+
+ Regression test for the preserve path: when the refreshed external shipping
+ method has changed and the assigned (valid) delivery has a stale invalid
+ sibling, _preserve_assigned_delivery used to fail with IntegrityError when
+ flipping is_valid on the assigned row.
+ """
+
+ # 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"},
+ )
+
+ checkout = checkout_with_item
+ assigned_delivery = convert_shipping_method_data_to_checkout_delivery(
+ available_shipping_method, checkout
+ )
+ assigned_delivery.is_valid = True
+ assigned_delivery.save()
+
+ stale_invalid_sibling = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id,
+ built_in_shipping_method_id=None,
+ name="Stale",
+ price_amount=shipping_price_amount.amount,
+ currency=checkout.currency,
+ 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()
+
+ 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
+ assigned_delivery.refresh_from_db()
+ assert assigned_delivery.is_valid is False
+ assert assigned_delivery.price == shipping_price_amount
+
+ assert not CheckoutDelivery.objects.filter(pk=stale_invalid_sibling.pk).exists()
+
+ deliveries = CheckoutDelivery.objects.filter(
+ external_shipping_method_id=assigned_delivery.external_shipping_method_id
+ )
+ assert len(deliveries) == 2
+ refreshed_delivery = next(
+ delivery for delivery in deliveries if delivery.id != assigned_delivery.id
+ )
+ assert refreshed_delivery.is_valid is True
+ assert refreshed_delivery.price == changed_shipping_price_amount
+
+ assert len(shipping_methods) == 2
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
diff --git a/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py b/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py
index 8421119478..453c203078 100644
--- a/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py
+++ b/saleor/graphql/shipping/tests/mutations/test_delivery_options_calculate.py
@@ -326,6 +326,89 @@ def test_when_refreshed_delivery_has_different_details(
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_assigned_delivery_has_stale_invalid_sibling(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ api_client,
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
+ """Ensure it deletes duplicate delivery method on conflict.
+
+ Regression test for the IntegrityError on `unique_for_checkout` raised
+ when the assigned (valid) delivery is invalidated while a stale invalid
+ sibling row for the same shipping method already exists. Matches the
+ Sentry signature: POST /graphql/ -> IntegrityError in
+ `_invalidate_assigned_delivery`.
+ """
+
+ # given
+ checkout = checkout_with_item
+ assigned_delivery = checkout_delivery(checkout)
+ stale_invalid_sibling = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ built_in_shipping_method_id=assigned_delivery.built_in_shipping_method_id,
+ external_shipping_method_id=None,
+ name=assigned_delivery.name,
+ price_amount=assigned_delivery.price_amount,
+ currency=assigned_delivery.currency,
+ is_valid=False,
+ )
+
+ checkout.assigned_delivery = assigned_delivery
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.save()
+
+ # Force the refresh path to treat the refreshed delivery as "changed"
+ # so `_preserve_assigned_delivery` reaches `_invalidate_assigned_delivery`.
+ expected_name = assigned_delivery.name
+ assigned_delivery.name = "PreviousName"
+ assigned_delivery.save(update_fields=["name"])
+
+ 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
+
+ assigned_delivery.refresh_from_db()
+ assert assigned_delivery.is_valid is False
+
+ assert not CheckoutDelivery.objects.filter(pk=stale_invalid_sibling.pk).exists()
+
+ refreshed_delivery = CheckoutDelivery.objects.exclude(id=assigned_delivery.id).get()
+ assert refreshed_delivery.is_valid is True
+ assert refreshed_delivery.name == expected_name
+ assert (
+ refreshed_delivery.built_in_shipping_method_id
+ == assigned_delivery.built_in_shipping_method_id
+ )
+
+ assert data["deliveries"][0]["id"] == graphene.Node.to_global_id(
+ "CheckoutDelivery", refreshed_delivery.pk
+ )
+
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assert mocked_list_shipping_methods.called
+ assert mocked_exclude_shipping_methods.called
+
+
@mock.patch(
"saleor.graphql.shipping.mutations.delivery_options_calculate.fetch_shipping_methods_for_checkout",
wraps=fetch_shipping_methods_for_checkout,