Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Product variant channel listing webhooks (stocks) (#7590)
mstrumeck6921f6552031
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ad628ac282..ff31f4e822 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -141,6 +141,7 @@ All notable, unreleased changes to this project will be documented in this file.- Optimize available quantity loader. - #7802 by @fowczarek- Configure a periodic task for removing empty allocations - #7885 by @fowczarek+- Add webhooks for stock changes: `PRODUCT_VARIANT_OUT_OF_STOCK` and `PRODUCT_VARIANT_BACK_IN_STOCK` - #7590 by @mstrumeck### Breaking- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysockidiff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 40a3eadf1e..1bdf09c247 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -399,7 +399,7 @@ def _create_order(OrderLine.objects.bulk_create(order_lines)country_code = checkout_info.get_country()- allocate_stocks(order_lines_info, country_code, checkout_info.channel.slug)+ allocate_stocks(order_lines_info, country_code, checkout_info.channel.slug, manager)# Add gift cards to the orderfor gift_card in checkout.gift_cards.select_for_update():diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex ce73f66ec6..979d277bb7 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -1,3 +1,5 @@+from unittest.mock import patch+import pytestfrom graphene import Node@@ -5,6 +7,7 @@ from .....checkout import calculationsfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkoutfrom .....plugins.manager import get_plugins_manager+from .....warehouse.models import Stockfrom ....tests.utils import get_graphql_contentFRAGMENT_PRICE = """@@ -696,6 +699,28 @@ def test_complete_checkout(api_client, checkout_with_charged_payment, count_querassert not response["data"]["checkoutComplete"]["errors"][email protected]_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_complete_checkout_with_out_of_stock_webhook(+ product_variant_out_of_stock_webhook_mock,+ api_client,+ checkout_with_charged_payment,+ count_queries,+):+ query = COMPLETE_CHECKOUT_MUTATION+ Stock.objects.update(quantity=10)+ variables = {+ "token": checkout_with_charged_payment.token,+ }++ response = get_graphql_content(api_client.post_graphql(query, variables))+ assert not response["data"]["checkoutComplete"]["errors"]+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(+ Stock.objects.last()+ )++@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_complete_checkout_with_single_line(diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 0a2e4e227d..178935ddeb 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -387,6 +387,7 @@ class DraftOrderComplete(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, id):+ manager = info.context.pluginsorder = cls.get_node_or_error(info, id, only_type=Order)country = get_order_country(order)validate_draft_order(order, country)@@ -408,7 +409,7 @@ class DraftOrderComplete(BaseMutation):line=line, quantity=line.quantity, variant=line.variant)try:- allocate_stocks([line_data], country, order.channel.slug)+ allocate_stocks([line_data], country, order.channel.slug, manager)except InsufficientStock as exc:errors = prepare_insufficient_stock_order_validation_errors(exc)raise ValidationError({"lines": errors})diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 2f4fde3ae3..36b3035cf3 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -831,6 +831,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):@classmethoddef perform_mutation(cls, _root, info, id):+ manager = info.context.pluginsline = cls.get_node_or_error(info,id,@@ -851,7 +852,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):variant=line.variant,warehouse_pk=warehouse_pk,)- delete_order_line(line_info)+ delete_order_line(line_info, manager)line.id = db_idif not order.is_shipping_required():@@ -915,6 +916,7 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):@classmethoddef save(cls, info, instance, cleaned_input):+ manager = info.context.pluginswarehouse_pk = (instance.allocations.first().stock.warehouse.pkif instance.order.is_unconfirmed()@@ -934,6 +936,7 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):instance.old_quantity,instance.quantity,instance.order.channel.slug,+ manager,)except InsufficientStock:raise ValidationError(diff --git a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.pyindex ad9d08878b..998ac4edd8 100644--- a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py+++ b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py@@ -4,6 +4,7 @@ import grapheneimport pytestfrom .....payment import ChargeStatus+from .....warehouse.models import Stockfrom ....tests.utils import get_graphql_content@@ -69,9 +70,11 @@ def test_fulfillment_refund_products_order_lines(@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")@patch("saleor.order.actions.gateway.refund")def test_fulfillment_return_products_order_lines(mocked_refund,+ back_in_stock_webhook_mock,staff_api_client,permission_manage_orders,order_with_lines,@@ -167,3 +170,5 @@ def test_fulfillment_return_products_order_lines(data = content["data"]["orderFulfillmentReturnProducts"]assert data["returnFulfillment"]assert data["replaceFulfillment"]++ back_in_stock_webhook_mock.assert_called_once_with(Stock.objects.last())diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex da748462c1..9bfeeb959d 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -32,6 +32,45 @@ ORDER_FULFILL_QUERY = """"""+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_order_fulfill_with_out_of_stock_webhook(+ product_variant_out_of_stock_webhooks,+ staff_api_client,+ order_with_lines,+ permission_manage_orders,+ warehouse,+):+ order = order_with_lines++ query = ORDER_FULFILL_QUERY+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line, order_line2 = order.lines.all()+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],+ },+ ],+ },+ }+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )++ product_variant_out_of_stock_webhooks.assert_called_once_with(Stock.objects.last())++@pytest.mark.parametrize("fulfillment_auto_approve", [True, False])@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")def test_order_fulfill(diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.pyindex 6fd56db3a3..d8de363422 100644--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py@@ -8,7 +8,7 @@ from ....core.prices import quantize_pricefrom ....order.error_codes import OrderErrorCodefrom ....order.models import FulfillmentStatusfrom ....payment import ChargeStatus, PaymentError-from ....warehouse.models import Stock+from ....warehouse.models import Allocation, Stockfrom ...tests.utils import get_graphql_contentORDER_FULFILL_REFUND_MUTATION = """@@ -42,6 +42,41 @@ mutation OrderFulfillmentRefundProducts("""+@patch("saleor.order.actions.gateway.refund")+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_fulfillment_refund_products_with_back_in_stock_webhook(+ back_in_stock_webhook_trigger,+ mock_refunded,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ payment_dummy,+):++ Allocation.objects.update(quantity_allocated=5)+ payment_dummy.total = order_with_lines.total_gross_amount+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ line_to_refund = order_with_lines.lines.first()+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)+ variables = {+ "order": order_id,+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 1}]},+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderFulfillmentRefundProducts"]+ refund_fulfillment = data["fulfillment"]+ errors = data["errors"]+ assert not errors+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()+ back_in_stock_webhook_trigger.assert_called_once_with(Stock.objects.first())++def test_fulfillment_refund_products_order_without_payment(staff_api_client, permission_manage_orders, fulfilled_order):diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 333e0df60f..8a09b319ac 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -9,6 +9,7 @@ import grapheneimport pytestfrom django.contrib.auth.models import AnonymousUserfrom django.core.exceptions import ValidationError+from django.db.models import Sumfrom freezegun import freeze_timefrom measurement.measures import Weightfrom prices import Money, TaxedMoney@@ -2908,7 +2909,9 @@ DRAFT_ORDER_COMPLETE_MUTATION = """"""+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_draft_order_complete(+ product_variant_out_of_stock_webhook_mock,staff_api_client,permission_manage_orders,staff_user,@@ -2950,6 +2953,38 @@ def test_draft_order_complete(assert matching_events.count() == 2assert matching_events[0].type != matching_events[1].typeassert not OrderEvent.objects.exclude(**event_params).exists()+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(+ Stock.objects.last()+ )+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_draft_order_complete_with_out_of_stock_webhook(+ product_variant_out_of_stock_webhook_mock,+ staff_api_client,+ permission_manage_orders,+ draft_order,+):+ order = draft_order+ first_line = order.lines.first()+ first_line.quantity = 5+ first_line.save()++ # Ensure no allocation were created+ assert not Allocation.objects.filter(order_line__order=order).exists()+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}+ staff_api_client.post_graphql(+ DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]+ )++ total_stock = Stock.objects.aggregate(Sum("quantity"))["quantity__sum"]+ total_allocation = Allocation.objects.filter(order_line__order=order).aggregate(+ Sum("quantity_allocated")+ )["quantity_allocated__sum"]+ assert total_stock == total_allocation+ assert product_variant_out_of_stock_webhook_mock.call_count == 2+ product_variant_out_of_stock_webhook_mock.assert_called_with(Stock.objects.last())def test_draft_order_from_reissue_complete(@@ -3330,8 +3365,68 @@ ORDER_LINES_CREATE_MUTATION = """"""+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_order_lines_create_with_out_of_stock_webhook(+ product_variant_out_of_stock_webhook_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ query = ORDER_LINES_CREATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ line = order.lines.first()+ variant = line.variant+ quantity = 2+ order_id = graphene.Node.to_global_id("Order", order.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ staff_api_client.post_graphql(query, variables)++ quantity_allocated = Allocation.objects.aggregate(Sum("quantity_allocated"))[+ "quantity_allocated__sum"+ ]+ stock_quantity = Allocation.objects.aggregate(Sum("stock__quantity"))[+ "stock__quantity__sum"+ ]+ assert quantity_allocated == stock_quantity+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(+ Stock.objects.first()+ )+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_order_lines_create_for_variant_with_many_stocks_with_out_of_stock_webhook(+ product_variant_out_of_stock_webhook_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+ variant_with_many_stocks,+):+ query = ORDER_LINES_CREATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ variant = variant_with_many_stocks+ quantity = 4+ order_id = graphene.Node.to_global_id("Order", order.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ staff_api_client.post_graphql(query, variables)+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(+ Stock.objects.all()[3]+ )+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))def test_order_lines_create(+ product_variant_out_of_stock_webhook_mock,status,order_with_lines,permission_manage_orders,@@ -3371,6 +3466,7 @@ def test_order_lines_create(assert data["errors"]assert data["errors"][0]["field"] == "quantity"assert data["errors"][0]["variants"] == [variant_id]+ product_variant_out_of_stock_webhook_mock.assert_not_called()def test_order_lines_create_with_unavailable_variant(@@ -3532,6 +3628,140 @@ ORDER_LINE_UPDATE_MUTATION = """"""+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_order_line_update_with_out_of_stock_webhook_for_two_lines_success_scenario(+ out_of_stock_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ Stock.objects.update(quantity=5)+ query = ORDER_LINE_UPDATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ first_line, second_line = order.lines.all()+ new_quantity = 5++ first_line_id = graphene.Node.to_global_id("OrderLine", first_line.id)+ second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id)++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ variables = {"lineId": first_line_id, "quantity": new_quantity}+ staff_api_client.post_graphql(query, variables)++ variables = {"lineId": second_line_id, "quantity": new_quantity}+ staff_api_client.post_graphql(query, variables)++ assert out_of_stock_mock.call_count == 2+ out_of_stock_mock.assert_called_with(Stock.objects.last())+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_order_line_update_with_out_of_stock_webhook_success_scenario(+ out_of_stock_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ query = ORDER_LINE_UPDATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ line = order.lines.first()+ new_quantity = 5+ line_id = graphene.Node.to_global_id("OrderLine", line.id)++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ variables = {"lineId": line_id, "quantity": new_quantity}+ staff_api_client.post_graphql(query, variables)++ out_of_stock_mock.assert_called_once_with(Stock.objects.first())+++@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_order_line_update_with_back_in_stock_webhook_fail_scenario(+ product_variant_back_in_stock_webhook_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ query = ORDER_LINE_UPDATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ line = order.lines.first()+ new_quantity = 1+ line_id = graphene.Node.to_global_id("OrderLine", line.id)++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ variables = {"lineId": line_id, "quantity": new_quantity}+ staff_api_client.post_graphql(query, variables)++ product_variant_back_in_stock_webhook_mock.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_order_line_update_with_back_in_stock_webhook_called_once_success_scenario(+ back_in_stock_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ first_allocated = Allocation.objects.first()+ first_allocated.quantity_allocated = 5+ first_allocated.save()++ query = ORDER_LINE_UPDATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ line = order.lines.first()+ new_quantity = 1+ line_id = graphene.Node.to_global_id("OrderLine", line.id)+ variables = {"lineId": line_id, "quantity": new_quantity}++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ staff_api_client.post_graphql(query, variables)+ back_in_stock_mock.assert_called_once_with(first_allocated.stock)+++@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_order_line_update_with_back_in_stock_webhook_called_twice_success_scenario(+ product_variant_back_in_stock_webhook_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ first_allocation = Allocation.objects.first()+ first_allocation.quantity_allocated = 5+ first_allocation.save()++ query = ORDER_LINE_UPDATE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ first_line, second_line = order.lines.all()+ new_quantity = 1+ first_line_id = graphene.Node.to_global_id("OrderLine", first_line.id)+ second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id)++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ variables = {"lineId": first_line_id, "quantity": new_quantity}+ staff_api_client.post_graphql(query, variables)++ variables = {"lineId": second_line_id, "quantity": new_quantity}+ staff_api_client.post_graphql(query, variables)++ assert product_variant_back_in_stock_webhook_mock.call_count == 2+ product_variant_back_in_stock_webhook_mock.assert_called_with(Stock.objects.last())++@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))def test_order_line_update(status,@@ -3713,6 +3943,57 @@ ORDER_LINE_DELETE_MUTATION = """"""+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_order_line_remove_with_back_in_stock_webhook(+ back_in_stock_webhook_mock,+ order_with_lines,+ permission_manage_orders,+ staff_api_client,+):+ Stock.objects.update(quantity=3)+ first_stock = Stock.objects.first()+ assert (+ first_stock.quantity+ - (+ first_stock.allocations.aggregate(Sum("quantity_allocated"))[+ "quantity_allocated__sum"+ ]+ or 0+ )+ ) == 0++ query = ORDER_LINE_DELETE_MUTATION+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])++ line = order.lines.first()++ line_id = graphene.Node.to_global_id("OrderLine", line.id)+ variables = {"id": line_id}++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderLineDelete"]+ assert OrderEvent.objects.count() == 1+ assert OrderEvent.objects.last().type == order_events.OrderEvents.REMOVED_PRODUCTS+ assert data["orderLine"]["id"] == line_id+ assert line not in order.lines.all()+ first_stock.refresh_from_db()+ assert (+ first_stock.quantity+ - (+ first_stock.allocations.aggregate(Sum("quantity_allocated"))[+ "quantity_allocated__sum"+ ]+ or 0+ )+ ) == 3+ back_in_stock_webhook_mock.assert_called_once_with(Stock.objects.first())++@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))def test_order_line_remove(status, order_with_lines, permission_manage_orders, staff_api_client@@ -5367,6 +5648,27 @@ def test_order_bulk_cancel(mock_cancel_order.call_count == expected_count+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_order_bulk_cancel_with_back_in_stock_webhook(+ product_variant_back_in_stock_webhook_mock,+ staff_api_client,+ fulfilled_order_with_all_cancelled_fulfillments,+ permission_manage_orders,+):+ variables = {+ "ids": [+ graphene.Node.to_global_id(+ "Order", fulfilled_order_with_all_cancelled_fulfillments.id+ )+ ]+ }+ staff_api_client.post_graphql(+ MUTATION_ORDER_BULK_CANCEL, variables, permissions=[permission_manage_orders]+ )++ product_variant_back_in_stock_webhook_mock.assert_called_once()++@patch("saleor.graphql.order.bulk_mutations.orders.cancel_order")def test_order_bulk_cancel_as_app(mock_cancel_order,diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex a5ec0ee84c..fff3d95846 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -636,7 +636,9 @@ class ProductVariantStocksCreate(BaseMutation):error_type_field = "bulk_stock_errors"@classmethod+ @traced_atomic_transaction()def perform_mutation(cls, root, info, **data):+ manager = info.context.pluginserrors = defaultdict(list)stocks = data["stocks"]variant = cls.get_node_or_error(@@ -646,9 +648,15 @@ class ProductVariantStocksCreate(BaseMutation):warehouses = cls.clean_stocks_input(variant, stocks, errors)if errors:raise ValidationError(errors)- create_stocks(variant, stocks, warehouses)+ new_stocks = create_stocks(variant, stocks, warehouses)++ for stock in new_stocks:+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(stock)+ )variant = ChannelContext(node=variant, channel_slug=None)+return cls(product_variant=variant)@classmethod@@ -716,21 +724,36 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):warehouses = cls.get_nodes_or_error(warehouse_ids, "warehouse", only_type=Warehouse)- cls.update_or_create_variant_stocks(variant, stocks, warehouses)++ manager = info.context.plugins+ cls.update_or_create_variant_stocks(variant, stocks, warehouses, manager)variant = ChannelContext(node=variant, channel_slug=None)return cls(product_variant=variant)@classmethod@traced_atomic_transaction()- def update_or_create_variant_stocks(cls, variant, stocks_data, warehouses):+ def update_or_create_variant_stocks(cls, variant, stocks_data, warehouses, manager):+stocks = []for stock_data, warehouse in zip(stocks_data, warehouses):- stock, _ = warehouse_models.Stock.objects.get_or_create(+ stock, is_created = warehouse_models.Stock.objects.get_or_create(product_variant=variant, warehouse=warehouse)++ if is_created or (stock.quantity == 0 and stock_data["quantity"] > 0):+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(stock)+ )++ if stock_data["quantity"] <= 0:+ transaction.on_commit(+ lambda: manager.product_variant_out_of_stock(stock)+ )+stock.quantity = stock_data["quantity"]stocks.append(stock)+warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])@@ -755,18 +778,26 @@ class ProductVariantStocksDelete(BaseMutation):error_type_field = "stock_errors"@classmethod+ @traced_atomic_transaction()def perform_mutation(cls, root, info, **data):+ manager = info.context.pluginsvariant = cls.get_node_or_error(info, data["variant_id"], only_type=ProductVariant)warehouses_pks = cls.get_global_ids_or_error(data["warehouse_ids"], Warehouse, field="warehouse_ids")- warehouse_models.Stock.objects.filter(+ stocks_to_delete = warehouse_models.Stock.objects.filter(product_variant=variant, warehouse__pk__in=warehouses_pks- ).delete()+ )variant = ChannelContext(node=variant, channel_slug=None)++ for stock in stocks_to_delete:+ transaction.on_commit(lambda: manager.product_variant_out_of_stock(stock))++ stocks_to_delete.delete()+return cls(product_variant=variant)diff --git a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py b/saleor/graphql/product/tests/benchmark/test_variant_stocks.pyindex 7fc2f1c037..606f19cb29 100644--- a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py+++ b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py@@ -1,3 +1,5 @@+from unittest.mock import patch+import grapheneimport pytest@@ -7,8 +9,14 @@ from ....tests.utils import get_graphql_content@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")def test_product_variants_stocks_create(- staff_api_client, variant, warehouse, permission_manage_products, count_queries+ product_variant_back_in_stock_webhook_mock,+ staff_api_client,+ variant,+ warehouse,+ permission_manage_products,+ count_queries,):query = """mutation ProductVariantStocksCreate($variantId: ID!, $stocks: [StockInput!]!){@@ -64,6 +72,72 @@ def test_product_variants_stocks_create(== variant.stocks.count()== stocks_count + len(stocks))+ assert product_variant_back_in_stock_webhook_mock.call_count == 2+ product_variant_back_in_stock_webhook_mock.assert_called_with(Stock.objects.last())++[email protected]_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_product_variants_stocks_create_with_single_webhook_called(+ product_variant_back_in_stock_webhook_mock,+ staff_api_client,+ variant,+ warehouse,+ permission_manage_products,+ count_queries,+):+ query = """+ mutation ProductVariantStocksCreate($variantId: ID!, $stocks: [StockInput!]!){+ productVariantStocksCreate(variantId: $variantId, stocks: $stocks){+ productVariant{+ stocks {+ quantity+ quantityAllocated+ id+ warehouse{+ slug+ }+ }+ }+ errors{+ code+ field+ message+ index+ }+ }+ }+ """+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)+ second_warehouse.slug = "second warehouse"+ second_warehouse.pk = None+ second_warehouse.save()++ stocks_count = variant.stocks.count()++ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.id),+ "quantity": 20,+ },+ ]+ variables = {"variantId": variant_id, "stocks": stocks}+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantStocksCreate"]+ assert not data["errors"]+ assert (+ len(data["productVariant"]["stocks"])+ == variant.stocks.count()+ == stocks_count + len(stocks)+ )+ product_variant_back_in_stock_webhook_mock.assert_called_with(Stock.objects.last())@pytest.mark.django_db@@ -129,8 +203,14 @@ def test_product_variants_stocks_update(@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_product_variants_stocks_delete(- staff_api_client, variant, warehouse, permission_manage_products, count_queries+ product_variant_out_of_stock_webhook_mock,+ staff_api_client,+ variant,+ warehouse,+ permission_manage_products,+ count_queries,):query = """mutation ProductVariantStocksDelete($variantId: ID!, $warehouseIds: [ID!]!){@@ -154,7 +234,6 @@ def test_product_variants_stocks_delete(}}"""-variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)second_warehouse = Warehouse.objects.get(pk=warehouse.pk)second_warehouse.slug = "second warehouse"@@ -167,6 +246,7 @@ def test_product_variants_stocks_delete(Stock(product_variant=variant, warehouse=second_warehouse, quantity=140),])+ stock_to_delete = Stock.objects.last()stocks_count = variant.stocks.count()warehouse_ids = [graphene.Node.to_global_id("Warehouse", second_warehouse.id)]@@ -186,6 +266,73 @@ def test_product_variants_stocks_delete(== variant.stocks.count()== stocks_count - 1)+ assert stock_to_delete not in Stock.objects.all()+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(stock_to_delete)++[email protected]_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_product_variants_stocks_delete_with_out_of_stock_webhook_many_calls(+ product_variant_out_of_stock_webhook_mock,+ staff_api_client,+ variant,+ warehouse,+ permission_manage_products,+ count_queries,+):+ query = """+ mutation ProductVariantStocksDelete($variantId: ID!, $warehouseIds: [ID!]!){+ productVariantStocksDelete(+ variantId: $variantId, warehouseIds: $warehouseIds+ ){+ productVariant{+ stocks{+ id+ quantity+ warehouse{+ slug+ }+ }+ }+ stockErrors{+ field+ code+ message+ }+ }+ }+ """++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)+ second_warehouse.slug = "second warehouse"+ second_warehouse.pk = None+ second_warehouse.save()+ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=10),+ Stock(product_variant=variant, warehouse=second_warehouse, quantity=140),+ ]+ )++ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", warehouse_id)+ for warehouse_id in Warehouse.objects.values_list("id", flat=True)+ ]++ variables = {"variantId": variant_id, "warehouseIds": warehouse_ids}+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantStocksDelete"]++ assert not data["stockErrors"]++ assert product_variant_out_of_stock_webhook_mock.call_count == 2@pytest.mark.django_dbdiff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 0f3750e447..6e08928635 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -9,6 +9,7 @@ import grapheneimport pytestimport pytzfrom django.core.exceptions import ValidationError+from django.db.models import Sumfrom django.utils.dateparse import parse_datetimefrom django.utils.html import strip_tagsfrom django.utils.text import slugify@@ -24,7 +25,7 @@ from ....core.taxes import TaxTypefrom ....core.units import WeightUnitsfrom ....order import OrderEvents, OrderStatusfrom ....order.models import OrderEvent, OrderLine-from ....plugins.manager import PluginsManager+from ....plugins.manager import PluginsManager, get_plugins_managerfrom ....product import ProductMediaTypesfrom ....product.error_codes import ProductErrorCodefrom ....product.models import (@@ -41,7 +42,7 @@ from ....product.models import (from ....product.tasks import update_variants_namesfrom ....product.tests.utils import create_image, create_pdf_file_with_image_extfrom ....product.utils.costs import get_product_costs_data-from ....tests.utils import dummy_editorjs+from ....tests.utils import dummy_editorjs, flush_post_commit_hooksfrom ....warehouse.models import Allocation, Stock, Warehousefrom ....webhook.event_types import WebhookEventTypefrom ....webhook.payloads import generate_product_deleted_payload@@ -9995,7 +9996,7 @@ def test_update_or_create_variant_stocks(variant, warehouses):]ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses+ variant, stocks_data, warehouses, get_plugins_manager())variant.refresh_from_db()@@ -10015,7 +10016,9 @@ def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):quantity=5,)- ProductVariantStocksUpdate.update_or_create_variant_stocks(variant, [], warehouses)+ ProductVariantStocksUpdate.update_or_create_variant_stocks(+ variant, [], warehouses, get_plugins_manager()+ )variant.refresh_from_db()assert variant.stocks.count() == 1@@ -10024,6 +10027,125 @@ def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):assert stock.quantity == 5+@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(+ product_variant_stock_out_of_stock_webhook,+ product_variant_back_in_stock_webhook,+ settings,+ variant,+ warehouses,+ info,+):++ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse)+ for warehouse in warehouses+ ]+ )++ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ info.context.plugins = get_plugins_manager()+ stocks_data = [+ {"quantity": 10, "warehouse": "123"},+ ]+ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0++ ProductVariantStocksUpdate.update_or_create_variant_stocks(+ variant, stocks_data, warehouses, info.context.plugins+ )++ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10++ flush_post_commit_hooks()+ product_variant_back_in_stock_webhook.assert_called_once_with(+ Stock.objects.all()[1]+ )+ product_variant_stock_out_of_stock_webhook.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(+ product_variant_stock_out_of_stock_webhook,+ product_variant_back_in_stock_webhook,+ settings,+ variant,+ warehouses,+ info,+):++ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse)+ for warehouse in warehouses+ ]+ )++ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ info.context.plugins = get_plugins_manager()+ stocks_data = [+ {"quantity": 0, "warehouse": "123"},+ ]+ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0++ ProductVariantStocksUpdate.update_or_create_variant_stocks(+ variant, stocks_data, warehouses, info.context.plugins+ )++ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0++ flush_post_commit_hooks()+ product_variant_back_in_stock_webhook.assert_not_called()+ product_variant_stock_out_of_stock_webhook.assert_called_once_with(+ Stock.objects.all()[1]+ )+++@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(+ product_variant_stock_out_of_stock_webhook,+ product_variant_back_in_stock_webhook,+ settings,+ variant,+ warehouses,+ info,+):++ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=5)+ for warehouse in warehouses+ ]+ )++ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ info.context.plugins = get_plugins_manager()++ stocks_data = [+ {"quantity": 0, "warehouse": "123"},+ {"quantity": 2, "warehouse": "321"},+ ]++ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10++ ProductVariantStocksUpdate.update_or_create_variant_stocks(+ variant, stocks_data, warehouses, info.context.plugins+ )++ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 2++ flush_post_commit_hooks()++ product_variant_stock_out_of_stock_webhook.assert_called_once_with(+ Stock.objects.last()+ )+ product_variant_back_in_stock_webhook.assert_not_called()++# Because we use Scalars for Weight this test query tests only a scenario when weight# value is passed by a variableMUTATION_CREATE_PRODUCT_WITH_WEIGHT_GQL_VARIABLE = """diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex d1a979b4c5..75a145706b 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -67,7 +67,7 @@ def create_stocks(variant: "ProductVariant", stocks_data: List[Dict[str, str]], warehouses: "QuerySet"):try:- Stock.objects.bulk_create(+ new_stocks = Stock.objects.bulk_create([Stock(product_variant=variant,@@ -80,6 +80,7 @@ def create_stocks(except IntegrityError:msg = "Stock for one of warehouses already exists for this product variant."raise ValidationError(msg)+ return new_stocksDraftOrderLinesData = namedtuple(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 2309de6243..935b8dc6fe 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -7021,6 +7021,8 @@ enum WebhookEventTypeEnum {PRODUCT_VARIANT_CREATEDPRODUCT_VARIANT_UPDATEDPRODUCT_VARIANT_DELETED+ PRODUCT_VARIANT_OUT_OF_STOCK+ PRODUCT_VARIANT_BACK_IN_STOCKCHECKOUT_CREATEDCHECKOUT_UPDATEDFULFILLMENT_CREATED@@ -7058,6 +7060,8 @@ enum WebhookSampleEventTypeEnum {PRODUCT_VARIANT_CREATEDPRODUCT_VARIANT_UPDATEDPRODUCT_VARIANT_DELETED+ PRODUCT_VARIANT_OUT_OF_STOCK+ PRODUCT_VARIANT_BACK_IN_STOCKCHECKOUT_CREATEDCHECKOUT_UPDATEDFULFILLMENT_CREATEDdiff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.pyindex 400fdb5e98..41aae6bfda 100644--- a/saleor/graphql/warehouse/mutations.py+++ b/saleor/graphql/warehouse/mutations.py@@ -1,7 +1,9 @@import graphenefrom django.core.exceptions import ValidationError+from django.db import transactionfrom ...core.permissions import ProductPermissions+from ...core.tracing import traced_atomic_transactionfrom ...warehouse import modelsfrom ...warehouse.error_codes import WarehouseErrorCodefrom ...warehouse.validation import validate_warehouse_count # type: ignore@@ -165,3 +167,16 @@ class WarehouseDelete(ModelDeleteMutation):class Arguments:id = graphene.ID(description="ID of a warehouse to delete.", required=True)++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, **data):+ manager = info.context.plugins+ node_id = data.get("id")+ model_type = cls.get_type_for_model()+ instance = cls.get_node_or_error(info, node_id, only_type=model_type)+ stocks = (stock for stock in instance.stock_set.only("product_variant"))+ result = super(WarehouseDelete, cls).perform_mutation(_root, info, **data)+ for stock in stocks:+ transaction.on_commit(lambda: manager.product_variant_out_of_stock(stock))+ return resultdiff --git a/saleor/graphql/warehouse/tests/test_warehouse.py b/saleor/graphql/warehouse/tests/test_warehouse.pyindex 010b94425e..66af168cf1 100644--- a/saleor/graphql/warehouse/tests/test_warehouse.py+++ b/saleor/graphql/warehouse/tests/test_warehouse.py@@ -1,9 +1,11 @@+from unittest.mock import patch+import grapheneimport pytestfrom ....account.models import Addressfrom ....warehouse.error_codes import WarehouseErrorCode-from ....warehouse.models import Warehouse+from ....warehouse.models import Stock, Warehousefrom ...tests.utils import (assert_no_permission,get_graphql_content,@@ -841,6 +843,56 @@ def test_delete_warehouse_mutation(assert not Warehouse.objects.exists()+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_delete_warehouse_mutation_with_webhooks(+ product_variant_out_of_stock_webhook,+ staff_api_client,+ warehouse,+ permission_manage_products,+ variant_with_many_stocks,+):+ old_first_stock = Stock.objects.first()+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ assert Warehouse.objects.count() == 3+ assert Stock.objects.count() == 3+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ errors = content["data"]["deleteWarehouse"]["errors"]+ assert len(errors) == 0+ assert Warehouse.objects.count() == 2+ assert Stock.objects.count() == 2+ product_variant_out_of_stock_webhook.assert_called_once_with(old_first_stock)+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_delete_warehouse_mutation_with_webhooks_for_many_product_variants(+ product_variant_out_of_stock_webhook,+ staff_api_client,+ warehouse,+ permission_manage_products,+ product_with_two_variants,+):++ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ assert Warehouse.objects.count() == 1+ assert Stock.objects.count() == 2+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ errors = content["data"]["deleteWarehouse"]["errors"]+ assert len(errors) == 0+ assert Warehouse.objects.count() == 0+ assert Stock.objects.count() == 0+ assert product_variant_out_of_stock_webhook.call_count == 2++def test_delete_warehouse_deletes_associated_address(staff_api_client, warehouse, permission_manage_products):diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 71dc5709e3..e679eb6d0d 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -158,8 +158,7 @@ def cancel_order("""events.order_canceled_event(order=order, user=user, app=app)-- deallocate_stock_for_order(order)+ deallocate_stock_for_order(order, manager)order.status = OrderStatus.CANCELEDorder.save(update_fields=["status"])@@ -365,7 +364,7 @@ def approve_fulfillment()for f_line in fulfillment.lines.all()]- fulfill_order_lines(lines_to_fulfill)+ fulfill_order_lines(lines_to_fulfill, manager)order.refresh_from_db()update_order_status(order)@@ -433,11 +432,13 @@ def clean_mark_order_as_paid(order: "Order"):@traced_atomic_transaction()-def fulfill_order_lines(order_lines_info: Iterable["OrderLineData"]):+def fulfill_order_lines(+ order_lines_info: Iterable["OrderLineData"], manager: "PluginsManager"+):"""Fulfill order line with given quantity."""lines_to_decrease_stock = get_order_lines_with_track_inventory(order_lines_info)if lines_to_decrease_stock:- decrease_stock(lines_to_decrease_stock)+ decrease_stock(lines_to_decrease_stock, manager)order_lines = []for line_info in order_lines_info:line = line_info.line@@ -486,7 +487,7 @@ def automatically_fulfill_digital_lines(order: "Order", manager: "PluginsManager)FulfillmentLine.objects.bulk_create(fulfillments)- fulfill_order_lines(lines_info)+ fulfill_order_lines(lines_info, manager)send_fulfillment_confirmation_to_customer(order, fulfillment, user=order.user, app=None, manager=manager@@ -499,6 +500,7 @@ def _create_fulfillment_lines(warehouse_pk: str,lines_data: List[Dict],channel_slug: str,+ manager: "PluginsManager",decrease_stock: bool = True,) -> List[FulfillmentLine]:"""Modify stocks and allocations. Return list of unsaved FulfillmentLines.@@ -516,6 +518,7 @@ def _create_fulfillment_lines(...]channel_slug (str): Channel for which fulfillment lines should be created.+ manager (PluginsManager): Plugin manager from given contextdecrease_stock (Bool): Stocks will get decreased if this is True.Return:@@ -578,7 +581,7 @@ def _create_fulfillment_lines(raise InsufficientStock(insufficient_stocks)if lines_info and decrease_stock:- fulfill_order_lines(lines_info)+ fulfill_order_lines(lines_info, manager)return fulfillment_lines@@ -644,6 +647,7 @@ def create_fulfillments(warehouse_pk,fulfillment_lines_for_warehouses[warehouse_pk],order.channel.slug,+ manager,decrease_stock=approved,))@@ -705,6 +709,7 @@ def _get_fulfillment_line(def _move_order_lines_to_target_fulfillment(order_lines_to_move: List[OrderLineData],target_fulfillment: Fulfillment,+ manager: "PluginsManager",) -> List[FulfillmentLine]:"""Move order lines with given quantity to the target fulfillment."""fulfillment_lines_to_create: List[FulfillmentLine] = []@@ -739,7 +744,7 @@ def _move_order_lines_to_target_fulfillment(if lines_to_dellocate:try:- deallocate_stock(lines_to_dellocate)+ deallocate_stock(lines_to_dellocate, manager)except AllocationError as e:lines = [str(line.pk) for line in e.order_lines]logger.warning(@@ -864,6 +869,7 @@ def create_refund_fulfillment(created_fulfillment_lines = _move_order_lines_to_target_fulfillment(order_lines_to_move=order_lines_to_refund,target_fulfillment=refunded_fulfillment,+ manager=manager,)_move_fulfillment_lines_to_target_fulfillment(@@ -980,6 +986,7 @@ def _move_lines_to_return_fulfillment(order: "Order",total_refund_amount: Optional[Decimal],shipping_refund_amount: Optional[Decimal],+ manager: "PluginsManager",) -> Fulfillment:target_fulfillment = Fulfillment.objects.create(status=fulfillment_status,@@ -990,6 +997,7 @@ def _move_lines_to_return_fulfillment(lines_in_target_fulfillment = _move_order_lines_to_target_fulfillment(order_lines_to_move=order_lines,target_fulfillment=target_fulfillment,+ manager=manager,)fulfillment_lines_already_refunded = FulfillmentLine.objects.filter(@@ -1034,6 +1042,7 @@ def _move_lines_to_replace_fulfillment(order_lines_to_replace: List[OrderLineData],fulfillment_lines_to_replace: List[FulfillmentLineData],order: "Order",+ manager: "PluginsManager",) -> Fulfillment:target_fulfillment = Fulfillment.objects.create(status=FulfillmentStatus.REPLACED, order=order@@ -1041,6 +1050,7 @@ def _move_lines_to_replace_fulfillment(lines_in_target_fulfillment = _move_order_lines_to_target_fulfillment(order_lines_to_move=order_lines_to_replace,target_fulfillment=target_fulfillment,+ manager=manager,)_move_fulfillment_lines_to_target_fulfillment(fulfillment_lines_to_move=fulfillment_lines_to_replace,@@ -1059,6 +1069,7 @@ def create_return_fulfillment(fulfillment_lines: List[FulfillmentLineData],total_refund_amount: Optional[Decimal],shipping_refund_amount: Optional[Decimal],+ manager: "PluginsManager",) -> Fulfillment:status = FulfillmentStatus.RETURNEDif total_refund_amount is not None:@@ -1071,6 +1082,7 @@ def create_return_fulfillment(order=order,total_refund_amount=total_refund_amount,shipping_refund_amount=shipping_refund_amount,+ manager=manager,)returned_lines: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()order_lines_with_fulfillment = OrderLine.objects.in_bulk(@@ -1110,6 +1122,7 @@ def process_replace(order: "Order",order_lines: List[OrderLineData],fulfillment_lines: List[FulfillmentLineData],+ manager: "PluginsManager",) -> Tuple[Fulfillment, Optional["Order"]]:"""Create replace fulfillment and new draft order.@@ -1121,6 +1134,7 @@ def process_replace(order_lines_to_replace=order_lines,fulfillment_lines_to_replace=fulfillment_lines,order=order,+ manager=manager,)new_order = create_replace_order(user=user,@@ -1211,6 +1225,7 @@ def create_fulfillments_for_returned_products(order=order,order_lines=replace_order_lines,fulfillment_lines=replace_fulfillment_lines,+ manager=manager,)return_fulfillment = create_return_fulfillment(user=user,@@ -1220,6 +1235,7 @@ def create_fulfillments_for_returned_products(fulfillment_lines=return_fulfillment_lines,total_refund_amount=total_refund_amount,shipping_refund_amount=shipping_refund_amount,+ manager=manager,)Fulfillment.objects.filter(order=order, lines=None, status=FulfillmentStatus.FULFILLEDdiff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfullments_actions.pyindex e9f7831497..c9e08cfec6 100644--- a/saleor/order/tests/test_fulfullments_actions.py+++ b/saleor/order/tests/test_fulfullments_actions.py@@ -541,3 +541,56 @@ def test_create_fulfillments_with_variant_without_inventory_tracking_and_without)mock_email_fulfillment.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_create_fullfilment_with_out_of_stock_webhook(+ product_variant_out_of_stock_webhook, staff_user, order_with_lines, warehouse+):++ order = order_with_lines+ order_line1, order_line2 = order.lines.all()+ fulfillment_lines_for_warehouses = {+ str(warehouse.pk): [+ {"order_line": order_line1, "quantity": 3},+ {"order_line": order_line2, "quantity": 2},+ ]+ }+ manager = get_plugins_manager()+ create_fulfillments(+ user=staff_user,+ app=None,+ order=order,+ fulfillment_lines_for_warehouses=fulfillment_lines_for_warehouses,+ manager=manager,+ )+ flush_post_commit_hooks()++ product_variant_out_of_stock_webhook.assert_called_once()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_create_fullfilment_with_out_of_stock_webhook_not_triggered(+ product_variant_out_of_stock_webhook, staff_user, order_with_lines, warehouse+):++ order = order_with_lines+ order_line1, order_line2 = order.lines.all()+ fulfillment_lines_for_warehouses = {+ str(warehouse.pk): [+ {"order_line": order_line1, "quantity": 1},+ {"order_line": order_line2, "quantity": 1},+ ]+ }+ manager = get_plugins_manager()+ create_fulfillments(+ user=staff_user,+ app=None,+ order=order,+ fulfillment_lines_for_warehouses=fulfillment_lines_for_warehouses,+ manager=manager,+ approved=False,+ )+ flush_post_commit_hooks()++ product_variant_out_of_stock_webhook.assert_not_called()diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex c6b0c5dddf..55c5ca7ee9 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -239,7 +239,7 @@ def test_restock_order_lines(order_with_lines, track_inventory):stock_1_quantity_before = stock_1.quantitystock_2_quantity_before = stock_2.quantity- restock_order_lines(order)+ restock_order_lines(order, get_plugins_manager())stock_1.refresh_from_db()stock_2.refresh_from_db()@@ -275,7 +275,7 @@ def test_restock_fulfilled_order_lines(fulfilled_order):stock_1_quantity_before = stock_1.quantitystock_2_quantity_before = stock_2.quantity- restock_order_lines(fulfilled_order)+ restock_order_lines(fulfilled_order, get_plugins_manager())stock_1.refresh_from_db()stock_2.refresh_from_db()@@ -670,7 +670,13 @@ def test_order_weight_change_line_quantity(staff_user, lines_info):new_quantity = line_info.quantity + 2order = line_info.line.orderchange_order_line_quantity(- staff_user, app, line_info, new_quantity, line_info.quantity, order.channel.slug+ staff_user,+ app,+ line_info,+ new_quantity,+ line_info.quantity,+ order.channel.slug,+ get_plugins_manager(),)assert order.weight == _calculate_order_weight_from_lines(order)@@ -678,7 +684,7 @@ def test_order_weight_change_line_quantity(staff_user, lines_info):def test_order_weight_delete_line(lines_info):order = lines_info[0].line.orderline_info = lines_info[0]- delete_order_line(line_info)+ delete_order_line(line_info, get_plugins_manager())assert order.weight == _calculate_order_weight_from_lines(order)@@ -967,10 +973,22 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):order = lines_info[0].line.orderassert not order.events.count()change_order_line_quantity(- staff_user, app, lines_info[1], lines_info[1].quantity, 0, order.channel.slug+ staff_user,+ app,+ lines_info[1],+ lines_info[1].quantity,+ 0,+ order.channel.slug,+ get_plugins_manager(),)change_order_line_quantity(- staff_user, app, lines_info[0], lines_info[0].quantity, 0, order.channel.slug+ staff_user,+ app,+ lines_info[0],+ lines_info[0].quantity,+ 0,+ order.channel.slug,+ get_plugins_manager(),)assert order.get_total_quantity() == 0@@ -984,7 +1002,13 @@ def test_change_order_line_quantity_changes_total_prices(line_info = lines_info[0]new_quantity = line_info.quantity + 1change_order_line_quantity(- staff_user, app, line_info, line_info.quantity, new_quantity, order.channel.slug+ staff_user,+ app,+ line_info,+ line_info.quantity,+ new_quantity,+ order.channel.slug,+ get_plugins_manager(),)assert line_info.line.total_price == line_info.line.unit_price * new_quantitydiff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex 8cfcbf26f3..ee6532d18e 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -303,6 +303,7 @@ def test_fulfill_order_lines(order_with_lines):warehouse_pk=stock.warehouse.pk,)],+ get_plugins_manager(),)stock.refresh_from_db()@@ -341,6 +342,7 @@ def test_fulfill_order_lines_multiple_lines(order_with_lines):warehouse_pk=stock_2.warehouse.pk,),],+ get_plugins_manager(),)stock_1.refresh_from_db()@@ -362,7 +364,9 @@ def test_fulfill_order_lines_with_variant_deleted(order_with_lines):line.refresh_from_db()- fulfill_order_lines([OrderLineData(line=line, quantity=line.quantity)])+ fulfill_order_lines(+ [OrderLineData(line=line, quantity=line.quantity)], get_plugins_manager()+ )def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):@@ -385,7 +389,8 @@ def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):variant=variant,warehouse_pk=stock.warehouse.pk,)- ]+ ],+ get_plugins_manager(),)stock.refresh_from_db()diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 3b53ac8452..bede997665 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -4,6 +4,7 @@ from unittest.mock import Mockimport pytestfrom prices import Money, TaxedMoney+from ...plugins.manager import get_plugins_managerfrom .. import OrderLineData, OrderStatusfrom ..events import OrderEventsfrom ..models import Order, OrderEvent@@ -58,6 +59,7 @@ def test_change_quantity_generates_proper_event(previous_quantity,new_quantity,order_with_lines.channel.slug,+ get_plugins_manager(),)if removed_count:@@ -104,6 +106,7 @@ def test_change_quantity_update_line_fields(line.quantity,new_quantity,order_with_lines.channel.slug,+ get_plugins_manager(),)# thendiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex e1da226c10..bb1120ab7c 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -327,6 +327,7 @@ def add_variant_to_order(old_quantity,new_quantity,channel.slug,+ manager=manager,send_event=False,)except OrderLine.DoesNotExist:@@ -393,6 +394,7 @@ def add_variant_to_order()],channel.slug,+ manager=manager,)return line@@ -417,7 +419,11 @@ def add_gift_card_to_order(order, gift_card, total_price_left):def _update_allocations_for_line(- line_info: OrderLineData, old_quantity: int, new_quantity: int, channel_slug: str+ line_info: OrderLineData,+ old_quantity: int,+ new_quantity: int,+ channel_slug: str,+ manager: "PluginsManager",):if old_quantity == new_quantity:return@@ -427,10 +433,10 @@ def _update_allocations_for_line(if old_quantity < new_quantity:line_info.quantity = new_quantity - old_quantity- increase_allocations([line_info], channel_slug)+ increase_allocations([line_info], channel_slug, manager)else:line_info.quantity = old_quantity - new_quantity- decrease_allocations([line_info])+ decrease_allocations([line_info], manager)def change_order_line_quantity(@@ -440,6 +446,7 @@ def change_order_line_quantity(old_quantity: int,new_quantity: int,channel_slug: str,+ manager: "PluginsManager",send_event=True,):"""Change the quantity of ordered items in a order line."""@@ -447,7 +454,7 @@ def change_order_line_quantity(if new_quantity:if line.order.is_unconfirmed():_update_allocations_for_line(- line_info, old_quantity, new_quantity, channel_slug+ line_info, old_quantity, new_quantity, channel_slug, manager)line.quantity = new_quantitytotal_price_net_amount = line.quantity * line.unit_price_net_amount@@ -478,7 +485,7 @@ def change_order_line_quantity(])else:- delete_order_line(line_info)+ delete_order_line(line_info, manager)quantity_diff = old_quantity - new_quantity@@ -500,14 +507,14 @@ def create_order_event(line, user, app, quantity_diff):)-def delete_order_line(line_info):+def delete_order_line(line_info, manager):"""Delete an order line from an order."""if line_info.line.order.is_unconfirmed():- decrease_allocations([line_info])+ decrease_allocations([line_info], manager)line_info.line.delete()-def restock_order_lines(order):+def restock_order_lines(order, manager):"""Return ordered products to corresponding stocks."""country = get_order_country(order)default_warehouse = Warehouse.objects.filter(@@ -533,7 +540,7 @@ def restock_order_lines(order):line.save(update_fields=["quantity_fulfilled"])if dellocating_stock_lines:- deallocate_stock(dellocating_stock_lines)+ deallocate_stock(dellocating_stock_lines, manager)def restock_fulfillment_lines(fulfillment, warehouse):diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex b3b1ccc526..61a82a403b 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -47,6 +47,7 @@ if TYPE_CHECKING:)from ..product.models import Product, ProductType, ProductVariantfrom ..translation.models import Translation+ from ..warehouse.models import Stockfrom .base_plugin import BasePlugin@@ -517,7 +518,21 @@ class PluginsManager(PaymentInterface):def product_variant_deleted(self, product_variant: "ProductVariant"):default_value = Nonereturn self.__run_method_on_plugins(- "product_variant_deleted", default_value, product_variant+ "product_variant_deleted",+ default_value,+ product_variant,+ )++ def product_variant_out_of_stock(self, stock: "Stock"):+ default_value = None+ self.__run_method_on_plugins(+ "product_variant_out_of_stock", default_value, stock+ )++ def product_variant_back_in_stock(self, stock: "Stock"):+ default_value = None+ self.__run_method_on_plugins(+ "product_variant_back_in_stock", default_value, stock)def order_created(self, order: "Order"):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 5650c88f91..dd44013de6 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -18,6 +18,7 @@ from ...webhook.payloads import (generate_product_deleted_payload,generate_product_payload,generate_product_variant_payload,+ generate_product_variant_with_stock_payload,generate_translation_payload,)from ..base_plugin import BasePlugin@@ -38,6 +39,7 @@ if TYPE_CHECKING:from ...payment.interface import GatewayResponse, PaymentData, PaymentGatewayfrom ...product.models import Product, ProductVariantfrom ...translation.models import Translation+ from ...warehouse.models import Stocklogger = logging.getLogger(__name__)@@ -205,6 +207,22 @@ class WebhookPlugin(BasePlugin):WebhookEventType.PRODUCT_VARIANT_DELETED, product_variant_data)+ def product_variant_out_of_stock(self, stock: "Stock", previous_value: Any) -> Any:+ if not self.active:+ return previous_value+ product_variant_data = generate_product_variant_with_stock_payload([stock])+ trigger_webhooks_for_event.delay(+ WebhookEventType.PRODUCT_VARIANT_OUT_OF_STOCK, product_variant_data+ )++ def product_variant_back_in_stock(self, stock: "Stock", previous_value: Any) -> Any:+ if not self.active:+ return previous_value+ product_variant_data = generate_product_variant_with_stock_payload([stock])+ trigger_webhooks_for_event.delay(+ WebhookEventType.PRODUCT_VARIANT_BACK_IN_STOCK, product_variant_data+ )+def checkout_created(self, checkout: "Checkout", previous_value: Any) -> Any:if not self.active:return previous_valuediff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex 05b60023e4..372490de92 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -26,6 +26,7 @@ from ....webhook.payloads import (generate_product_deleted_payload,generate_product_payload,generate_product_variant_payload,+ generate_product_variant_with_stock_payload,)from ...manager import get_plugins_managerfrom ...webhook.tasks import trigger_webhooks_for_event@@ -238,6 +239,38 @@ def test_product_variant_deleted(mocked_webhook_trigger, settings, variant):)[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")+def test_product_variant_out_of_stock(+ mocked_webhook_trigger, settings, variant_with_many_stocks+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ manager = get_plugins_manager()+ manager.product_variant_out_of_stock(variant_with_many_stocks.stocks.first())++ expected_data = generate_product_variant_with_stock_payload(+ [variant_with_many_stocks.stocks.first()]+ )+ mocked_webhook_trigger.assert_called_once_with(+ WebhookEventType.PRODUCT_VARIANT_OUT_OF_STOCK, expected_data+ )++[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")+def test_product_variant_back_in_stock(+ mocked_webhook_trigger, settings, variant_with_many_stocks+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ manager = get_plugins_manager()+ manager.product_variant_back_in_stock(variant_with_many_stocks.stocks.first())++ expected_data = generate_product_variant_with_stock_payload(+ [variant_with_many_stocks.stocks.first()]+ )+ mocked_webhook_trigger.assert_called_once_with(+ WebhookEventType.PRODUCT_VARIANT_BACK_IN_STOCK, expected_data+ )++@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")def test_order_updated(mocked_webhook_trigger, settings, order_with_lines):settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f6c7749796..e1be38019a 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -3015,6 +3015,7 @@ def fulfilled_order(order_with_lines):line=line_2, quantity=line_2.quantity, warehouse_pk=warehouse_2_pk),],+ manager=get_plugins_manager(),)order.status = OrderStatus.FULFILLEDorder.save(update_fields=["status"])@@ -3032,7 +3033,8 @@ def fulfilled_order_without_inventory_tracking(warehouse_pk = stock.warehouse.pkfulfillment.lines.create(order_line=line, quantity=line.quantity, stock=stock)fulfill_order_lines(- [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)]+ [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],+ get_plugins_manager(),)order.status = OrderStatus.FULFILLEDorder.save(update_fields=["status"])diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex d11011f7d2..9d5f76c5a3 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -71,14 +71,16 @@ def check_stock_quantity_bulk(if not stocks:insufficient_stocks.append(InsufficientStockData(- variant=variant, available_quantity=available_quantity+ variant=variant,+ available_quantity=available_quantity,))elif variant.track_inventory:if quantity > available_quantity:insufficient_stocks.append(InsufficientStockData(- variant=variant, available_quantity=available_quantity+ variant=variant,+ available_quantity=available_quantity,))diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 5d153c5b67..96bd7aa9ad 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -1,11 +1,13 @@from collections import defaultdict, namedtuplefrom typing import TYPE_CHECKING, Dict, Iterable, List, cast+from django.db import transactionfrom django.db.models import F, Sumfrom ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockDatafrom ..core.tracing import traced_atomic_transactionfrom ..order import OrderLineData+from ..plugins.manager import PluginsManagerfrom ..product.models import ProductVariantfrom .models import Allocation, Stock, Warehouse@@ -18,7 +20,10 @@ StockData = namedtuple("StockData", ["pk", "quantity"])@traced_atomic_transaction()def allocate_stocks(- order_lines_info: Iterable["OrderLineData"], country_code: str, channel_slug: str+ order_lines_info: Iterable["OrderLineData"],+ country_code: str,+ channel_slug: str,+ manager: PluginsManager,):"""Allocate stocks for given `order_lines` in given country.@@ -84,6 +89,18 @@ def allocate_stocks(if allocations:Allocation.objects.bulk_create(allocations)+ for allocation in allocations:+ allocated_stock = (+ Allocation.objects.filter(stock_id=allocation.stock_id).aggregate(+ Sum("quantity_allocated")+ )["quantity_allocated__sum"]+ or 0+ )+ if not max(allocation.stock.quantity - allocated_stock, 0):+ transaction.on_commit(+ lambda: manager.product_variant_out_of_stock(allocation.stock)+ )+def _create_allocations(line_info: "OrderLineData",@@ -127,7 +144,9 @@ def _create_allocations(@traced_atomic_transaction()-def deallocate_stock(order_lines_data: Iterable["OrderLineData"]):+def deallocate_stock(+ order_lines_data: Iterable["OrderLineData"], manager: PluginsManager+):"""Deallocate stocks for given `order_lines`.Function lock for update stocks and allocations related to given `order_lines`.@@ -178,8 +197,28 @@ def deallocate_stock(order_lines_data: Iterable["OrderLineData"]):if not_dellocated_lines:raise AllocationError(not_dellocated_lines)+ allocations_before_update = list(+ Allocation.objects.filter(+ id__in=[a.id for a in allocations_to_update]+ ).annotate_stock_available_quantity()+ )+Allocation.objects.bulk_update(allocations_to_update, ["quantity_allocated"])+ for allocation_before_update in allocations_before_update:+ available_stock_now = Allocation.objects.available_quantity_for_stock(+ allocation_before_update.stock+ )+ if (+ allocation_before_update.stock_available_quantity == 0+ and available_stock_now > 0+ ):+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(+ allocation_before_update.stock+ )+ )+@traced_atomic_transaction()def increase_stock(@@ -221,7 +260,9 @@ def increase_stock(@traced_atomic_transaction()-def increase_allocations(lines_info: Iterable["OrderLineData"], channel_slug: str):+def increase_allocations(+ lines_info: Iterable["OrderLineData"], channel_slug: str, manager: PluginsManager+):"""Increase allocation for order lines with appropriate quantity."""line_pks = [info.line.pk for info in lines_info]allocations = list(@@ -247,19 +288,22 @@ def increase_allocations(lines_info: Iterable["OrderLineData"], channel_slug: stlines_info,lines_info[0].line.order.shipping_address.country.code, # type: ignorechannel_slug,+ manager,)-def decrease_allocations(lines_info: Iterable["OrderLineData"]):+def decrease_allocations(lines_info: Iterable["OrderLineData"], manager):"""Decreate allocations for provided order lines."""tracked_lines = get_order_lines_with_track_inventory(lines_info)if not tracked_lines:return- decrease_stock(tracked_lines, update_stocks=False)+ decrease_stock(tracked_lines, update_stocks=False, manager=manager)@traced_atomic_transaction()-def decrease_stock(order_lines_info: Iterable["OrderLineData"], update_stocks=True):+def decrease_stock(+ order_lines_info: Iterable["OrderLineData"], manager, update_stocks=True+):"""Decrease stocks quantities for given `order_lines` in given warehouses.Function deallocate as many quantities as requested if order_line has less quantity@@ -273,7 +317,7 @@ def decrease_stock(order_lines_info: Iterable["OrderLineData"], update_stocks=Trvariants = [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)+ deallocate_stock(order_lines_info, manager)except AllocationError as exc:Allocation.objects.filter(order_line__in=exc.order_lines).update(quantity_allocated=0@@ -307,7 +351,6 @@ def decrease_stock(order_lines_info: Iterable["OrderLineData"], update_stocks=Trquantity_allocation_for_stocks[allocation["stock"]] += allocation["quantity_allocated__sum"]-if update_stocks:_decrease_stocks_quantity(order_lines_info,@@ -315,6 +358,15 @@ def decrease_stock(order_lines_info: Iterable["OrderLineData"], update_stocks=Trquantity_allocation_for_stocks,)+ 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(order_lines_info: Iterable["OrderLineData"],@@ -348,7 +400,6 @@ def _decrease_stocks_quantity())continue-stock.quantity = stock.quantity - line_info.quantitystocks_to_update.append(stock)@@ -370,9 +421,16 @@ def get_order_lines_with_track_inventory(@traced_atomic_transaction()-def deallocate_stock_for_order(order: "Order"):+def deallocate_stock_for_order(order: "Order", manager: PluginsManager):"""Remove all allocations for given order."""allocations = Allocation.objects.filter(order_line__order=order, quantity_allocated__gt=0- ).select_for_update(of=("self",))+ )++ for allocation in allocations.annotate_stock_available_quantity():+ if allocation.stock_available_quantity <= 0:+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(allocation.stock)+ )+allocations.update(quantity_allocated=0)diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 7aba6769da..2e733417a5 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -146,6 +146,23 @@ class Stock(models.Model):self.save(update_fields=["quantity"])+class AllocationQueryset(models.QuerySet):+ def annotate_stock_available_quantity(self):+ return self.annotate(+ stock_available_quantity=F("stock__quantity")+ - Coalesce(Sum("stock__allocations__quantity_allocated"), 0)+ )++ def available_quantity_for_stock(self, stock: "Stock"):+ allocated_quantity = (+ self.filter(stock=stock).aggregate(Sum("quantity_allocated"))[+ "quantity_allocated__sum"+ ]+ or 0+ )+ return max(stock.quantity - allocated_quantity, 0)++class Allocation(models.Model):order_line = models.ForeignKey(OrderLine,@@ -163,6 +180,8 @@ class Allocation(models.Model):)quantity_allocated = models.PositiveIntegerField(default=0)+ objects = models.Manager.from_queryset(AllocationQueryset)()+class Meta:unique_together = [["order_line", "stock"]]ordering = ("pk",)diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex e983f024e2..38248cc28c 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -1,3 +1,5 @@+from unittest import mock+import pytestfrom django.db.models import Sumfrom django.db.models.functions import Coalesce@@ -5,6 +7,8 @@ from django.db.models.functions import Coalescefrom ...core.exceptions import InsufficientStockfrom ...order import OrderLineDatafrom ...order.models import OrderLine+from ...plugins.manager import get_plugins_manager+from ...tests.utils import flush_post_commit_hooksfrom ...warehouse.models import Stockfrom ..management import (allocate_stocks,@@ -25,10 +29,13 @@ def test_allocate_stocks(order_line, stock, channel_USD):line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=50)- allocate_stocks([line_data], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ )stock.refresh_from_db()assert stock.quantity == 100+ assert stock.quantity == 100allocation = Allocation.objects.get(order_line=order_line, stock=stock)assert allocation.quantity_allocated == 50@@ -57,7 +64,12 @@ def test_allocate_stocks_multiple_lines(order_line, order, product, stock, channline=order_line_2, variant=variant_2, quantity=quantity_2)- allocate_stocks([line_data_1, line_data_2], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data_1, line_data_2],+ COUNTRY_CODE,+ channel_USD.slug,+ manager=get_plugins_manager(),+ )stock.refresh_from_db()assert stock.quantity == 100@@ -74,7 +86,9 @@ def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channestocks = variant.stocks.all()line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=5)- allocate_stocks([line_data], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ )allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)assert allocations[0].quantity_allocated == 4@@ -92,7 +106,9 @@ def test_allocate_stock_many_stocks_partially_allocated(stocks = variant.stocks.all()line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=3)- allocate_stocks([line_data], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ )allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)assert allocations[0].quantity_allocated == 1@@ -108,7 +124,9 @@ def test_allocate_stock_partially_allocated_insufficient_stocks(line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=6)with pytest.raises(InsufficientStock):- allocate_stocks([line_data], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ )assert not Allocation.objects.filter(order_line=order_line, stock__in=stocks@@ -123,7 +141,9 @@ def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_USline_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=50)with pytest.raises(InsufficientStock):- allocate_stocks([line_data], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ )def test_allocate_stock_insufficient_stocks(@@ -134,7 +154,9 @@ def test_allocate_stock_insufficient_stocks(line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=10)with pytest.raises(InsufficientStock):- allocate_stocks([line_data], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ )assert not Allocation.objects.filter(order_line=order_line, stock__in=stocks@@ -167,7 +189,12 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines()with pytest.raises(InsufficientStock) as exc:- allocate_stocks([line_data_1, line_data_2], COUNTRY_CODE, channel_USD.slug)+ allocate_stocks(+ [line_data_1, line_data_2],+ COUNTRY_CODE,+ channel_USD.slug,+ manager=get_plugins_manager(),+ )assert set(item.variant for item in exc._excinfo[1].items) == {variant, variant_2}@@ -188,7 +215,8 @@ def test_deallocate_stock(allocation):OrderLineData(line=allocation.order_line, quantity=80, variant=stock.product_variant)- ]+ ],+ manager=get_plugins_manager(),)stock.refresh_from_db()@@ -209,7 +237,8 @@ def test_deallocate_stock_partially(allocation):OrderLineData(line=allocation.order_line, quantity=50, variant=stock.product_variant)- ]+ ],+ manager=get_plugins_manager(),)stock.refresh_from_db()@@ -224,7 +253,8 @@ def test_deallocate_stock_many_allocations(order_line = order_line_with_allocation_in_many_stocksdeallocate_stock(- [OrderLineData(line=order_line, quantity=3, variant=order_line.variant)]+ [OrderLineData(line=order_line, quantity=3, variant=order_line.variant)],+ manager=get_plugins_manager(),)allocations = order_line.allocations.all()@@ -238,7 +268,8 @@ def test_deallocate_stock_many_allocations_partially(order_line = order_line_with_allocation_in_many_stocksdeallocate_stock(- [OrderLineData(line=order_line, quantity=1, variant=order_line.variant)]+ [OrderLineData(line=order_line, quantity=1, variant=order_line.variant)],+ manager=get_plugins_manager(),)allocations = order_line.allocations.all()@@ -305,7 +336,9 @@ def test_increase_allocations(quantity, allocation):allocation.quantity_allocated = initially_allocatedallocation.save(update_fields=["quantity_allocated"])- increase_allocations([order_line_info], order_line.order.channel.slug)+ increase_allocations(+ [order_line_info], order_line.order.channel.slug, manager=get_plugins_manager()+ )stock.refresh_from_db()assert stock.quantity == 100@@ -333,7 +366,11 @@ def test_increase_allocation_insufficient_stock(allocation):allocation.save(update_fields=["quantity_allocated"])with pytest.raises(InsufficientStock):- increase_allocations([order_line_info], order_line.order.channel.slug)+ increase_allocations(+ [order_line_info],+ order_line.order.channel.slug,+ manager=get_plugins_manager(),+ )stock.refresh_from_db()assert stock.quantity == 100@@ -345,6 +382,22 @@ def test_increase_allocation_insufficient_stock(allocation):)[email protected]("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_increase_stock_with_back_in_stock_webhook_triggered_without_allocation(+ product_variant_back_in_stock_webhook, allocation+):+ stock = allocation.stock+ stock.quantity = 0+ stock.save(update_fields=["quantity"])++ increase_stock(allocation.order_line, stock.warehouse, 50, allocate=False)+ flush_post_commit_hooks()++ stock.refresh_from_db()+ assert stock.quantity == 50+ product_variant_back_in_stock_webhook.assert_not_called()++def test_decrease_stock(allocation):stock = allocation.stockstock.quantity = 100@@ -362,6 +415,7 @@ def test_decrease_stock(allocation):warehouse_pk=warehouse_pk,)],+ manager=get_plugins_manager(),)stock.refresh_from_db()@@ -388,6 +442,7 @@ def test_decrease_stock_without_stock_update(quantity, expected_allocated, allocwarehouse_pk=warehouse_pk,)],+ manager=get_plugins_manager(),update_stocks=False,)@@ -427,6 +482,7 @@ def test_decrease_stock_multiple_lines(allocations):warehouse_pk=warehouse_pk_2,),],+ manager=get_plugins_manager(),)stock.refresh_from_db()@@ -452,6 +508,7 @@ def test_decrease_stock_partially(allocation):warehouse_pk=str(warehouse_pk),)],+ manager=get_plugins_manager(),)stock.refresh_from_db()@@ -476,6 +533,7 @@ def test_decrease_stock_many_allocations(warehouse_pk=str(warehouse_pk),)],+ manager=get_plugins_manager(),)assert allocations[0].quantity_allocated == 0@@ -500,7 +558,8 @@ def test_decrease_stock_many_allocations_partially(warehouse_pk=str(warehouse_pk),)],- )+ manager=get_plugins_manager(),+ ),assert allocations[0].quantity_allocated == 0assert allocations[1].quantity_allocated == 1@@ -528,6 +587,7 @@ def test_decrease_stock_more_then_allocated(warehouse_pk=warehouse_pk,)],+ manager=get_plugins_manager(),)allocations = order_line.allocations.all()@@ -555,6 +615,7 @@ def test_decrease_stock_insufficient_stock(allocation):warehouse_pk=warehouse_pk,)],+ manager=get_plugins_manager(),)stock.refresh_from_db()@@ -569,8 +630,70 @@ def test_deallocate_stock_for_order(order_line = order_line_with_allocation_in_many_stocksorder = order_line.order- deallocate_stock_for_order(order)+ deallocate_stock_for_order(order, manager=get_plugins_manager())allocations = order_line.allocations.all()assert allocations[0].quantity_allocated == 0assert allocations[1].quantity_allocated == 0++[email protected]("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, allocation+):+ stock = allocation.stock+ stock.quantity = 10+ stock.save(update_fields=["quantity"])++ increase_stock(allocation.order_line, stock.warehouse, 50, allocate=False)++ stock.refresh_from_db()+ assert stock.quantity == 60++ flush_post_commit_hooks()+ product_variant_back_in_stock_webhook.assert_not_called()++[email protected]("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+def test_increase_stock_with_back_in_stock_webhook_not_triggered_with_allocation(+ product_variant_back_in_stock_webhook, allocation+):+ stock = allocation.stock+ stock.quantity = 0+ stock.save(update_fields=["quantity"])++ increase_stock(allocation.order_line, stock.warehouse, 30, allocate=True)++ stock.refresh_from_db()+ assert stock.quantity == 30++ flush_post_commit_hooks()+ product_variant_back_in_stock_webhook.assert_not_called()++[email protected]("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_decrease_stock_with_out_of_stock_webhook_triggered(+ product_variant_out_of_stock_webhook_mock, allocation+):+ stock = allocation.stock+ stock.quantity = 50+ stock.save(update_fields=["quantity"])+ allocation.quantity_allocated = 50+ allocation.save(update_fields=["quantity_allocated"])+ warehouse_pk = allocation.stock.warehouse.pk++ decrease_stock(+ [+ OrderLineData(+ line=allocation.order_line,+ quantity=50,+ variant=stock.product_variant,+ warehouse_pk=warehouse_pk,+ )+ ],+ manager=get_plugins_manager(),+ )++ flush_post_commit_hooks()++ product_variant_out_of_stock_webhook_mock.assert_called_once()diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex f56b41cbfc..8a0a2e8f90 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -36,6 +36,9 @@ class WebhookEventType:PRODUCT_VARIANT_UPDATED = "product_variant_updated"PRODUCT_VARIANT_DELETED = "product_variant_deleted"+ PRODUCT_VARIANT_OUT_OF_STOCK = "product_variant_out_of_stock"+ PRODUCT_VARIANT_BACK_IN_STOCK = "product_variant_back_in_stock"+CHECKOUT_CREATED = "checkout_created"CHECKOUT_UPDATED = "checkout_updated"@@ -75,6 +78,8 @@ class WebhookEventType:PRODUCT_VARIANT_CREATED: "Product variant created",PRODUCT_VARIANT_UPDATED: "Product variant updated",PRODUCT_VARIANT_DELETED: "Product variant deleted",+ PRODUCT_VARIANT_OUT_OF_STOCK: "Product variant stock changed",+ PRODUCT_VARIANT_BACK_IN_STOCK: "Product variant back in stock",CHECKOUT_CREATED: "Checkout created",CHECKOUT_UPDATED: "Checkout updated",FULFILLMENT_CREATED: "Fulfillment_created",@@ -113,6 +118,8 @@ class WebhookEventType:(PRODUCT_VARIANT_CREATED, DISPLAY_LABELS[PRODUCT_VARIANT_CREATED]),(PRODUCT_VARIANT_UPDATED, DISPLAY_LABELS[PRODUCT_VARIANT_UPDATED]),(PRODUCT_VARIANT_DELETED, DISPLAY_LABELS[PRODUCT_VARIANT_DELETED]),+ (PRODUCT_VARIANT_OUT_OF_STOCK, DISPLAY_LABELS[PRODUCT_VARIANT_OUT_OF_STOCK]),+ (PRODUCT_VARIANT_BACK_IN_STOCK, DISPLAY_LABELS[PRODUCT_VARIANT_BACK_IN_STOCK]),(CHECKOUT_CREATED, DISPLAY_LABELS[CHECKOUT_CREATED]),(CHECKOUT_UPDATED, DISPLAY_LABELS[CHECKOUT_UPDATED]),(FULFILLMENT_CREATED, DISPLAY_LABELS[FULFILLMENT_CREATED]),@@ -160,6 +167,8 @@ class WebhookEventType:PRODUCT_VARIANT_CREATED: ProductPermissions.MANAGE_PRODUCTS,PRODUCT_VARIANT_UPDATED: ProductPermissions.MANAGE_PRODUCTS,PRODUCT_VARIANT_DELETED: ProductPermissions.MANAGE_PRODUCTS,+ PRODUCT_VARIANT_BACK_IN_STOCK: ProductPermissions.MANAGE_PRODUCTS,+ PRODUCT_VARIANT_OUT_OF_STOCK: ProductPermissions.MANAGE_PRODUCTS,CHECKOUT_CREATED: CheckoutPermissions.MANAGE_CHECKOUTS,CHECKOUT_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,FULFILLMENT_CREATED: OrderPermissions.MANAGE_ORDERS,diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex c2d2dd6a19..e079b6b769 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -4,7 +4,7 @@ from dataclasses import asdictfrom typing import TYPE_CHECKING, Iterable, Optionalimport graphene-from django.db.models import F, QuerySet+from django.db.models import F, QuerySet, Sumfrom ..attribute.models import AttributeValueTranslationfrom ..checkout.models import Checkout@@ -23,7 +23,7 @@ from ..payment import ChargeStatusfrom ..plugins.webhook.utils import from_payment_app_idfrom ..product import ProductMediaTypesfrom ..product.models import Product-from ..warehouse.models import Warehouse+from ..warehouse.models import Stock, Warehousefrom .event_types import WebhookEventTypefrom .payload_serializers import PayloadSerializerfrom .serializers import (@@ -396,6 +396,23 @@ def generate_product_variant_media_payload(product_variant):]+def generate_product_variant_with_stock_payload(stocks: Iterable["Stock"]):+ serializer = PayloadSerializer()+ extra_dict_data = {+ "product_id": lambda v: graphene.Node.to_global_id(+ "Product", v.product_variant.product_id+ ),+ "product_variant_id": lambda v: graphene.Node.to_global_id(+ "ProductVariant", v.product_variant_id+ ),+ "warehouse_id": lambda v: graphene.Node.to_global_id(+ "Warehouse", v.warehouse_id+ ),+ "product_slug": lambda v: v.product_variant.product.slug,+ }+ return serializer.serialize(stocks, fields=[], extra_dict_data=extra_dict_data)++def generate_product_variant_payload(product_variants: Iterable["ProductVariant"]):serializer = PayloadSerializer()payload = serializer.serialize(@@ -413,6 +430,10 @@ def generate_product_variant_payload(product_variants: Iterable["ProductVariant"return payload+def generate_product_variant_stocks_payload(product_variant: "ProductVariant"):+ return product_variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] or 0++def generate_fulfillment_lines_payload(fulfillment: Fulfillment):serializer = PayloadSerializer()lines = FulfillmentLine.objects.prefetch_related(diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 8646eaebe6..9659bd45d4 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -12,6 +12,7 @@ from ...discount import DiscountValueType, OrderDiscountTypefrom ...order import OrderLineData, OrderOriginfrom ...order.actions import fulfill_order_linesfrom ...order.models import Order+from ...plugins.manager import get_plugins_managerfrom ...plugins.webhook.utils import from_payment_app_idfrom ...product.models import ProductVariantfrom ..payloads import (@@ -25,6 +26,7 @@ from ..payloads import (generate_order_payload,generate_payment_payload,generate_product_variant_payload,+ generate_product_variant_with_stock_payload,generate_translation_payload,)@@ -121,9 +123,8 @@ def test_generate_fulfillment_lines_payload(order_with_lines):order_line=line, quantity=line.quantity, stock=stock)fulfill_order_lines(- [- OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk),- ]+ [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],+ get_plugins_manager(),)payload = json.loads(generate_fulfillment_lines_payload(fulfillment))[0]@@ -227,6 +228,47 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat}+def test_generate_base_product_variant_payload(product_with_two_variants):+ stocks_to_serialize = [+ variant.stocks.first() for variant in product_with_two_variants.variants.all()+ ]+ first_stock, second_stock = stocks_to_serialize+ payload = json.loads(+ generate_product_variant_with_stock_payload(stocks_to_serialize)+ )+ expected_payload = [+ {+ "type": "Stock",+ "id": graphene.Node.to_global_id("Stock", first_stock.id),+ "product_id": graphene.Node.to_global_id(+ "Product", first_stock.product_variant.product_id+ ),+ "product_variant_id": graphene.Node.to_global_id(+ "ProductVariant", first_stock.product_variant_id+ ),+ "warehouse_id": graphene.Node.to_global_id(+ "Warehouse", first_stock.warehouse_id+ ),+ "product_slug": "test-product-with-two-variant",+ },+ {+ "type": "Stock",+ "id": graphene.Node.to_global_id("Stock", second_stock.id),+ "product_id": graphene.Node.to_global_id(+ "Product", second_stock.product_variant.product_id+ ),+ "product_variant_id": graphene.Node.to_global_id(+ "ProductVariant", second_stock.product_variant_id+ ),+ "warehouse_id": graphene.Node.to_global_id(+ "Warehouse", second_stock.warehouse_id+ ),+ "product_slug": "test-product-with-two-variant",+ },+ ]+ assert payload == expected_payload++def test_generate_product_variant_payload(product_with_variant_with_two_attributes, product_with_images, channel_USD):