Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle no stocks in approve order fulfillment (#8358)
L3str4nge88662b3a5d06
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.pyindex 6128c9f39c..69caa9ace2 100644--- a/saleor/core/exceptions.py+++ b/saleor/core/exceptions.py@@ -11,7 +11,7 @@ if TYPE_CHECKING:@dataclassclass InsufficientStockData:- variant: "ProductVariant"+ variant: Optional["ProductVariant"] = Nonecheckout_line: Optional["CheckoutLine"] = Noneorder_line: Optional["OrderLine"] = Nonewarehouse_pk: Union[str, int, None] = None@@ -20,8 +20,8 @@ class InsufficientStockData:class InsufficientStock(Exception):def __init__(self, items: List[InsufficientStockData]):- variants = [str(item.variant) for item in items]- super().__init__(f"Insufficient stock for {', '.join(variants)}")+ details = [str(item.variant or item.order_line) for item in items]+ super().__init__(f"Insufficient stock for {', '.join(details)}")self.items = itemsself.code = CheckoutErrorCode.INSUFFICIENT_STOCKdiff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex 7c3f845ab8..d3ab4723e9 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -12,7 +12,7 @@ from ....order.error_codes import OrderErrorCodefrom ....order.events import OrderEventsfrom ....order.models import Fulfillment, FulfillmentLine, FulfillmentStatusfrom ....plugins.manager import get_plugins_manager-from ....product.models import ProductVariant+from ....product.models import Product, ProductVariantfrom ....warehouse.models import Allocation, Stockfrom ...tests.utils import assert_no_permission, get_graphql_content@@ -1748,6 +1748,82 @@ def test_fulfillment_approve(assert event.user == staff_api_client.user+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)+def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceeded_true(+ mock_email_fulfillment,+ staff_api_client,+ fulfillment,+ permission_manage_orders,+):+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL+ fulfillment.save(update_fields=["status"])++ Product.objects.all().delete()++ query = APPROVE_FULFILLMENT_MUTATION+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)+ variables = {+ "id": fulfillment_id,+ "notifyCustomer": True,+ "allowStockToBeExceeded": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfillmentApprove"]+ assert not data["errors"]+ assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper()+ assert data["order"]["status"] == OrderStatus.FULFILLED.upper()+ fulfillment.refresh_from_db()+ assert fulfillment.status == FulfillmentStatus.FULFILLED++ assert mock_email_fulfillment.call_count == 1+ events = fulfillment.order.events.all()+ assert len(events) == 1+ event = events[0]+ assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS+ assert event.user == staff_api_client.user+++@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)+def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceeded_false(+ mock_email_fulfillment,+ staff_api_client,+ fulfillment,+ permission_manage_orders,+):+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL+ fulfillment.save(update_fields=["status"])++ Product.objects.all().delete()++ query = APPROVE_FULFILLMENT_MUTATION+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)+ variables = {+ "id": fulfillment_id,+ "notifyCustomer": True,+ "allowStockToBeExceeded": False,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response, ignore_errors=True)+ errors = content["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["message"]+ == "Insufficient stock for Test product (SKU_AA), Test product 2 (SKU_B)"+ )++ fulfillment.refresh_from_db()+ assert fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL++ assert mock_email_fulfillment.call_count == 1+ events = fulfillment.order.events.all()+ assert len(events) == 0++@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)def test_fulfillment_approve_gift_cards_created(mock_email_fulfillment,diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 3a88e54e75..b9faefe1e0 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -405,17 +405,33 @@ def approve_fulfillment()lines_to_fulfill = []gift_card_lines_info = []+ insufficient_stocks = []for fulfillment_line in fulfillment.lines.all().prefetch_related("order_line__variant"):order_line = fulfillment_line.order_linevariant = fulfillment_line.order_line.variant++ stock = fulfillment_line.stock++ if stock is None:+ warehouse_pk = None+ if not allow_stock_to_be_exceeded:+ error_data = InsufficientStockData(+ variant=variant,+ order_line=order_line,+ warehouse_pk=warehouse_pk,+ )+ insufficient_stocks.append(error_data)+ else:+ warehouse_pk = stock.warehouse_id+lines_to_fulfill.append(OrderLineData(line=order_line,quantity=fulfillment_line.quantity,variant=variant,- warehouse_pk=str(fulfillment_line.stock.warehouse_id), # type: ignore+ warehouse_pk=str(warehouse_pk) if warehouse_pk else None,))if order_line.is_gift_card:@@ -427,6 +443,10 @@ def approve_fulfillment(fulfillment_line=fulfillment_line,))++ if insufficient_stocks:+ raise InsufficientStock(insufficient_stocks)+_decrease_stocks(lines_to_fulfill, manager, allow_stock_to_be_exceeded)order.refresh_from_db()update_order_status(order)