Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Prevent creation of fulfillment in case of race thread (#17156)
Krzysztof Waliczek49fa050cda23
diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.pyindex 6e72f917d9..30994a47dd 100644--- a/saleor/graphql/order/mutations/order_fulfill.py+++ b/saleor/graphql/order/mutations/order_fulfill.py@@ -4,12 +4,12 @@ from uuid import UUIDimport graphenefrom django.core.exceptions import ValidationError-from django.template.defaultfilters import pluralizefrom ....core.exceptions import InsufficientStockfrom ....order import models as order_modelsfrom ....order.actions import OrderFulfillmentLineInfo, create_fulfillmentsfrom ....order.error_codes import OrderErrorCode+from ....order.utils import clean_order_line_quantitiesfrom ....permission.enums import OrderPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promise@@ -126,29 +126,7 @@ class OrderFulfill(BaseMutation):@classmethoddef clean_lines(cls, order_lines, quantities_for_lines):- for order_line, line_quantities in zip(order_lines, quantities_for_lines):- line_total_quantity = sum(line_quantities)- line_quantity_unfulfilled = order_line.quantity_unfulfilled-- if line_total_quantity > line_quantity_unfulfilled:- msg = (- "Only %(quantity)d item%(item_pluralize)s remaining to fulfill."- ) % {- "quantity": line_quantity_unfulfilled,- "item_pluralize": pluralize(line_quantity_unfulfilled),- }- order_line_global_id = graphene.Node.to_global_id(- "OrderLine", order_line.pk- )- raise ValidationError(- {- "order_line_id": ValidationError(- msg,- code=OrderErrorCode.FULFILL_ORDER_LINE.value,- params={"order_lines": [order_line_global_id]},- )- }- )+ clean_order_line_quantities(order_lines, quantities_for_lines)@classmethoddef check_warehouses_for_duplicates(cls, warehouse_ids):diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.pyindex 19aed89f74..f0ba444150 100644--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py@@ -13,6 +13,7 @@ from .....order.actions import call_order_events, order_fulfilledfrom .....order.error_codes import OrderErrorCodefrom .....order.models import Fulfillment, FulfillmentLinefrom .....product.models import ProductVariant+from .....tests import race_conditionfrom .....warehouse.models import Allocation, Stockfrom .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -1657,3 +1658,50 @@ def test_order_fulfill_triggers_webhooks(any_order=True,)assert wrapped_call_order_events.called+++def test_order_fulfill_fulfilled_order_race_condition(+ staff_api_client,+ staff_user,+ order_with_lines,+ permission_group_manage_orders,+ warehouse,+):+ # given+ query = ORDER_FULFILL_MUTATION+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order_id = graphene.Node.to_global_id("Order", order_with_lines.id)+ order_line = order_with_lines.lines.first()+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 100, "warehouse": warehouse_id}],+ }+ ]+ },+ }++ def fulfill_line():+ order_line.quantity_fulfilled = 100+ order_line.save()++ # when+ with race_condition.RunBefore(+ "saleor.order.actions.create_fulfillments", fulfill_line+ ):+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderFulfill"]+ assert data["errors"]+ error = data["errors"][0]+ assert error["field"] == "orderLineId"+ assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name+ assert error["orderLines"] == [order_line_id]+ assert not error["warehouse"]diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.pyindex 6ce37d2318..c2eaad4769 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py@@ -13,8 +13,8 @@ from ....core.postgres import FlatConcatSearchVectorfrom ....core.tracing import traced_atomic_transactionfrom ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....order import events as order_events-from ....order import models as order_modelsfrom ....order.tasks import recalculate_orders_task+from ....order.utils import order_lines_qs_select_for_updatefrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....product.search import prepare_product_search_vector_value@@ -120,7 +120,7 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):response = super().perform_mutation(_root, info, ids=ids, **data)# delete order lines for deleted variants, they are ordered by Meta- order_models.OrderLine.objects.select_for_update(of=("self",)).filter(+ order_lines_qs_select_for_update().filter(pk__in=draft_order_lines_data.line_pks).delete()diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 2706130b1e..aea786bbde 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -19,6 +19,7 @@ from ..core.utils.events import (webhook_async_event_requires_sync_webhooks_to_trigger,)from ..giftcard import GiftCardLineData+from ..order.utils import order_lines_qs_select_for_updatefrom ..payment import (ChargeStatus,CustomPaymentChoices,@@ -69,6 +70,7 @@ from .notifications import (send_payment_confirmation,)from .utils import (+ clean_order_line_quantities,get_valid_shipping_methods_for_order,order_line_needs_automatic_fulfillment,restock_fulfillment_lines,@@ -1298,7 +1300,23 @@ def create_fulfillments(if approvedelse FulfillmentStatus.WAITING_FOR_APPROVAL)++ order_line_quantities_to_fulfill: defaultdict[UUID, list[int]] = defaultdict(list)+ for _, lines in fulfillment_lines_for_warehouses.items():+ for line in lines:+ order_line = line["order_line"]+ order_line_quantities_to_fulfill[order_line.pk].append(line["quantity"])+with traced_atomic_transaction():+ # refresh order lines from db to prevent race condition+ order_lines = order_lines_qs_select_for_update().filter(+ pk__in=order_line_quantities_to_fulfill.keys()+ )+ quantities_for_lines: list[list[int]] = [+ order_line_quantities_to_fulfill[line.pk] for line in order_lines+ ]+ clean_order_line_quantities(order_lines, quantities_for_lines)+for warehouse_pk in fulfillment_lines_for_warehouses:fulfillment = Fulfillment.objects.create(order=order, status=status, tracking_number=tracking_numberdiff --git a/saleor/order/tests/test_fulfillments_actions.py b/saleor/order/tests/test_fulfillments_actions.pyindex 14dbce9480..8f32b66e3f 100644--- a/saleor/order/tests/test_fulfillments_actions.py+++ b/saleor/order/tests/test_fulfillments_actions.py@@ -1,6 +1,7 @@from unittest.mock import patchimport pytest+from django.core.exceptions import ValidationErrorfrom ...core.exceptions import InsufficientStockfrom ...order import OrderEvents@@ -759,3 +760,36 @@ def test_create_fulfillments_quantity_allocated_lower_than_line_quantity(mock_email_fulfillment.assert_called_once_with(order, order.fulfillments.get(), staff_user, None, manager)+++def test_create_fulfillments_validate_lines_raise_error(+ staff_user,+ order_with_lines,+ warehouse,+ site_settings,+):+ # given+ order = order_with_lines+ order_line1, order_line2 = order.lines.all()+ order_line1.quantity_fulfilled = 3+ order_line1.save()+ order_line2.quantity_fulfilled = 2+ order_line2.save()+ fulfillment_lines_for_warehouses = {+ warehouse.pk: [+ {"order_line": order_line1, "quantity": 3},+ {"order_line": order_line2, "quantity": 2},+ ]+ }+ manager = get_plugins_manager(allow_replica=False)+ # when & then+ with pytest.raises(ValidationError):+ create_fulfillments(+ staff_user,+ None,+ order,+ fulfillment_lines_for_warehouses,+ manager,+ site_settings,+ True,+ )diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 8bb7975365..ea11930578 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -5,7 +5,9 @@ from typing import TYPE_CHECKING, Optional, castimport graphenefrom django.conf import settings+from django.core.exceptions import ValidationErrorfrom django.db.models import QuerySet, Sum+from django.template.defaultfilters import pluralizefrom django.utils import timezonefrom prices import Money, TaxedMoney@@ -54,6 +56,7 @@ from . import (OrderStatus,events,)+from .error_codes import OrderErrorCodefrom .fetch import OrderLineInfo, fetch_draft_order_lines_infofrom .models import Order, OrderGrantedRefund, OrderLine@@ -68,6 +71,10 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+def order_lines_qs_select_for_update():+ return OrderLine.objects.order_by("pk").select_for_update(of=["self"])++def get_order_country(order: Order) -> str:"""Return country to which order will be shipped."""return get_active_country(@@ -1285,3 +1292,27 @@ def order_info_for_logs(order: Order, lines: Iterable[OrderLine]):for line_info in lines_info],}+++def clean_order_line_quantities(order_lines, quantities_for_lines):+ for order_line, line_quantities in zip(order_lines, quantities_for_lines):+ line_total_quantity = sum(line_quantities)+ line_quantity_unfulfilled = order_line.quantity_unfulfilled++ if line_total_quantity > line_quantity_unfulfilled:+ msg = ("Only %(quantity)d item%(item_pluralize)s remaining to fulfill.") % {+ "quantity": line_quantity_unfulfilled,+ "item_pluralize": pluralize(line_quantity_unfulfilled),+ }+ order_line_global_id = graphene.Node.to_global_id(+ "OrderLine", order_line.pk+ )+ raise ValidationError(+ {+ "order_line_id": ValidationError(+ msg,+ code=OrderErrorCode.FULFILL_ORDER_LINE.value,+ params={"order_lines": [order_line_global_id]},+ )+ }+ )