Skip to content

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

Fix checkout payload crash when assigned delivery is deleted concurrently (#19820)

Lukasz Ostrowski38a37f7d77cd
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 1428120d56..b4fe973349 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -12,7 +12,7 @@ from django.db.models import F, QuerySet, Sum
from ..account.models import User
from ..attribute.models import AttributeValueTranslation
-from ..checkout.models import Checkout
+from ..checkout.models import Checkout, CheckoutDelivery
from ..checkout.utils import get_checkout_metadata
from ..core.db.connection import allow_writer
from ..core.prices import quantize_price, quantize_price_fields
@@ -534,10 +534,17 @@ def generate_checkout_payload(
else:
warehouse = Warehouse.objects.for_channel(checkout.channel_id).first()
+ try:
+ assigned_delivery = checkout.assigned_delivery
+ except CheckoutDelivery.DoesNotExist:
+ # Deleted by a concurrent request after the checkout was fetched; the DB
+ # has already nulled the FK (SET_NULL), so treat it as no delivery.
+ assigned_delivery = None
+
shipping_method = None
- if checkout.assigned_delivery and not checkout.assigned_delivery.is_external:
+ if assigned_delivery and not assigned_delivery.is_external:
shipping_method = ShippingMethod.objects.filter(
- id=checkout.assigned_delivery.shipping_method_id
+ id=assigned_delivery.shipping_method_id
).first()
checkout_data = serializer.serialize(
[checkout],
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index ca201167c6..a3191a28e1 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -13,6 +13,7 @@ from django.core.serializers.json import DjangoJSONEncoder
from freezegun import freeze_time
from ... import __version__
+from ...checkout.models import Checkout, CheckoutDelivery
from ...core.prices import quantize_price
from ...core.utils.json_serializer import CustomJsonEncoder
from ...discount import DiscountType, DiscountValueType
@@ -1532,6 +1533,23 @@ def test_generate_checkout_payload(
}
+def test_generate_checkout_payload_assigned_delivery_deleted_concurrently(
+ checkout_with_prices, customer_user
+):
+ # given
+ assigned_delivery_id = checkout_with_prices.assigned_delivery_id
+ assert assigned_delivery_id is not None
+ stale_checkout = Checkout.objects.get(pk=checkout_with_prices.pk)
+ CheckoutDelivery.objects.filter(pk=assigned_delivery_id).delete()
+
+ # when
+ payload = json.loads(generate_checkout_payload(stale_checkout, customer_user))[0]
+
+ # then
+ assert payload["shipping_method"] is None
+ assert payload["token"] == graphene.Node.to_global_id("Checkout", stale_checkout.pk)
+
+
def test_generate_requestor_returns_dict_with_user_id_and_user_type(staff_user, rf):
request = rf.request()
request.user = staff_user