Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix mismatch between stock.quantity_allocated & quantity from the allocations (#17657)
Maciej Korycinski0696ec30d606
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9b46756c98..3cba8f330b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -118,3 +118,5 @@ All notable, unreleased changes to this project will be documented in this file.- Fixes incorrect gift card balances after covering the full order total - #17566 by @korycins- Fixes tax class not clearing when selecting a shipping method without a tax class - #17560 by @korycins- The prices for draft orders created in `OrderBulkCreate` now are properly calculated - #17583 by @IKarbowiak+- Fixes incorrect stock deallocation when multiple order lines share the same ProductVariant - #17657 by @korycins+- Decrease allocations for lines with inventory tracking disabled, if allocations exist - #17657 by @korycinsdiff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex 635ae25b7e..e9aac26af1 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -74,10 +74,11 @@ class OrderLineUpdate(def save(cls, info: ResolveInfo, instance, cleaned_input):manager = get_plugin_manager_promise(info.context).get()+ order_is_unconfirmed = instance.order.is_unconfirmed()line_allocation = instance.allocations.first()warehouse_pk = (line_allocation.stock.warehouse.pk- if line_allocation and instance.order.is_unconfirmed()+ if line_allocation and order_is_unconfirmedelse None)app = get_app_promise(info.context).get()@@ -98,6 +99,7 @@ class OrderLineUpdate(instance.quantity,order,manager,+ allocate_stock=order_is_unconfirmed,)except InsufficientStock as e:raise ValidationError(diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.pyindex 85b8233a3a..a9feb23275 100644--- a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py@@ -44,13 +44,13 @@ def test_fulfillment_approve(mock_email_fulfillment,mock_fulfillment_approved,staff_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_group_manage_orders,):# givenpermission_group_manage_orders.user_set.add(staff_api_client.user)- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approval+query = APPROVE_FULFILLMENT_MUTATIONfulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)variables = {"id": fulfillment_id, "notifyCustomer": True}@@ -78,19 +78,17 @@ def test_fulfillment_approve(def test_fulfillment_approve_by_user_no_channel_access(staff_api_client,- fulfillment,+ partial_fulfillment_awaiting_approval,permission_group_all_perms_channel_USD_only,channel_PLN,):# givenpermission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)+ fulfillment = partial_fulfillment_awaiting_approvalorder = fulfillment.orderorder.channel = channel_PLNorder.save(update_fields=["channel"])- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])-query = APPROVE_FULFILLMENT_MUTATIONfulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)variables = {"id": fulfillment_id, "notifyCustomer": True}@@ -108,12 +106,11 @@ def test_fulfillment_approve_by_app(mock_email_fulfillment,mock_fulfillment_approved,app_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_manage_orders,):# given- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approvalquery = APPROVE_FULFILLMENT_MUTATIONfulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)variables = {"id": fulfillment_id, "notifyCustomer": True}@@ -146,12 +143,11 @@ def test_fulfillment_approve_by_app(def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceeded_true(mock_email_fulfillment,staff_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_group_manage_orders,):permission_group_manage_orders.user_set.add(staff_api_client.user)- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approvalProduct.objects.all().delete()@@ -185,14 +181,13 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceedemock_email_fulfillment,mock_fulfillment_approved,staff_api_client,- fulfillment,+ partial_fulfillment_awaiting_approval,permission_group_manage_orders,django_capture_on_commit_callbacks,):# givenpermission_group_manage_orders.user_set.add(staff_api_client.user)- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = partial_fulfillment_awaiting_approvalProduct.objects.all().delete()@@ -243,14 +238,13 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceededef test_fulfillment_approve_gift_cards_created(mock_email_fulfillment,staff_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_group_manage_orders,gift_card_shippable_order_line,gift_card_non_shippable_order_line,):permission_group_manage_orders.user_set.add(staff_api_client.user)- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approvalgift_card_line_1 = gift_card_shippable_order_linegift_card_line_2 = gift_card_non_shippable_order_line@@ -312,17 +306,18 @@ def test_fulfillment_approve_gift_cards_created(def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(mock_email_fulfillment,staff_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_group_manage_orders,):# make stocks exceededpermission_group_manage_orders.user_set.add(staff_api_client.user)- for stock in [line.stock for line in fulfillment.lines.all()]:+ for stock in [+ line.stock for line in full_fulfillment_awaiting_approval.lines.all()+ ]:stock.quantity = -99stock.save()- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approvalquery = APPROVE_FULFILLMENT_MUTATIONfulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)@@ -353,17 +348,18 @@ def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(def test_fulfillment_approve_when_stock_is_exceeded_and_flag_disabled(mock_email_fulfillment,staff_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_group_manage_orders,):# make stocks exceededpermission_group_manage_orders.user_set.add(staff_api_client.user)- for stock in [line.stock for line in fulfillment.lines.all()]:+ for stock in [+ line.stock for line in full_fulfillment_awaiting_approval.lines.all()+ ]:stock.quantity = -99stock.save()- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approvalquery = APPROVE_FULFILLMENT_MUTATIONfulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)@@ -402,13 +398,13 @@ def test_fulfillment_approve_partial_order_fulfill(mock_email_fulfillment,mock_fulfillment_approved,staff_api_client,- fulfillment_awaiting_approval,+ partial_fulfillment_awaiting_approval,permission_group_manage_orders,):# givenpermission_group_manage_orders.user_set.add(staff_api_client.user)query = APPROVE_FULFILLMENT_MUTATION- order = fulfillment_awaiting_approval.order+ order = partial_fulfillment_awaiting_approval.ordersecond_fulfillment = order.fulfillments.create()line_1 = order.lines.first()@@ -428,7 +424,7 @@ def test_fulfillment_approve_partial_order_fulfill(OrderLine.objects.bulk_update([line_1, line_2], ["quantity_fulfilled"])fulfillment_id = graphene.Node.to_global_id(- "Fulfillment", fulfillment_awaiting_approval.id+ "Fulfillment", partial_fulfillment_awaiting_approval.id)variables = {"id": fulfillment_id, "notifyCustomer": False}@@ -441,12 +437,12 @@ def test_fulfillment_approve_partial_order_fulfill(assert not data["errors"]assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper()assert data["order"]["status"] == "PARTIALLY_FULFILLED"- fulfillment_awaiting_approval.refresh_from_db()- assert fulfillment_awaiting_approval.status == FulfillmentStatus.FULFILLED+ partial_fulfillment_awaiting_approval.refresh_from_db()+ assert partial_fulfillment_awaiting_approval.status == FulfillmentStatus.FULFILLEDassert mock_email_fulfillment.call_count == 0mock_fulfillment_approved.assert_called_once_with(- fulfillment_awaiting_approval, False+ partial_fulfillment_awaiting_approval, False)@@ -516,7 +512,7 @@ def test_fulfillment_approve_preorder(def test_fulfillment_approve_trigger_webhook_event(mocked_trigger_async,staff_api_client,- fulfillment,+ full_fulfillment_awaiting_approval,permission_group_manage_orders,settings,subscription_fulfillment_approved_webhook,@@ -524,8 +520,8 @@ def test_fulfillment_approve_trigger_webhook_event(# givensettings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]permission_group_manage_orders.user_set.add(staff_api_client.user)- fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL- fulfillment.save(update_fields=["status"])+ fulfillment = full_fulfillment_awaiting_approval+query = APPROVE_FULFILLMENT_MUTATIONfulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)variables = {"id": fulfillment_id, "notifyCustomer": True}diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex d0fd408fef..926afac755 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -37,9 +37,8 @@ from ..plugins.manager import PluginsManagerfrom ..shipping.models import ShippingMethodChannelListingfrom ..warehouse.management import (deallocate_stock,- deallocate_stock_for_order,+ deallocate_stock_for_orders,decrease_stock,- get_order_lines_with_track_inventory,)from ..warehouse.models import Stockfrom ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType@@ -419,7 +418,7 @@ def cancel_order(# transaction ensures proper allocation and event triggeringwith traced_atomic_transaction():events.order_canceled_event(order=order, user=user, app=app)- deallocate_stock_for_order(order, manager)+ deallocate_stock_for_orders([order.id], manager)order.status = OrderStatus.CANCELEDorder.save(update_fields=["status", "updated_at"])if not webhook_event_map:@@ -900,7 +899,11 @@ def approve_fulfillment(if insufficient_stocks:raise InsufficientStock(insufficient_stocks)- _decrease_stocks(lines_to_fulfill, manager, allow_stock_to_be_exceeded)+ decrease_stock(+ lines_to_fulfill,+ manager,+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,+ )order.refresh_from_db()order_fulfilled([fulfillment],@@ -1032,16 +1035,6 @@ def clean_mark_order_as_paid(order: "Order"):)-def _decrease_stocks(order_lines_info, manager, allow_stock_to_be_exceeded=False):- lines_to_decrease_stock = get_order_lines_with_track_inventory(order_lines_info)- if lines_to_decrease_stock:- decrease_stock(- lines_to_decrease_stock,- manager,- allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,- )--def _increase_order_line_quantity(order_lines_info):order_lines = []for line_info in order_lines_info:@@ -1061,7 +1054,11 @@ def fulfill_order_lines(# transaction ensures that there is a consistency between quantities in order line# and stockswith traced_atomic_transaction():- _decrease_stocks(order_lines_info, manager, allow_stock_to_be_exceeded)+ decrease_stock(+ order_lines_info,+ manager,+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,+ )_increase_order_line_quantity(order_lines_info)@@ -1136,7 +1133,7 @@ def _create_fulfillment_lines(channel_slug: str,gift_card_lines_info: list[GiftCardLineData],manager: "PluginsManager",- decrease_stock: bool = True,+ should_decrease_stock: bool = True,allow_stock_to_be_exceeded: bool = False,) -> list[FulfillmentLine]:"""Modify stocks and allocations. Return list of unsaved FulfillmentLines.@@ -1157,7 +1154,7 @@ def _create_fulfillment_lines(gift_card_lines_info (List): List with information requiredto create gift cards.manager (PluginsManager): Plugin manager from given context- decrease_stock (Bool): Stocks will get decreased if this is True.+ should_decrease_stock (Bool): Stocks will get decreased if this is True.allow_stock_to_be_exceeded (bool): If `True` then stock quantity could exceed.Default value is set to `False`.@@ -1239,8 +1236,13 @@ def _create_fulfillment_lines(raise InsufficientStock(insufficient_stocks)if lines_info:- if decrease_stock:- _decrease_stocks(lines_info, manager, allow_stock_to_be_exceeded)+ if should_decrease_stock:+ decrease_stock(+ lines_info,+ manager,+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,+ )+_increase_order_line_quantity(lines_info)return fulfillment_lines@@ -1338,7 +1340,7 @@ def create_fulfillments(order.channel.slug,gift_card_lines_info,manager,- decrease_stock=auto_approved,+ should_decrease_stock=auto_approved,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,))diff --git a/saleor/order/tests/fixtures/fulfillment.py b/saleor/order/tests/fixtures/fulfillment.pyindex c3c0d3bc5e..5091c66fff 100644--- a/saleor/order/tests/fixtures/fulfillment.py+++ b/saleor/order/tests/fixtures/fulfillment.py@@ -3,7 +3,7 @@ from typing import NamedTupleimport grapheneimport pytest-from ....warehouse.models import Warehouse+from ....warehouse.models import Stock, Warehousefrom ...models import FulfillmentLine, FulfillmentStatus, Order, OrderLine@@ -13,15 +13,39 @@ def fulfillment(fulfilled_order):@pytest.fixture-def fulfillment_awaiting_approval(fulfilled_order):+def full_fulfillment_awaiting_approval(fulfilled_order):fulfillment = fulfilled_order.fulfillments.first()fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVALfulfillment.save(update_fields=["status"])+ fulfillment_lines_to_update = []+ order_lines_to_update = []+ for f_line in fulfillment.lines.all():+ order_line = f_line.order_line+ f_line.stock.quantity = order_line.quantity+ f_line.quantity = order_line.quantity+ fulfillment_lines_to_update.append(f_line)++ order_line.quantity_fulfilled = order_line.quantity+ order_lines_to_update.append(order_line)++ Stock.objects.bulk_update(+ [line.stock for line in fulfillment_lines_to_update], ["quantity"]+ )+ FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])+ OrderLine.objects.bulk_update(order_lines_to_update, ["quantity_fulfilled"])++ return fulfillment+++def partial_fulfillment_awaiting_approval(full_fulfillment_awaiting_approval):+ fulfillment = full_fulfillment_awaiting_approvalquantity = 1fulfillment_lines_to_update = []order_lines_to_update = []for f_line in fulfillment.lines.all():+ f_line.stock.quantity = quantityf_line.quantity = quantityfulfillment_lines_to_update.append(f_line)@@ -29,6 +53,9 @@ def fulfillment_awaiting_approval(fulfilled_order):order_line.quantity_fulfilled = quantityorder_lines_to_update.append(order_line)+ Stock.objects.bulk_update(+ [line.stock for line in fulfillment_lines_to_update], ["quantity"]+ )FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])OrderLine.objects.bulk_update(order_lines_to_update, ["quantity_fulfilled"])diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex e909d214c2..190ad0e591 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -74,6 +74,7 @@ def test_change_quantity_generates_proper_event(new_quantity,order_with_lines,get_plugins_manager(allow_replica=False),+ allocate_stock=order_with_lines.is_unconfirmed(),)if removed_count:diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex ab65b99fbb..8ba5600cfb 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -375,14 +375,14 @@ def add_variant_to_order(Returns an order line the variant was added to."""- channel = order.channel-is_new_line = not line_data.line_idif not is_new_line:line = order.lines.get(pk=line_data.line_id)old_quantity = line.quantitynew_quantity = old_quantity + line_data.quantity- line_info = OrderLineInfo(line=line, quantity=old_quantity)+ line_info = OrderLineInfo(+ line=line, variant=line_data.variant, quantity=old_quantity+ )update_fields: list[str] = []if new_quantity and line_data.price_override is not None:update_line_base_unit_prices_with_custom_price(@@ -399,25 +399,12 @@ def add_variant_to_order(manager=manager,send_event=False,update_fields=update_fields,+ allocate_stock=allocate_stock,)if update_fields:line.save(update_fields=update_fields)- if allocate_stock:- increase_allocations(- [- OrderLineInfo(- line=line,- quantity=line_data.quantity,- variant=line_data.variant,- warehouse_pk=None,- )- ],- channel,- manager=manager,- )-return linereturn create_order_line(@@ -550,10 +537,9 @@ def _update_allocations_for_line(if old_quantity == new_quantity:return- if not get_order_lines_with_track_inventory([line_info]):- return-if old_quantity < new_quantity:+ if not get_order_lines_with_track_inventory([line_info]):+ returnline_info.quantity = new_quantity - old_quantityincrease_allocations([line_info], channel, manager)else:@@ -571,13 +557,14 @@ def change_order_line_quantity(manager: "PluginsManager",send_event: bool = True,update_fields: list[str] | None = None,+ allocate_stock: bool = False,):"""Change the quantity of ordered items in a order line."""line = line_info.linechannel = order.channelcurrency = channel.currency_codeif new_quantity:- if line.order.is_unconfirmed():+ if allocate_stock:_update_allocations_for_line(line_info, old_quantity, new_quantity, channel, manager)diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex f3dea1720e..8b8f9a2fed 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -35,7 +35,6 @@ from .models import (if TYPE_CHECKING:from ..channel.models import Channel- from ..order.models import Orderclass StockData(NamedTuple):@@ -192,14 +191,19 @@ def allocate_stocks(raise InsufficientStock(insufficient_stock)if allocations:- stocks_to_update = []- for alloc in Allocation.objects.bulk_create(allocations):- stock = alloc.stock- stock.quantity_allocated = (- F("quantity_allocated") + alloc.quantity_allocated- )- stocks_to_update.append(stock)- Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])+ Allocation.objects.bulk_create(allocations)++ stocks_to_update_map = {alloc.stock_id: alloc.stock for alloc in allocations}+ quantity_from_allocations: dict[int, int] = defaultdict(int)++ for alloc in allocations:+ quantity_from_allocations[alloc.stock_id] += alloc.quantity_allocated++ for stock_id, quantity in quantity_from_allocations.items():+ stock = stocks_to_update_map[stock_id]+ stock.quantity_allocated = F("quantity_allocated") + quantity++ Stock.objects.bulk_update(stocks_to_update_map.values(), ["quantity_allocated"])for allocation in allocations:allocated_stock = (@@ -446,6 +450,28 @@ def increase_stock(stock.save(update_fields=["quantity_allocated"])+def _reduce_quantity_allocated_for_stocks(+ allocations: Iterable[Allocation],+) -> list[Stock]:+ """Reduce quantity allocated for stocks from allocations.++ This function reduces the quantity allocated for stocks based on the allocations+ associated with them. It takes a list of Allocation objects and returns a list of+ Stock objects with their quantity_allocated field updated.+ """+ stocks_to_update_map: dict[int, Stock] = {+ alloc.stock_id: alloc.stock for alloc in allocations+ }+ quantity_allocated_to_reduce: dict[int, int] = defaultdict(int)+ for alloc in allocations:+ quantity_allocated_to_reduce[alloc.stock_id] += alloc.quantity_allocated++ for stock_pk, quantity_allocated in quantity_allocated_to_reduce.items():+ stock = stocks_to_update_map[stock_pk]+ stock.quantity_allocated = F("quantity_allocated") - quantity_allocated+ return list(stocks_to_update_map.values())++@traced_atomic_transaction()def increase_allocations(lines_info: list["OrderLineInfo"], channel: "Channel", manager: PluginsManager@@ -470,11 +496,10 @@ def increase_allocations(# line_info.quantity resembles amount to add, sum it with already allocated.line_info.quantity += allocated- stocks_to_update = []- for alloc in allocations:- stock = alloc.stock- stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated- stocks_to_update.append(stock)+ # Reduces quantity allocated for stocks from allocations, as `allocate_stocks`+ # will create new allocations.+ stocks_to_update = _reduce_quantity_allocated_for_stocks(allocations=allocations)+Allocation.objects.filter(pk__in=allocation_pks_to_delete).delete()Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])@@ -491,18 +516,22 @@ def increase_allocations(def decrease_allocations(lines_info: list["OrderLineInfo"], manager):- """Decreate allocations for provided order lines."""- tracked_lines = get_order_lines_with_track_inventory(lines_info)- if not tracked_lines:+ """Decrease allocations for provided order lines."""+ lines_to_deallocate = get_order_lines_to_deallocate(lines_info)+ if not lines_to_deallocate:return- decrease_stock(tracked_lines, update_stocks=False, manager=manager)+ try:+ deallocate_stock(lines_info, manager)+ except AllocationError as exc:+ Allocation.objects.order_by("stock_id").filter(+ order_line__in=exc.order_lines+ ).update(quantity_allocated=0)@traced_atomic_transaction()def decrease_stock(order_lines_info: list["OrderLineInfo"],manager,- update_stocks=True,allow_stock_to_be_exceeded: bool = False,):"""Decrease stocks quantities for given `order_lines` in given warehouses.@@ -512,18 +541,15 @@ def decrease_stock(stock in a given warehouse, if stock not exists or have not enough stock,the function raise InsufficientStock exception. When the stock has enough quantityfunction decrease it by given value.- If update_stocks is False, allocations will decrease but stocks quantities- will stay unmodified (case of unconfirmed order editing).If allow_stock_to_be_exceeded flag is True then quantity could be < 0."""+ decrease_allocations(order_lines_info, manager)++ order_lines_info = get_order_lines_with_track_inventory(order_lines_info)+ if not order_lines_info:+ returnvariants = [line_info.variant for line_info in order_lines_info]warehouse_pks = [line_info.warehouse_pk for line_info in order_lines_info]- try:- deallocate_stock(order_lines_info, manager)- except AllocationError as exc:- Allocation.objects.order_by("stock_id").filter(- order_line__in=exc.order_lines- ).update(quantity_allocated=0)stocks = (stock_qs_select_for_update()@@ -547,27 +573,22 @@ def decrease_stock(.annotate(Sum("quantity_allocated")))- if update_stocks:- quantity_allocation_for_stocks: dict[int, int] = defaultdict(int)- for allocation in quantity_allocation_list:- quantity_allocation_for_stocks[allocation["stock"]] += allocation[- "quantity_allocated__sum"- ]- _decrease_stocks_quantity(- order_lines_info,- variant_and_warehouse_to_stock,- quantity_allocation_for_stocks,- allow_stock_to_be_exceeded,- )+ quantity_allocation_for_stocks: dict[int, int] = defaultdict(int)+ for allocation in quantity_allocation_list:+ quantity_allocation_for_stocks[allocation["stock"]] += allocation[+ "quantity_allocated__sum"+ ]+ _decrease_stocks_quantity(+ order_lines_info,+ variant_and_warehouse_to_stock,+ quantity_allocation_for_stocks,+ allow_stock_to_be_exceeded,+ )- stock_ids = (s.id for s in stocks)- for stock in Stock.objects.filter(- id__in=stock_ids- ).annotate_available_quantity():- if stock.available_quantity <= 0:- transaction.on_commit(- lambda: manager.product_variant_out_of_stock(stock)- )+ stock_ids = (s.id for s in stocks)+ for stock in Stock.objects.filter(id__in=stock_ids).annotate_available_quantity():+ if stock.available_quantity <= 0:+ transaction.on_commit(lambda: manager.product_variant_out_of_stock(stock))def _decrease_stocks_quantity(@@ -624,59 +645,72 @@ def _decrease_stocks_quantity(Stock.objects.bulk_update(stocks_to_update, ["quantity"])+def _get_variant_for_order_line_info(+ order_line_info: OrderLineInfo,+) -> ProductVariant | None:+ variant = order_line_info.variant+ if not variant and order_line_info.line.variant_id:+ variant = order_line_info.line.variant+ order_line_info.variant = variant+ return variant++def get_order_lines_with_track_inventory(order_lines_info: list["OrderLineInfo"],) -> list["OrderLineInfo"]:"""Return order lines with variants with track inventory set to True."""- return [- line_info- for line_info in order_lines_info- if line_info.variant- and line_info.variant.track_inventory- and not line_info.variant.is_preorder_active()- ]+ lines_to_return = []+ for line_info in order_lines_info:+ variant = _get_variant_for_order_line_info(line_info)-@traced_atomic_transaction()-def deallocate_stock_for_order(order: "Order", manager: PluginsManager):- """Remove all allocations for given order."""- lines = OrderLine.objects.filter(order_id=order.id)- allocations = allocation_with_stock_qs_select_for_update().filter(- Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0- )+ if not variant:+ continue+ if variant.is_preorder_active():+ continue+ if not variant.track_inventory:+ continue+ lines_to_return.append(line_info)+ return lines_to_return- stocks_to_update = []- for alloc in allocations:- stock = alloc.stock- stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated- stocks_to_update.append(stock)- allocations_for_back_in_stock = Allocation.objects.filter(- id__in=[allocation.id for allocation in allocations]+def get_order_lines_to_deallocate(+ order_lines_info: list["OrderLineInfo"],+) -> list["OrderLineInfo"]:+ """Get order lines to deallocate.++ The function returns the lines with active track inventory and the lines where track+ inventory was turned off but for some reason the allocations are present.+ Case like turning on & off the track-inventory.+ """++ order_lines_info_map = {+ line_info.line.id: line_info for line_info in order_lines_info+ }++ lines_to_deallocate = []+ existing_allocations = Allocation.objects.filter(+ order_line_id__in=order_lines_info_map.keys(),)- for allocation in allocations_for_back_in_stock.annotate_stock_available_quantity():- if allocation.stock_available_quantity <= 0:- transaction.on_commit(- lambda: manager.product_variant_back_in_stock(allocation.stock)- )+ for allocation in existing_allocations:+ line_to_deallocate = order_lines_info_map.get(allocation.order_line_id)+ if line_to_deallocate is None:+ continue+ _get_variant_for_order_line_info(line_to_deallocate)+ lines_to_deallocate.append(line_to_deallocate)- allocations.update(quantity_allocated=0)- Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])+ return lines_to_deallocate@traced_atomic_transaction()-def deallocate_stock_for_orders(orders_id, manager: PluginsManager):- """Remove all allocations for given order."""- lines = OrderLine.objects.filter(order_id__in=orders_id)+def deallocate_stock_for_orders(orders_ids: list[UUID], manager: PluginsManager):+ """Remove all allocations for given orders."""+ lines = OrderLine.objects.filter(order_id__in=orders_ids)allocations = allocation_with_stock_qs_select_for_update().filter(Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0)- stocks_to_update = []- for alloc in allocations:- stock = alloc.stock- stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated- stocks_to_update.append(stock)+ stocks_to_update = _reduce_quantity_allocated_for_stocks(allocations)allocations_for_back_in_stock = Allocation.objects.filter(id__in=[allocation.id for allocation in allocations]diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex 8ec7c8cd8d..8c24293bed 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -14,7 +14,8 @@ from ..management import (allocate_preorders,allocate_stocks,deallocate_stock,- deallocate_stock_for_order,+ deallocate_stock_for_orders,+ decrease_allocations,decrease_stock,increase_allocations,increase_stock,@@ -656,6 +657,77 @@ def test_increase_allocations(quantity, allocation):)+ ("first_quantity", "second_quantity"),+ [(9, 20), (2, 19)],+)+def test_increase_allocations_with_multiple_allocations_for_the_same_stock(+ first_quantity, second_quantity, allocations+):+ # given+ first_allocation = allocations[0]+ second_allocation = allocations[1]++ # make sure that we have only two allocations for the same stock+ Allocation.objects.exclude(+ pk__in=[first_allocation.pk, second_allocation.pk]+ ).delete()++ first_order_line = first_allocation.order_line+ first_order_line_info = OrderLineInfo(+ line=first_order_line,+ quantity=first_quantity,+ variant=first_order_line.variant,+ warehouse_pk=first_allocation.stock.warehouse.pk,+ )++ second_order_line = second_allocation.order_line+ second_order_line_info = OrderLineInfo(+ line=second_order_line,+ quantity=second_quantity,+ variant=second_order_line.variant,+ warehouse_pk=second_allocation.stock.warehouse.pk,+ )++ assert first_order_line.variant == second_order_line.variant+ assert first_allocation.stock_id == second_allocation.stock_id++ stock = first_allocation.stock+ stock.quantity = 100+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])++ initially_allocated_in_single_allocation = stock.quantity_allocated / 2+ first_allocation.quantity_allocated = initially_allocated_in_single_allocation+ first_allocation.save(update_fields=["quantity_allocated"])+ second_allocation.quantity_allocated = initially_allocated_in_single_allocation+ second_allocation.save(update_fields=["quantity_allocated"])++ # when+ increase_allocations(+ [first_order_line_info, second_order_line_info],+ first_order_line.order.channel,+ manager=get_plugins_manager(allow_replica=False),+ )++ stock.refresh_from_db()+ assert stock.quantity == 100++ # Check that both allocations are properly accounted for+ first_allocated = first_order_line.allocations.all().aggregate(+ Sum("quantity_allocated")+ )["quantity_allocated__sum"]+ second_allocated = second_order_line.allocations.all().aggregate(+ Sum("quantity_allocated")+ )["quantity_allocated__sum"]++ assert (+ first_allocated + second_allocated+ == stock.quantity_allocated+ == 80 + first_quantity + second_quantity+ )++def test_increase_allocation_insufficient_stock(allocation):order_line = allocation.order_lineorder_line_info = OrderLineInfo(@@ -737,7 +809,7 @@ def test_decrease_stock(allocation):@pytest.mark.parametrize(("quantity", "expected_allocated"), [(50, 30), (200, 0)])-def test_decrease_stock_without_stock_update(quantity, expected_allocated, allocation):+def test_decrease_allocations(quantity, expected_allocated, allocation):stock = allocation.stockstock.quantity = 100stock.quantity_allocated = 80@@ -746,7 +818,7 @@ def test_decrease_stock_without_stock_update(quantity, expected_allocated, allocallocation.save(update_fields=["quantity_allocated"])warehouse_pk = allocation.stock.warehouse.pk- decrease_stock(+ decrease_allocations([OrderLineInfo(line=allocation.order_line,@@ -756,7 +828,6 @@ def test_decrease_stock_without_stock_update(quantity, expected_allocated, alloc)],manager=get_plugins_manager(allow_replica=False),- update_stocks=False,)stock.refresh_from_db()@@ -1014,11 +1085,13 @@ def test_decrease_stock_insufficient_stock(allocation):assert allocation.quantity_allocated == 80-def test_deallocate_stock_for_order(order_line_with_allocation_in_many_stocks):+def test_deallocate_stock_for_orders(order_line_with_allocation_in_many_stocks):order_line = order_line_with_allocation_in_many_stocksorder = order_line.order- deallocate_stock_for_order(order, manager=get_plugins_manager(allow_replica=False))+ deallocate_stock_for_orders(+ [order.id], manager=get_plugins_manager(allow_replica=False)+ )allocations = order_line.allocations.all()assert (@@ -1033,6 +1106,51 @@ def test_deallocate_stock_for_order(order_line_with_allocation_in_many_stocks):)+def test_deallocate_stock_for_orders_with_multiple_allocations_from_the_same_stock(+ allocations,+):+ # given+ first_allocation = allocations[0]+ second_allocation = allocations[1]++ # make sure that we have only two allocations for the same stock+ Allocation.objects.exclude(+ pk__in=[first_allocation.pk, second_allocation.pk]+ ).delete()++ stock = first_allocation.stock+ stock.quantity = 100+ stock.quantity_allocated = (+ first_allocation.quantity_allocated + second_allocation.quantity_allocated+ )++ stock.save(update_fields=["quantity", "quantity_allocated"])++ first_order_line = first_allocation.order_line+ second_order_line = second_allocation.order_line+ order = first_order_line.order++ second_order_line.order = order+ second_order_line.save(update_fields=["order"])++ assert first_order_line.variant == second_order_line.variant+ assert first_allocation.stock_id == second_allocation.stock_id++ # when+ deallocate_stock_for_orders(+ [order.id], manager=get_plugins_manager(allow_replica=False)+ )++ # then+ first_allocation.refresh_from_db()+ second_allocation.refresh_from_db()+ stock.refresh_from_db()++ assert stock.quantity_allocated == 0+ assert first_allocation.quantity_allocated == 0+ assert second_allocation.quantity_allocated == 0++@mock.patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")def test_increase_stock_with_back_in_stock_webhook_not_triggered(product_variant_back_in_stock_webhook,