Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extract stock logic from webhook plugin to webhook module (#19092) (#19105)
Iga Karbowiak35d5dfdae1a2
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 5edfbc5e21..b606f02c74 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -844,7 +844,7 @@ def _create_order(order_lines_info,country_code,checkout_info.channel,- manager,+ app or user,calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,collection_point_pk=checkout_info.get_delivery_method_info().warehouse_pk,additional_filter_lookup=additional_warehouse_lookup,@@ -1272,7 +1272,7 @@ def _handle_allocations_of_order_lines(checkout_info: CheckoutInfo,checkout_lines: list[CheckoutLineInfo],order_lines_info: list[OrderLineInfo],- manager: "PluginsManager",+ requestor: "App | User | None",reservation_enabled: bool,calculate_stocks_with_shipping_zones: bool,):@@ -1284,7 +1284,7 @@ def _handle_allocations_of_order_lines(order_lines_info,country_code,checkout_info.channel,- manager,+ requestor,calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,collection_point_pk=checkout_info.get_delivery_method_info().warehouse_pk,additional_filter_lookup=additional_warehouse_lookup,@@ -1524,7 +1524,7 @@ def _create_order_from_checkout(checkout_info=checkout_info,checkout_lines=checkout_lines_info,order_lines_info=order_lines_info,- manager=manager,+ requestor=app or user,reservation_enabled=reservation_enabled,calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,)diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 0537e6ead8..3ea8376865 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -1643,7 +1643,7 @@ def test_complete_checkout(api_client, checkout_with_charged_payment, count_quer@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_complete_checkout_with_out_of_stock_webhook(product_variant_out_of_stock_webhook_mock,api_client,@@ -1659,7 +1659,7 @@ def test_complete_checkout_with_out_of_stock_webhook(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()+ Stock.objects.last(), requestor=api_client.app)diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex ea4ee7f690..a9a5348f26 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -215,7 +215,7 @@ class DraftOrderComplete(BaseMutation):[line_data],country,channel,- manager,+ requestor,check_reservations=is_reservation_enabled(site_settings),diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 7f3c3efaae..e6d48dc6d3 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -370,14 +370,14 @@ class DraftOrderCreate(cleaned_input["lines_data"] = grouped_lines_data@staticmethod- def _save_lines(info, instance, lines_data, app, manager, site_settings):+ def _save_lines(info, instance, lines_data, app, requestor, site_settings):lines = []if lines_data:for line_data in lines_data:new_line = create_order_line(instance,line_data,- manager,+ requestor,site_settings,)lines.append(new_line)@@ -395,6 +395,7 @@ class DraftOrderCreate(manager = get_plugin_manager_promise(info.context).get()app = get_app_promise(info.context).get()site = get_site_promise(info.context).get()+ requestor = app or info.context.userwith traced_atomic_transaction():# Process addresses@@ -407,7 +408,7 @@ class DraftOrderCreate(instance,cleaned_input.get("lines_data"),app,- manager,+ requestor,site.settings,)except TaxError as e:diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.pyindex b09bd939ec..52ade39ebd 100644--- a/saleor/graphql/order/mutations/order_line_delete.py+++ b/saleor/graphql/order/mutations/order_line_delete.py@@ -21,6 +21,7 @@ from ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ...core.utils import raise_validation_errorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_contextfrom ..types import Order, OrderLinefrom .utils import EditableOrderValidationMixin, call_event_by_order_status@@ -46,6 +47,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):cls, _root, info: ResolveInfo, /, *, id):manager = get_plugin_manager_promise(info.context).get()+ requestor = get_user_or_app_from_context(info.context)line = cls.get_node_or_error(info,id,@@ -73,7 +75,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):variant=line.variant,warehouse_pk=warehouse_pk,)- delete_order_line(line_info, manager)+ delete_order_line(line_info, requestor)line.id = db_idupdated_fields = []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 56cc5877dd..df40209322 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@@ -70,7 +70,7 @@ 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.warehouse.management.trigger_product_variant_back_in_stock")@patch("saleor.payment.gateway.refund")def test_fulfillment_return_products_order_lines(mocked_refund,@@ -171,4 +171,6 @@ def test_fulfillment_return_products_order_lines(assert data["returnFulfillment"]assert data["replaceFulfillment"]- back_in_stock_webhook_mock.assert_called_once_with(Stock.objects.last())+ back_in_stock_webhook_mock.assert_called_once_with(+ Stock.objects.last(), requestor=staff_api_client.user+ )diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex d06a11b146..017d8bcbb1 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -104,7 +104,7 @@ DRAFT_ORDER_COMPLETE_MUTATION = """"saleor.graphql.order.mutations.draft_order_complete.order_created",wraps=order_created,)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_draft_order_complete(product_variant_out_of_stock_webhook_mock,order_created_mock,@@ -163,7 +163,7 @@ def test_draft_order_complete(assert 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()+ Stock.objects.last(), requestor=staff_api_client.user)assert order_created_mock.calledstore_user_addresses_from_draft_order_mock.assert_called_once()@@ -238,7 +238,7 @@ def test_draft_order_complete_by_user_no_channel_access(assert_no_permission(response)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_draft_order_complete_by_app(product_variant_out_of_stock_webhook_mock,app_api_client,@@ -268,7 +268,7 @@ def test_draft_order_complete_by_app(assert order.search_vector-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_draft_order_complete_with_voucher(product_variant_out_of_stock_webhook_mock,staff_api_client,@@ -346,7 +346,7 @@ def test_draft_order_complete_with_voucher(assert 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()+ Stock.objects.last(), requestor=staff_user)assert not VoucherCustomer.objects.filter(voucher_code=code_instance, customer_email=order.get_customer_email()@@ -409,7 +409,7 @@ def test_draft_order_complete_with_voucher_once_per_customer().exists()-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_draft_order_complete_0_total(product_variant_out_of_stock_webhook_mock,staff_api_client,@@ -473,11 +473,11 @@ def test_draft_order_complete_0_total(assert 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()+ Stock.objects.last(), requestor=staff_user)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_draft_order_complete_without_sku(product_variant_out_of_stock_webhook_mock,staff_api_client,@@ -529,11 +529,11 @@ def test_draft_order_complete_without_sku(assert 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()+ Stock.objects.last(), requestor=staff_user)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -562,7 +562,9 @@ def test_draft_order_complete_with_out_of_stock_webhook()["quantity_allocated__sum"]assert total_stock == total_allocationassert product_variant_out_of_stock_webhook_mock.call_count == 2- product_variant_out_of_stock_webhook_mock.assert_called_with(Stock.objects.last())+ product_variant_out_of_stock_webhook_mock.assert_called_with(+ Stock.objects.last(), requestor=staff_api_client.user+ )def test_draft_order_from_reissue_complete(diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.pyindex afd572e340..a3d26d9b76 100644--- a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py@@ -8,7 +8,6 @@ from .....order.actions import fulfill_order_linesfrom .....order.error_codes import OrderErrorCodefrom .....order.fetch import OrderLineInfofrom .....order.models import OrderLine-from .....plugins.manager import get_plugins_managerfrom .....product.models import Productfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -270,7 +269,7 @@ def test_fulfillment_approve_gift_cards_created(warehouse_pk=stock_2.warehouse.pk,),],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)query = APPROVE_FULFILLMENT_MUTATIONdiff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.pyindex 937f31988e..b6a5e1baf5 100644--- a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py@@ -127,7 +127,7 @@ def test_fulfillment_refund_products_with_action_requested_by_app(@patch("saleor.payment.gateway.refund")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.warehouse.management.trigger_product_variant_back_in_stock")def test_fulfillment_refund_products_with_back_in_stock_webhook(back_in_stock_webhook_trigger,mock_refunded,@@ -157,7 +157,9 @@ def test_fulfillment_refund_products_with_back_in_stock_webhook(errors = data["errors"]assert not errorsassert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()- back_in_stock_webhook_trigger.assert_called_once_with(Stock.objects.first())+ back_in_stock_webhook_trigger.assert_called_once_with(+ Stock.objects.first(), requestor=staff_api_client.user+ )def test_fulfillment_refund_gift_card_products(diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.pyindex 9f7e015856..aee0b4bdb4 100644--- a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py@@ -94,7 +94,7 @@ def test_order_bulk_cancel_by_user_no_channel_access(assert_no_permission(response)-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.warehouse.management.trigger_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,diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.pyindex bd52ec86e6..681f125f03 100644--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py@@ -43,7 +43,7 @@ ORDER_FULFILL_MUTATION = """@patch("saleor.order.actions.order_fulfilled", wraps=order_fulfilled)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_order_fulfill_with_out_of_stock_webhook(product_variant_out_of_stock_webhooks,wrapped_order_fulfilled,@@ -75,7 +75,9 @@ def test_order_fulfill_with_out_of_stock_webhook(staff_api_client.post_graphql(query, variables)stock = order_line2.variant.stocks.filter(warehouse=warehouse).first()- product_variant_out_of_stock_webhooks.assert_called_once_with(stock)+ product_variant_out_of_stock_webhooks.assert_called_once_with(+ stock, requestor=staff_api_client.user+ )assert wrapped_order_fulfilled.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_line_delete.py b/saleor/graphql/order/tests/mutations/test_order_line_delete.pyindex 71c27e4864..c4637753f8 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_delete.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_delete.py@@ -45,7 +45,7 @@ ORDER_LINE_DELETE_MUTATION = """"""-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.warehouse.management.trigger_product_variant_back_in_stock")def test_order_line_remove_with_back_in_stock_webhook(back_in_stock_webhook_mock,order_with_lines,@@ -92,7 +92,9 @@ def test_order_line_remove_with_back_in_stock_webhook(or 0)) == 3- back_in_stock_webhook_mock.assert_called_once_with(Stock.objects.first())+ back_in_stock_webhook_mock.assert_called_once_with(+ Stock.objects.first(), requestor=staff_api_client.user+ )@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])diff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.pyindex 973c621867..6020e95641 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py@@ -96,7 +96,7 @@ ORDER_LINE_UPDATE_MUTATION = """"""-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -125,10 +125,12 @@ def test_order_line_update_with_out_of_stock_webhook_for_two_lines_success_scena# thenassert out_of_stock_mock.call_count == 2- out_of_stock_mock.assert_called_with(Stock.objects.last())+ out_of_stock_mock.assert_called_with(+ Stock.objects.last(), requestor=staff_api_client.user+ )-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_order_line_update_with_out_of_stock_webhook_success_scenario(out_of_stock_mock,order_with_lines,@@ -148,10 +150,12 @@ def test_order_line_update_with_out_of_stock_webhook_success_scenario(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())+ out_of_stock_mock.assert_called_once_with(+ Stock.objects.first(), requestor=staff_api_client.user+ )-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -174,7 +178,7 @@ def test_order_line_update_with_back_in_stock_webhook_fail_scenario(product_variant_back_in_stock_webhook_mock.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -197,10 +201,12 @@ def test_order_line_update_with_back_in_stock_webhook_called_once_success_scenarpermission_group_manage_orders.user_set.add(staff_api_client.user)staff_api_client.post_graphql(query, variables)- back_in_stock_mock.assert_called_once_with(first_allocated.stock)+ back_in_stock_mock.assert_called_once_with(+ first_allocated.stock, requestor=staff_api_client.user+ )-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -229,7 +235,9 @@ def test_order_line_update_with_back_in_stock_webhook_called_twice_success_scenastaff_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())+ product_variant_back_in_stock_webhook_mock.assert_called_with(+ Stock.objects.last(), requestor=staff_api_client.user+ )@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.pyindex bcf8ac4f2c..7f5c5eb84c 100644--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py@@ -118,7 +118,7 @@ ORDER_LINES_CREATE_MUTATION = """"""-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -147,11 +147,11 @@ def test_order_lines_create_with_out_of_stock_webhook(]assert quantity_allocated == stock_quantityproduct_variant_out_of_stock_webhook_mock.assert_called_once_with(- Stock.objects.first()+ Stock.objects.first(), requestor=staff_api_client.user)-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_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,@@ -172,14 +172,14 @@ def test_order_lines_create_for_variant_with_many_stocks_with_out_of_stock_webhopermission_group_manage_orders.user_set.add(staff_api_client.user)staff_api_client.post_graphql(query, variables)product_variant_out_of_stock_webhook_mock.assert_called_once_with(- Stock.objects.all()[3]+ Stock.objects.all()[3], requestor=staff_api_client.user)@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")@patch("saleor.plugins.manager.PluginsManager.order_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_order_lines_create(product_variant_out_of_stock_webhook_mock,order_updated_webhook_mock,@@ -327,7 +327,7 @@ def test_order_lines_create_by_app(@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")@patch("saleor.plugins.manager.PluginsManager.order_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_order_lines_create_for_just_published_product(product_variant_out_of_stock_webhook_mock,order_updated_webhook_mock,@@ -920,7 +920,7 @@ def test_order_lines_create_with_variant_not_assigned_to_channel(draft_order_update_webhook_mock.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])def test_order_lines_create_without_sku(product_variant_out_of_stock_webhook_mock,diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.pyindex 5050f8bb6f..91a2a975ca 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py@@ -4,8 +4,12 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....warehouse.error_codes import StockErrorCode+from ....warehouse.webhooks.stock_events import (+ trigger_product_variant_back_in_stock,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...core import ResolveInfo@@ -13,7 +17,7 @@ from ...core.context import ChannelContextfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.mutations import BaseMutationfrom ...core.types import BulkStockError, NonNullList-from ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_contextfrom ...warehouse.dataloaders import StocksByProductVariantIdLoaderfrom ...warehouse.types import Warehousefrom ..mutations.product.product_create import StockInput@@ -47,7 +51,6 @@ class ProductVariantStocksCreate(BaseMutation):@classmethod@traced_atomic_transaction()def perform_mutation(cls, _root, info: ResolveInfo, /, **data):- manager = get_plugin_manager_promise(info.context).get()errors: defaultdict[str, list[ValidationError]] = defaultdict(list)stocks = data["stocks"]variant = cls.get_node_or_error(@@ -62,9 +65,13 @@ class ProductVariantStocksCreate(BaseMutation):webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK)+ requestor = get_user_or_app_from_context(info.context)for stock in new_stocks:- cls.call_event(- manager.product_variant_back_in_stock, stock, webhooks=webhooks+ call_event(+ trigger_product_variant_back_in_stock,+ stock,+ webhooks=webhooks,+ requestor=requestor,)StocksByProductVariantIdLoader(info.context).clear(variant.id)diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.pyindex d73a5007f1..0e8b853cd7 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py@@ -2,10 +2,14 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....warehouse import models as warehouse_modelsfrom ....warehouse.management import delete_stocks+from ....warehouse.webhooks.stock_events import (+ trigger_product_variant_out_of_stock,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...core import ResolveInfo@@ -14,7 +18,7 @@ from ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.mutations import BaseMutationfrom ...core.types import NonNullList, StockErrorfrom ...core.validators import validate_one_of_args_is_in_mutation-from ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_contextfrom ...warehouse.dataloaders import StocksByProductVariantIdLoaderfrom ...warehouse.types import Warehousefrom ..types import ProductVariant@@ -52,8 +56,6 @@ class ProductVariantStocksDelete(BaseMutation):variant_id = data.get("variant_id")validate_one_of_args_is_in_mutation("sku", sku, "variant_id", variant_id)- manager = get_plugin_manager_promise(info.context).get()-if variant_id:variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)else:@@ -77,9 +79,13 @@ class ProductVariantStocksDelete(BaseMutation):webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK)+ requestor = get_user_or_app_from_context(info.context)for stock in stocks_to_delete:- cls.call_event(- manager.product_variant_out_of_stock, stock, webhooks=webhooks+ call_event(+ trigger_product_variant_out_of_stock,+ stock,+ webhooks=webhooks,+ requestor=requestor,)delete_stocks([stock.id for stock in stocks_to_delete])diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.pyindex 2dd09f5943..7a19d9333d 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py@@ -4,10 +4,16 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....warehouse import models as warehouse_modelsfrom ....warehouse.management import stock_bulk_update+from ....warehouse.webhooks.stock_events import (+ trigger_product_variant_back_in_stock,+ trigger_product_variant_out_of_stock,+ trigger_product_variant_stocks_updated,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...core import ResolveInfo@@ -15,7 +21,7 @@ from ...core.context import ChannelContextfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.types import BulkStockError, NonNullListfrom ...core.validators import validate_one_of_args_is_in_mutation-from ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_contextfrom ...warehouse.dataloaders import StocksByProductVariantIdLoaderfrom ...warehouse.types import Warehousefrom ..mutations.product.product_create import StockInput@@ -77,8 +83,8 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):warehouse_ids, "warehouse", only_type=Warehouse)- manager = get_plugin_manager_promise(info.context).get()- cls.update_or_create_variant_stocks(variant, stocks, warehouses, manager)+ requestor = get_user_or_app_from_context(info.context)+ cls.update_or_create_variant_stocks(variant, stocks, warehouses, requestor)StocksByProductVariantIdLoader(info.context).clear(variant.id)@@ -87,7 +93,9 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):@classmethod@traced_atomic_transaction()- def update_or_create_variant_stocks(cls, variant, stocks_data, warehouses, manager):+ def update_or_create_variant_stocks(+ cls, variant, stocks_data, warehouses, requestor+ ):stocks = []webhooks_stock_in = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK@@ -107,27 +115,30 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):<= 0< stock_data["quantity"]):- cls.call_event(- manager.product_variant_back_in_stock,+ call_event(+ trigger_product_variant_back_in_stock,stock,webhooks=webhooks_stock_in,+ requestor=requestor,)if stock_data["quantity"] <= 0 or (stock_data["quantity"] - stock.quantity_allocated <= 0):- cls.call_event(- manager.product_variant_out_of_stock,+ call_event(+ trigger_product_variant_out_of_stock,stock,webhooks=webhooks_stock_out,+ requestor=requestor,)stock.quantity = stock_data["quantity"]stocks.append(stock)- cls.call_event(- manager.product_variant_stocks_updated,+ call_event(+ trigger_product_variant_stocks_updated,stocks,webhooks=webhooks_stock_update,+ requestor=requestor,)stock_bulk_update(stocks, ["quantity"])diff --git a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py b/saleor/graphql/product/tests/benchmark/test_variant_stocks.pyindex f083da9dca..9830bb8703 100644--- a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py+++ b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py@@ -13,7 +13,10 @@ from ....tests.utils import get_graphql_content"saleor.graphql.product.bulk_mutations.""product_variant_stocks_create.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_create.trigger_product_variant_back_in_stock"+)def test_product_variants_stocks_create(product_variant_back_in_stock_webhook_mock,mocked_get_webhooks_for_event,@@ -84,7 +87,7 @@ def test_product_variants_stocks_create()assert product_variant_back_in_stock_webhook_mock.call_count == 2product_variant_back_in_stock_webhook_mock.assert_called_with(- Stock.objects.last(), webhooks=[any_webhook]+ Stock.objects.last(), webhooks=[any_webhook], requestor=staff_api_client.user)@@ -94,7 +97,10 @@ def test_product_variants_stocks_create("saleor.graphql.product.bulk_mutations.""product_variant_stocks_create.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_create.trigger_product_variant_back_in_stock"+)def test_product_variants_stocks_create_with_single_webhook_called(product_variant_back_in_stock_webhook_mock,mocked_get_webhooks_for_event,@@ -160,7 +166,7 @@ def test_product_variants_stocks_create_with_single_webhook_called(== stocks_count + len(stocks))product_variant_back_in_stock_webhook_mock.assert_called_with(- Stock.objects.last(), webhooks=[any_webhook]+ Stock.objects.last(), webhooks=[any_webhook], requestor=staff_api_client.user)@@ -297,7 +303,10 @@ PRODUCT_VARIANT_STOCKS_DELETE_MUTATION = """"saleor.graphql.product.bulk_mutations.""product_variant_stocks_delete.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_delete.trigger_product_variant_out_of_stock"+)def test_product_variants_stocks_delete_by_id(product_variant_out_of_stock_webhook_mock,mocked_get_webhooks_for_event,@@ -346,7 +355,7 @@ def test_product_variants_stocks_delete_by_id()assert stock_to_delete not in Stock.objects.all()product_variant_out_of_stock_webhook_mock.assert_called_once_with(- stock_to_delete, webhooks=[any_webhook]+ stock_to_delete, webhooks=[any_webhook], requestor=staff_api_client.user)@@ -356,7 +365,10 @@ def test_product_variants_stocks_delete_by_id("saleor.graphql.product.bulk_mutations.""product_variant_stocks_delete.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_delete.trigger_product_variant_out_of_stock"+)def test_product_variants_stocks_delete_by_sku(product_variant_out_of_stock_webhook_mock,mocked_get_webhooks_for_event,@@ -404,7 +416,7 @@ def test_product_variants_stocks_delete_by_sku()assert stock_to_delete not in Stock.objects.all()product_variant_out_of_stock_webhook_mock.assert_called_once_with(- stock_to_delete, webhooks=[any_webhook]+ stock_to_delete, webhooks=[any_webhook], requestor=staff_api_client.user)@@ -414,7 +426,10 @@ def test_product_variants_stocks_delete_by_sku("saleor.graphql.product.bulk_mutations.""product_variant_stocks_delete.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_delete.trigger_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,mocked_get_webhooks_for_event,diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.pyindex 6bdac516ee..f0427c1741 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py@@ -1,4 +1,4 @@-from unittest.mock import patch+from unittest.mock import ANY, patchimport grapheneimport pytest@@ -251,8 +251,14 @@ def test_update_or_create_variant_stocks(variant, warehouses):"saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_stocks_updated"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_back_in_stock"+)def test_update_or_create_variant_stocks_when_stock_out_of_quantity(back_in_stock_webhook_trigger,stocks_updated_webhook_trigger,@@ -283,9 +289,11 @@ def test_update_or_create_variant_stocks_when_stock_out_of_quantity(assert {stock.quantity for stock in variant.stocks.all()} == {data["quantity"] for data in stocks_data}- back_in_stock_webhook_trigger.assert_called_once_with(stock, webhooks=[any_webhook])+ back_in_stock_webhook_trigger.assert_called_once_with(+ stock, webhooks=[any_webhook], requestor=ANY+ )stocks_updated_webhook_trigger.assert_called_once_with(- [stock], webhooks=[any_webhook]+ [stock], webhooks=[any_webhook], requestor=ANY)assert variant.stocks.all()[0].quantity == 10@@ -312,9 +320,18 @@ def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):"saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_stocks_updated"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_back_in_stock"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_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,@@ -349,10 +366,10 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(stock = Stock.objects.all()[1]product_variant_back_in_stock_webhook.assert_called_once_with(- stock, webhooks=[any_webhook]+ stock, webhooks=[any_webhook], requestor=ANY)product_variant_stocks_updated_webhook.assert_called_once_with(- [stock], webhooks=[any_webhook]+ [stock], webhooks=[any_webhook], requestor=ANY)product_variant_stock_out_of_stock_webhook.assert_not_called()@@ -361,9 +378,18 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_stocks_updated"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_back_in_stock"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_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,@@ -400,11 +426,11 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(stock = Stock.objects.all()[1]product_variant_back_in_stock_webhook.assert_not_called()product_variant_stock_out_of_stock_webhook.assert_called_once_with(- stock, webhooks=[any_webhook]+ stock, webhooks=[any_webhook], requestor=ANY)assert product_variant_stocks_update_webhook.call_count == 1product_variant_stocks_update_webhook.assert_called_with(- [stock], webhooks=[any_webhook]+ [stock], webhooks=[any_webhook], requestor=ANY)@@ -412,9 +438,18 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_stocks_updated"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_back_in_stock"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_out_of_stock"+)def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,@@ -448,10 +483,10 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations()# thenproduct_variant_back_in_stock_webhook.assert_called_once_with(- stock, webhooks=[any_webhook]+ stock, webhooks=[any_webhook], requestor=ANY)product_variant_stocks_updated_webhook.assert_called_once_with(- [stock], webhooks=[any_webhook]+ [stock], webhooks=[any_webhook], requestor=ANY)product_variant_stock_out_of_stock_webhook.assert_not_called()@@ -460,9 +495,18 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_stocks_updated"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_back_in_stock"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_out_of_stock"+)def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,@@ -496,10 +540,10 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations()# thenproduct_variant_stock_out_of_stock_webhook.assert_called_once_with(- stock, webhooks=[any_webhook]+ stock, webhooks=[any_webhook], requestor=ANY)product_variant_stocks_updated_webhook.assert_called_once_with(- [stock], webhooks=[any_webhook]+ [stock], webhooks=[any_webhook], requestor=ANY)product_variant_back_in_stock_webhook.assert_not_called()@@ -508,9 +552,18 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")-@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_stocks_updated"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_product_variant_back_in_stock"+)+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_stocks_update.trigger_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,@@ -550,7 +603,7 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(assert product_variant_stocks_update_webhook.call_count == 1product_variant_stocks_update_webhook.assert_called_once_with(- list(variant.stocks.all()), webhooks=[any_webhook]+ list(variant.stocks.all()), webhooks=[any_webhook], requestor=ANY)product_variant_back_in_stock_webhook.assert_not_called()diff --git a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.pyindex b1e6760d62..cdeed55205 100644--- a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py+++ b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py@@ -5,10 +5,14 @@ from django.core.exceptions import ValidationErrorfrom django.db.models import F, Qfrom ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....warehouse import modelsfrom ....warehouse.error_codes import StockBulkUpdateErrorCodefrom ....warehouse.lock_objects import stock_qs_select_for_update+from ....warehouse.webhooks.stock_events import (+ trigger_product_variant_stocks_updated,+)from ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...core.doc_category import DOC_CATEGORY_PRODUCTS@@ -22,7 +26,7 @@ from ...core.types import ()from ...core.utils import WebhookEventInfofrom ...core.validators import validate_one_of_args_is_in_mutation-from ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_contextfrom ..types import Stock@@ -391,13 +395,16 @@ class StockBulkUpdate(BaseMutation):@classmethoddef post_save_actions(cls, info, instances):- manager = get_plugin_manager_promise(info.context).get()if instances:webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED)- cls.call_event(- manager.product_variant_stocks_updated, instances, webhooks=webhooks+ requestor = get_user_or_app_from_context(info.context)+ call_event(+ trigger_product_variant_stocks_updated,+ instances,+ webhooks=webhooks,+ requestor=requestor,)@classmethoddiff --git a/saleor/graphql/warehouse/mutations/warehouse_delete.py b/saleor/graphql/warehouse/mutations/warehouse_delete.pyindex a4ea3b3093..21e1f482ed 100644--- a/saleor/graphql/warehouse/mutations/warehouse_delete.py+++ b/saleor/graphql/warehouse/mutations/warehouse_delete.py@@ -1,12 +1,17 @@import graphenefrom ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....warehouse import models+from ....warehouse.webhooks.stock_events import (+ trigger_product_variant_out_of_stock,+)from ...core import ResolveInfofrom ...core.mutations import ModelDeleteMutationfrom ...core.types import WarehouseErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_contextfrom ..types import Warehouse@@ -24,7 +29,6 @@ class WarehouseDelete(ModelDeleteMutation):@classmethoddef perform_mutation(cls, _root, info: ResolveInfo, /, **data):- manager = get_plugin_manager_promise(info.context).get()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)@@ -54,8 +58,13 @@ class WarehouseDelete(ModelDeleteMutation):instance.is_object_deleted = Truecls.post_save_action(info, instance, None)+ requestor = get_user_or_app_from_context(info.context)for stock in stocks:- cls.call_event(manager.product_variant_out_of_stock, stock)+ call_event(+ trigger_product_variant_out_of_stock,+ stock,+ requestor=requestor,+ )return cls.success_response(instance)@classmethoddiff --git a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.pyindex 3d32b5cee3..47b9a1b224 100644--- a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py+++ b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py@@ -72,7 +72,7 @@ def test_stocks_bulk_update_queries_count(staff_api_client.ensure_access_token()# test number of queries when single object is updated- with django_assert_num_queries(13):+ with django_assert_num_queries(12):staff_api_client.user.user_permissions.add(permission_manage_products)response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, {"stocks": stocks_input}@@ -108,7 +108,7 @@ def test_stocks_bulk_update_queries_count(]# Test number of queries when multiple objects are updated- with django_assert_num_queries(13):+ with django_assert_num_queries(12):staff_api_client.user.user_permissions.add(permission_manage_products)response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, {"stocks": stocks_input}diff --git a/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.pyindex 29105dc562..e672ff8e60 100644--- a/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py+++ b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py@@ -79,7 +79,10 @@ def test_stocks_bulk_update_using_ids(@patch("saleor.graphql.warehouse.bulk_mutations.stock_bulk_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")+@patch(+ "saleor.graphql.warehouse.bulk_mutations.stock_bulk_update."+ "trigger_product_variant_stocks_updated"+)def test_stocks_bulk_update_send_stock_updated_event(product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,@@ -118,14 +121,17 @@ def test_stocks_bulk_update_send_stock_updated_event(assert not data["results"][0]["errors"]assert data["count"] == 1product_variant_stocks_update_webhook.assert_called_once_with(- [stock], webhooks=[any_webhook]+ [stock], webhooks=[any_webhook], requestor=staff_api_client.user)@patch("saleor.graphql.warehouse.bulk_mutations.stock_bulk_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")+@patch(+ "saleor.graphql.warehouse.bulk_mutations.stock_bulk_update."+ "trigger_product_variant_stocks_updated"+)def test_stocks_bulk_update_send_stock_updated_event_only_for_changed_stocks(product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,@@ -177,7 +183,7 @@ def test_stocks_bulk_update_send_stock_updated_event_only_for_changed_stocks(assert not data["results"][0]["errors"]assert data["count"] == 2product_variant_stocks_update_webhook.assert_called_once_with(- [modified_stock], webhooks=[any_webhook]+ [modified_stock], webhooks=[any_webhook], requestor=staff_api_client.user)diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.pyindex 710e69ace0..22808b7ec3 100644--- a/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py@@ -87,7 +87,10 @@ def test_delete_warehouse_mutation_trigger_webhook()-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.warehouse.mutations.warehouse_delete."+ "trigger_product_variant_out_of_stock"+)def test_delete_warehouse_mutation_with_webhooks(product_variant_out_of_stock_webhook,staff_api_client,@@ -114,10 +117,15 @@ def test_delete_warehouse_mutation_with_webhooks(assert len(errors) == 0assert Warehouse.objects.count() == 2assert Stock.objects.count() == 2- product_variant_out_of_stock_webhook.assert_called_once_with(old_first_stock)+ product_variant_out_of_stock_webhook.assert_called_once_with(+ old_first_stock, requestor=staff_api_client.user+ )-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch(+ "saleor.graphql.warehouse.mutations.warehouse_delete."+ "trigger_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,diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex ad382e838b..92959844df 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -432,7 +432,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_orders([order.id], manager)+ deallocate_stock_for_orders([order.id], app or user)order.status = OrderStatus.CANCELEDorder.save(update_fields=["status", "updated_at"])if not webhook_event_map:@@ -920,7 +920,7 @@ def approve_fulfillment(decrease_stock(lines_to_fulfill,- manager,+ app or user,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,)order.refresh_from_db()@@ -1072,7 +1072,7 @@ def _increase_order_line_quantity(order_lines_info):def fulfill_order_lines(order_lines_info: list["OrderLineInfo"],- manager: "PluginsManager",+ requestor: "App | User | None",allow_stock_to_be_exceeded: bool = False,):"""Fulfill order line with given quantity."""@@ -1081,7 +1081,7 @@ def fulfill_order_lines(with traced_atomic_transaction():decrease_stock(order_lines_info,- manager,+ requestor,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,)_increase_order_line_quantity(order_lines_info)@@ -1093,7 +1093,7 @@ def _create_fulfillment_lines(lines_data: list[OrderFulfillmentLineInfo],channel_slug: str,gift_card_lines_info: list[GiftCardLineData],- manager: "PluginsManager",+ requestor: "App | User | None",*,calculate_stocks_with_shipping_zones: bool,should_decrease_stock: bool = True,@@ -1116,7 +1116,7 @@ def _create_fulfillment_lines(channel_slug (str): Channel for which fulfillment lines should be created.gift_card_lines_info (List): List with information requiredto create gift cards.- manager (PluginsManager): Plugin manager from given context+ requestor (App | User | None): The entity making the request.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`.@@ -1203,7 +1203,7 @@ def _create_fulfillment_lines(if should_decrease_stock:decrease_stock(lines_info,- manager,+ requestor,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,)@@ -1303,7 +1303,7 @@ def create_fulfillments(fulfillment_lines_for_warehouses[warehouse_pk],order.channel.slug,gift_card_lines_info,- manager,+ app or user,should_decrease_stock=auto_approved,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,@@ -1376,7 +1376,7 @@ def _get_fulfillment_line(def _move_order_lines_to_target_fulfillment(order_lines_to_move: list[OrderLineInfo],target_fulfillment: Fulfillment,- manager: "PluginsManager",+ requestor: "App | User | None",) -> list[FulfillmentLine]:"""Move order lines with given quantity to the target fulfillment."""fulfillment_lines_to_create: list[FulfillmentLine] = []@@ -1415,7 +1415,7 @@ def _move_order_lines_to_target_fulfillment(if lines_to_dellocate:try:- deallocate_stock(lines_to_dellocate, manager)+ deallocate_stock(lines_to_dellocate, requestor)except AllocationError as e:lines = [str(line.pk) for line in e.order_lines]logger.warning(@@ -1540,7 +1540,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,+ requestor=app or user,)_move_fulfillment_lines_to_target_fulfillment(@@ -1671,7 +1671,7 @@ def _move_lines_to_return_fulfillment(order: "Order",total_refund_amount: Decimal | None,shipping_refund_amount: Decimal | None,- manager: "PluginsManager",+ requestor: "App | User | None",) -> Fulfillment:target_fulfillment = Fulfillment.objects.create(status=fulfillment_status,@@ -1682,7 +1682,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,+ requestor=requestor,)fulfillment_lines_already_refunded = FulfillmentLine.objects.filter(@@ -1727,7 +1727,7 @@ def _move_lines_to_replace_fulfillment(order_lines_to_replace: list[OrderLineInfo],fulfillment_lines_to_replace: list[FulfillmentLineData],order: "Order",- manager: "PluginsManager",+ requestor: "App | User | None",) -> Fulfillment:target_fulfillment = Fulfillment.objects.create(status=FulfillmentStatus.REPLACED, order=order@@ -1735,7 +1735,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,+ requestor=requestor,)_move_fulfillment_lines_to_target_fulfillment(fulfillment_lines_to_move=fulfillment_lines_to_replace,@@ -1753,7 +1753,6 @@ def create_return_fulfillment(fulfillment_lines: list[FulfillmentLineData],total_refund_amount: Decimal | None,shipping_refund_amount: Decimal | None,- manager: "PluginsManager",) -> Fulfillment:status = FulfillmentStatus.RETURNEDif total_refund_amount is not None:@@ -1766,7 +1765,7 @@ def create_return_fulfillment(order=order,total_refund_amount=total_refund_amount,shipping_refund_amount=shipping_refund_amount,- manager=manager,+ requestor=app or user,)returned_lines: dict[OrderLineIDType, tuple[QuantityType, OrderLine]] = {}order_lines_with_fulfillment = OrderLine.objects.in_bulk(@@ -1818,7 +1817,7 @@ def process_replace(order_lines_to_replace=order_lines,fulfillment_lines_to_replace=fulfillment_lines,order=order,- manager=manager,+ requestor=app or user,)new_order = create_replace_order(user=user,@@ -1918,7 +1917,6 @@ 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,diff --git a/saleor/order/tasks.py b/saleor/order/tasks.pyindex f2ee85cc5a..6b88b23ae8 100644--- a/saleor/order/tasks.py+++ b/saleor/order/tasks.py@@ -166,7 +166,7 @@ def _expire_orders(manager, now):)_bulk_release_voucher_usage(ids_batch)_order_expired_events(ids_batch)- deallocate_stock_for_orders(ids_batch, manager)+ deallocate_stock_for_orders(ids_batch, requestor=None)_call_expired_order_events(ids_batch, manager)diff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.pyindex 914d06cfdb..bca83d84d8 100644--- a/saleor/order/tests/fixtures/order.py+++ b/saleor/order/tests/fixtures/order.py@@ -1014,7 +1014,7 @@ def fulfilled_order(order_with_lines):line=line_2, quantity=line_2.quantity, warehouse_pk=warehouse_2_pk),],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)order.status = OrderStatus.FULFILLEDorder.save(update_fields=["status"])@@ -1041,7 +1041,7 @@ def fulfilled_order_without_inventory_tracking(fulfillment.lines.create(order_line=line, quantity=line.quantity, stock=stock)fulfill_order_lines([OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],- get_plugins_manager(allow_replica=False),+ requestor=None,)order.status = OrderStatus.FULFILLEDorder.save(update_fields=["status"])diff --git a/saleor/order/tests/test_fulfillments_actions.py b/saleor/order/tests/test_fulfillments_actions.pyindex 73c05fa6d4..6fa139fc69 100644--- a/saleor/order/tests/test_fulfillments_actions.py+++ b/saleor/order/tests/test_fulfillments_actions.py@@ -623,7 +623,7 @@ def test_create_fulfillments_with_variant_without_inventory_tracking_and_withoutmock_email_fulfillment.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_create_fullfilment_with_out_of_stock_webhook(product_variant_out_of_stock_webhook,staff_user,@@ -654,7 +654,7 @@ def test_create_fullfilment_with_out_of_stock_webhook(product_variant_out_of_stock_webhook.assert_called_once()-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+@patch("saleor.warehouse.webhooks.stock_events.trigger_product_variant_out_of_stock")def test_create_fullfilment_with_out_of_stock_webhook_not_triggered(product_variant_out_of_stock_webhook,staff_user,diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex f3652ed682..efad068331 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -1413,7 +1413,7 @@ def test_fulfill_order_lines(order_with_lines):warehouse_pk=stock.warehouse.pk,)],- get_plugins_manager(allow_replica=False),+ None,)stock.refresh_from_db()@@ -1452,7 +1452,7 @@ def test_fulfill_order_lines_multiple_lines(order_with_lines):warehouse_pk=stock_2.warehouse.pk,),],- get_plugins_manager(allow_replica=False),+ None,)stock_1.refresh_from_db()@@ -1476,7 +1476,7 @@ def test_fulfill_order_lines_with_variant_deleted(order_with_lines):fulfill_order_lines([OrderLineInfo(line=line, quantity=line.quantity)],- get_plugins_manager(allow_replica=False),+ None,)@@ -1501,7 +1501,7 @@ def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):warehouse_pk=stock.warehouse.pk,)],- get_plugins_manager(allow_replica=False),+ None,)stock.refresh_from_db()diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 91ef901b59..7054c0bd1d 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -230,7 +230,7 @@ def determine_order_status(def create_order_line(order,line_data,- manager,+ requestor,site_settings,allocate_stock=False,) -> OrderLine:@@ -337,7 +337,7 @@ def create_order_line()],channel,- manager=manager,+ requestor=requestor,calculate_stocks_with_shipping_zones=(site_settings.use_legacy_shipping_zone_stock_availability),@@ -400,7 +400,7 @@ def add_variant_to_order(return create_order_line(order,line_data,- manager,+ app or user,site_settings,allocate_stock,)@@ -530,7 +530,7 @@ def _update_allocations_for_line(old_quantity: int,new_quantity: int,channel: "Channel",- manager: "PluginsManager",+ requestor: "App | User | None",site_settings: "SiteSettings",):if old_quantity == new_quantity:@@ -546,12 +546,12 @@ def _update_allocations_for_line(increase_allocations([line_info],channel,- manager,+ requestor,calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,)else:line_info.quantity = old_quantity - new_quantity- decrease_allocations([line_info], manager)+ decrease_allocations([line_info], requestor)def change_order_line_quantity(@@ -573,8 +573,9 @@ def change_order_line_quantity(currency = channel.currency_codeif new_quantity:if allocate_stock:+ requestor = app or user_update_allocations_for_line(- line_info, old_quantity, new_quantity, channel, manager, site_settings+ line_info, old_quantity, new_quantity, channel, requestor, site_settings)line.quantity = new_quantitytotal_price_net_amount = line.quantity * line.unit_price_net_amount@@ -620,7 +621,7 @@ def change_order_line_quantity()else:- delete_order_line(line_info, manager)+ delete_order_line(line_info, app or user)quantity_diff = old_quantity - new_quantity@@ -647,10 +648,10 @@ def create_order_event(line, user, app, quantity_diff):)-def delete_order_line(line_info, manager):+def delete_order_line(line_info, requestor: "App | User | None"):"""Delete an order line from an order."""if line_info.line.order.is_unconfirmed():- decrease_allocations([line_info], manager)+ decrease_allocations([line_info], requestor)line_info.line.delete()diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 8cedf2862d..215c52cec9 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -64,7 +64,7 @@ if TYPE_CHECKING:from ..shipping.models import ShippingMethod, ShippingZonefrom ..site.models import SiteSettingsfrom ..tax.models import TaxClass- from ..warehouse.models import Stock, Warehouse+ from ..warehouse.models import WarehousePluginConfigurationType = list[dict]RequestorOrLazyObject = Union[SimpleLazyObject, "Requestor"]@@ -1347,33 +1347,6 @@ class BasePlugin:# Webhook-related functionality will be moved from the plugin to core modules.product_variant_metadata_updated: Callable[["ProductVariant", Any], Any]- # Trigger when product variant is out of stock.- #- # Overwrite this method if you need to trigger specific logic after a product- # variant is out of stock.- #- # Note: This method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from the plugin to core modules.- product_variant_out_of_stock: Callable[["Stock", None, None], Any]-- # Trigger when product variant is back in stock.- #- # Overwrite this method if you need to trigger specific logic after a product- # variant is back in stock.- #- # Note: This method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from the plugin to core modules.- product_variant_back_in_stock: Callable[["Stock", None, None], Any]-- # Trigger when product variant stock is updated.- #- # Overwrite this method if you need to trigger specific logic after a product- # variant stock is updated.- #- # Note: This method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from the plugin to core modules.- product_variant_stocks_updated: Callable[[list["Stock"], None, None], Any]-# Trigger when a product export is completed.## Overwrite this method if you need to trigger specific logic after a productdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex dbd627ba9f..c1469289ef 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -80,7 +80,7 @@ if TYPE_CHECKING:from ..site.models import SiteSettingsfrom ..tax.models import TaxClassfrom ..thumbnail.models import Thumbnail- from ..warehouse.models import Stock, Warehouse+ from ..warehouse.models import Warehousefrom .base_plugin import BasePluginNotifyEventTypeChoice = str@@ -890,42 +890,6 @@ class PluginsManager(PaymentInterface):channel_slug=None,)- # Note: this method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from plugin to core modules.- def product_variant_out_of_stock(self, stock: "Stock", webhooks=None):- default_value = None- self.__run_method_on_plugins(- "product_variant_out_of_stock",- default_value,- stock,- webhooks=webhooks,- channel_slug=None,- )-- # Note: this method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from plugin to core modules.- def product_variant_back_in_stock(self, stock: "Stock", webhooks=None):- default_value = None- self.__run_method_on_plugins(- "product_variant_back_in_stock",- default_value,- stock,- webhooks=webhooks,- channel_slug=None,- )-- # Note: this method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from plugin to core modules.- def product_variant_stocks_updated(self, stocks: list["Stock"], webhooks=None):- default_value = None- self.__run_method_on_plugins(- "product_variant_stocks_updated",- default_value,- stocks,- webhooks=webhooks,- channel_slug=None,- )-# Note: this method is deprecated and will be removed in a future release.# Webhook-related functionality will be moved from plugin to core modules.def product_variant_metadata_updated(self, product_variant: "ProductVariant"):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex a0738dedcb..bbd3fc4cd0 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -81,7 +81,6 @@ from ...webhook.payloads import (generate_product_media_payload,generate_product_payload,generate_product_variant_payload,- generate_product_variant_with_stock_payload,generate_requestor,generate_sale_payload,generate_sale_toggle_payload,@@ -150,7 +149,7 @@ if TYPE_CHECKING:from ...shipping.models import ShippingMethod, ShippingZonefrom ...site.models import SiteSettingsfrom ...tax.models import TaxClass- from ...warehouse.models import Stock, Warehouse+ from ...warehouse.models import Warehousefrom ...webhook.models import Webhook@@ -2025,73 +2024,6 @@ class WebhookPlugin(BasePlugin):)return previous_value- def product_variant_out_of_stock(- self, stock: "Stock", previous_value: None, webhooks=None- ) -> None:- if not self.active:- return previous_value- event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK- if webhooks := self._get_webhooks_for_event(event_type, webhooks):- product_variant_data_generator = partial(- generate_product_variant_with_stock_payload, [stock]- )- self.trigger_webhooks_async(- None,- event_type,- webhooks,- stock,- self.requestor,- legacy_data_generator=product_variant_data_generator,- )- return previous_value-- def product_variant_back_in_stock(- self, stock: "Stock", previous_value: None, webhooks=None- ) -> None:- if not self.active:- return previous_value- event_type = WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK- if webhooks := self._get_webhooks_for_event(event_type, webhooks):- product_variant_data_generator = partial(- generate_product_variant_with_stock_payload, [stock], self.requestor- )- self.trigger_webhooks_async(- None,- event_type,- webhooks,- stock,- self.requestor,- legacy_data_generator=product_variant_data_generator,- )- return previous_value-- def product_variant_stocks_updated(- self, stocks: list["Stock"], previous_value: None, webhooks=None- ) -> None:- if not self.active:- return previous_value- event_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED- if webhooks := self._get_webhooks_for_event(event_type, webhooks):- webhook_payload_details = []- for stock in stocks:- product_variant_data_generator = partial(- generate_product_variant_with_stock_payload, [stock], self.requestor- )- webhook_payload_details.append(- WebhookPayloadData(- subscribable_object=stock,- legacy_data_generator=product_variant_data_generator,- data=None,- )- )- trigger_webhooks_async_for_multiple_objects(- event_type,- webhooks,- webhook_payloads_data=webhook_payload_details,- requestor=self.requestor,- )- return previous_value-def checkout_created(self, checkout: "Checkout", previous_value: None, webhooks=None) -> None:diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex 376c9236b8..4d0273050a 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -52,7 +52,6 @@ from ....webhook.payloads import ()from ....webhook.transport import signature_for_payloadfrom ....webhook.transport.asynchronous.transport import (- WebhookPayloadData,send_webhook_request_async,trigger_webhooks_async,)@@ -843,106 +842,6 @@ def test_product_variant_metadata_updated()[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")-def test_product_variant_out_of_stock(- mocked_webhook_trigger,- mocked_get_webhooks_for_event,- any_webhook,- settings,- variant_with_many_stocks,-):- variant = variant_with_many_stocks.stocks.first()- mocked_get_webhooks_for_event.return_value = [any_webhook]- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- manager = get_plugins_manager(allow_replica=False)- manager.product_variant_out_of_stock(variant)-- mocked_webhook_trigger.assert_called_once_with(- None,- WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK,- [any_webhook],- variant,- None,- legacy_data_generator=ANY,- allow_replica=False,- )- assert callable(mocked_webhook_trigger.call_args.kwargs["legacy_data_generator"])- assert isinstance(- mocked_webhook_trigger.call_args.kwargs["legacy_data_generator"], partial- )--[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")-def test_product_variant_back_in_stock(- mocked_webhook_trigger,- mocked_get_webhooks_for_event,- any_webhook,- settings,- variant_with_many_stocks,-):- variant = variant_with_many_stocks.stocks.first()- mocked_get_webhooks_for_event.return_value = [any_webhook]- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- manager = get_plugins_manager(allow_replica=False)- manager.product_variant_back_in_stock(variant)-- mocked_webhook_trigger.assert_called_once_with(- None,- WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK,- [any_webhook],- variant,- None,- legacy_data_generator=ANY,- allow_replica=False,- )- assert callable(mocked_webhook_trigger.call_args.kwargs["legacy_data_generator"])- assert isinstance(- mocked_webhook_trigger.call_args.kwargs["legacy_data_generator"], partial- )---@freeze_time("2014-06-28 10:50")[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async_for_multiple_objects")-def test_product_variant_stocks_updated(- mocked_webhook_trigger_for_multiple_objects,- mocked_get_webhooks_for_event,- any_webhook,- settings,- variant_with_many_stocks,-):- stock = variant_with_many_stocks.stocks.first()- mocked_get_webhooks_for_event.return_value = [any_webhook]- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- manager = get_plugins_manager(allow_replica=False)- manager.product_variant_stocks_updated([stock])-- mocked_webhook_trigger_for_multiple_objects.assert_called_once_with(- WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED,- [any_webhook],- webhook_payloads_data=[- WebhookPayloadData(- subscribable_object=stock, legacy_data_generator=ANY, data=None- )- ],- requestor=None,- )-- assert callable(- mocked_webhook_trigger_for_multiple_objects.call_args.kwargs[- "webhook_payloads_data"- ][0].legacy_data_generator- )- assert isinstance(- mocked_webhook_trigger_for_multiple_objects.call_args.kwargs[- "webhook_payloads_data"- ][0].legacy_data_generator,- partial,- )--@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")def test_order_updated(diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 0b98e9a285..377b60c5d1 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -9,6 +9,8 @@ from django.db.models import F, Sumfrom django.db.models.expressions import Exists, OuterReffrom django.db.models.functions import Coalesce+from ..account.models import User+from ..app.models import Appfrom ..channel import AllocationStrategyfrom ..checkout.models import CheckoutLinefrom ..core.exceptions import (@@ -21,7 +23,6 @@ from ..core.tracing import traced_atomic_transactionfrom ..core.utils.country import get_active_countryfrom ..order.fetch import OrderLineInfofrom ..order.models import OrderLine-from ..plugins.manager import PluginsManagerfrom ..product.models import ProductVariant, ProductVariantChannelListingfrom .lock_objects import (allocation_with_stock_qs_select_for_update,@@ -37,11 +38,18 @@ from .models import (Stock,Warehouse,)+from .webhooks.stock_events import (+ trigger_product_variant_back_in_stock,+ trigger_product_variant_out_of_stock,+)if TYPE_CHECKING:from ..channel.models import Channel+T_REQUESTOR = App | User | None++class StockData(NamedTuple):pk: intquantity: int@@ -82,7 +90,7 @@ def allocate_stocks(order_lines_info: list["OrderLineInfo"],country_code: str,channel: "Channel",- manager: PluginsManager,+ requestor: T_REQUESTOR,*,calculate_stocks_with_shipping_zones: bool,collection_point_pk: UUID | None = None,@@ -203,7 +211,9 @@ def allocate_stocks()if not max(allocation.stock.quantity - allocated_stock, 0):transaction.on_commit(- lambda: manager.product_variant_out_of_stock(allocation.stock)+ lambda: trigger_product_variant_out_of_stock(+ allocation.stock, requestor=requestor+ ))@@ -323,7 +333,7 @@ def _create_allocations(return [], allocations-def deallocate_stock(order_lines_data: list["OrderLineInfo"], manager: PluginsManager):+def deallocate_stock(order_lines_data: list["OrderLineInfo"], requestor: T_REQUESTOR):"""Deallocate stocks for given `order_lines`.Function lock for update stocks and allocations related to given `order_lines`.@@ -386,8 +396,8 @@ def deallocate_stock(order_lines_data: list["OrderLineInfo"], manager: PluginsMaand available_stock_now > 0):transaction.on_commit(- lambda: manager.product_variant_back_in_stock(- allocation_before_update.stock+ lambda: trigger_product_variant_back_in_stock(+ allocation_before_update.stock, requestor=requestor))@@ -465,7 +475,7 @@ def _reduce_quantity_allocated_for_stocks(def increase_allocations(lines_info: list["OrderLineInfo"],channel: "Channel",- manager: PluginsManager,+ requestor: T_REQUESTOR,calculate_stocks_with_shipping_zones: bool,):"""Increase allocation for order lines with appropriate quantity."""@@ -503,18 +513,18 @@ def increase_allocations(lines_info,country_code,channel,- manager,+ requestor,calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,)-def decrease_allocations(lines_info: list["OrderLineInfo"], manager):+def decrease_allocations(lines_info: list["OrderLineInfo"], requestor: T_REQUESTOR):"""Decrease allocations for provided order lines."""lines_to_deallocate = get_order_lines_to_deallocate(lines_info)if not lines_to_deallocate:returntry:- deallocate_stock(lines_info, manager)+ deallocate_stock(lines_info, requestor)except AllocationError as exc:Allocation.objects.order_by("stock_id").filter(order_line__in=exc.order_lines@@ -524,7 +534,7 @@ def decrease_allocations(lines_info: list["OrderLineInfo"], manager):@traced_atomic_transaction()def decrease_stock(order_lines_info: list["OrderLineInfo"],- manager,+ requestor: T_REQUESTOR,allow_stock_to_be_exceeded: bool = False,):"""Decrease stocks quantities for given `order_lines` in given warehouses.@@ -536,7 +546,7 @@ def decrease_stock(function decrease it by given value.If allow_stock_to_be_exceeded flag is True then quantity could be < 0."""- decrease_allocations(order_lines_info, manager)+ decrease_allocations(order_lines_info, requestor)order_lines_info = get_order_lines_with_track_inventory(order_lines_info)if not order_lines_info:@@ -581,7 +591,9 @@ def decrease_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))+ transaction.on_commit(+ lambda: trigger_product_variant_out_of_stock(stock, requestor=requestor)+ )def _decrease_stocks_quantity(@@ -696,7 +708,7 @@ def get_order_lines_to_deallocate(@traced_atomic_transaction()-def deallocate_stock_for_orders(orders_ids: list[UUID], manager: PluginsManager):+def deallocate_stock_for_orders(orders_ids: list[UUID], requestor: T_REQUESTOR):"""Remove all allocations for given orders."""lines = OrderLine.objects.filter(order_id__in=orders_ids)allocations = allocation_with_stock_qs_select_for_update().filter(@@ -708,10 +720,13 @@ def deallocate_stock_for_orders(orders_ids: list[UUID], manager: PluginsManager)allocations_for_back_in_stock = Allocation.objects.filter(id__in=[allocation.id for allocation in allocations])+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)+ lambda: trigger_product_variant_back_in_stock(+ allocation.stock, requestor=requestor+ ))allocations.update(quantity_allocated=0)diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex 7a3ccac8ab..efd7a368a0 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -8,7 +8,6 @@ from ...channel import AllocationStrategyfrom ...core.exceptions import InsufficientStockfrom ...order.fetch import OrderLineInfofrom ...order.models import OrderLine-from ...plugins.manager import get_plugins_managerfrom ...warehouse.models import Stockfrom ..management import (allocate_preorders,@@ -35,7 +34,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):[line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -76,7 +75,7 @@ def test_allocate_stocks_multiple_lines_the_highest_stock_strategy([line_data_1, line_data_2],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -101,7 +100,7 @@ def test_allocate_stock_many_stocks_the_highest_stock_strategy([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -134,7 +133,7 @@ def test_allocate_stocks_the_highest_stock_strategy_with_collection_point([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,collection_point_pk=warehouse_for_cc.pk,)@@ -175,7 +174,7 @@ def test_allocate_stock_many_stocks_prioritize_sorting_order_strategy([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -237,7 +236,7 @@ def test_allocate_stock_prioritize_sorting_order_strategy_with_collection_point([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,collection_point_pk=warehouse_for_cc.pk,)@@ -263,7 +262,7 @@ def test_allocate_stock_with_reservations_the_highest_stock_strategy([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,check_reservations=True,)@@ -310,7 +309,7 @@ def test_allocate_stock_with_reservations_prioritize_sorting_order_strategy([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,check_reservations=True,)@@ -341,7 +340,7 @@ def test_allocate_stock_insufficient_stock_due_to_reservations([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,check_reservations=True,)@@ -371,7 +370,7 @@ def test_allocate_stock_many_stocks_partially_allocated([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -401,7 +400,7 @@ def test_allocate_stock_partially_allocated_insufficient_stocks([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -425,7 +424,7 @@ def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_US[line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -446,7 +445,7 @@ def test_allocate_stocks_no_channel_shipping_zones_excluded_from_stock_calculati[line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=False,)@@ -463,7 +462,7 @@ def test_allocate_stock_insufficient_stocks([line_data],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -502,7 +501,7 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines([line_data_1, line_data_2],COUNTRY_CODE,channel_USD,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -527,7 +526,7 @@ def test_deallocate_stock(allocation):line=allocation.order_line, quantity=80, variant=stock.product_variant)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -550,7 +549,7 @@ def test_deallocate_stock_when_quantity_less_than_zero(allocation):line=allocation.order_line, quantity=80, variant=stock.product_variant)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -573,7 +572,7 @@ def test_deallocate_stock_partially(allocation):line=allocation.order_line, quantity=50, variant=stock.product_variant)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -590,7 +589,7 @@ def test_deallocate_stock_many_allocations(deallocate_stock([OrderLineInfo(line=order_line, quantity=3, variant=order_line.variant)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)allocations = order_line.allocations.all()@@ -605,7 +604,7 @@ def test_deallocate_stock_many_allocations_partially(deallocate_stock([OrderLineInfo(line=order_line, quantity=1, variant=order_line.variant)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)allocations = order_line.allocations.all()@@ -681,7 +680,7 @@ def test_increase_allocations(quantity, allocation):increase_allocations([order_line_info],order_line.order.channel,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -746,7 +745,7 @@ def test_increase_allocations_with_multiple_allocations_for_the_same_stock(increase_allocations([first_order_line_info, second_order_line_info],first_order_line.order.channel,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -788,7 +787,7 @@ def test_increase_allocation_insufficient_stock(allocation):increase_allocations([order_line_info],order_line.order.channel,- manager=get_plugins_manager(allow_replica=False),+ requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -803,7 +802,9 @@ def test_increase_allocation_insufficient_stock(allocation):)[email protected]("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+ "saleor.warehouse.webhooks.stock_events.trigger_product_variant_back_in_stock"+)def test_increase_stock_with_back_in_stock_webhook_triggered_without_allocation(product_variant_back_in_stock_webhook,allocation,@@ -839,7 +840,7 @@ def test_decrease_stock(allocation):warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -868,7 +869,7 @@ def test_decrease_allocations(quantity, expected_allocated, allocation):warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -908,7 +909,7 @@ def test_decrease_stock_multiple_lines(allocations):warehouse_pk=warehouse_pk_2,),],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -972,7 +973,7 @@ def test_decrease_stock_multiple_lines_deallocate_stock_raises_error(order_with_warehouse_pk=warehouse_pk_2,),],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)# then@@ -1006,7 +1007,7 @@ def test_decrease_stock_partially(allocation):warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -1031,7 +1032,7 @@ def test_decrease_stock_many_allocations(warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)assert allocations[0].quantity_allocated == 0@@ -1056,7 +1057,7 @@ def test_decrease_stock_many_allocations_partially(warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)assert allocations[0].quantity_allocated == 0@@ -1085,7 +1086,7 @@ def test_decrease_stock_more_then_allocated(warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)allocations = order_line.allocations.all()@@ -1116,7 +1117,7 @@ def test_decrease_stock_insufficient_stock(allocation):warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)stock.refresh_from_db()@@ -1130,9 +1131,7 @@ 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_orders(- [order.id], manager=get_plugins_manager(allow_replica=False)- )+ deallocate_stock_for_orders([order.id], requestor=None)allocations = order_line.allocations.all()assert (@@ -1178,9 +1177,7 @@ def test_deallocate_stock_for_orders_with_multiple_allocations_from_the_same_stoassert first_allocation.stock_id == second_allocation.stock_id# when- deallocate_stock_for_orders(- [order.id], manager=get_plugins_manager(allow_replica=False)- )+ deallocate_stock_for_orders([order.id], requestor=None)# thenfirst_allocation.refresh_from_db()@@ -1192,7 +1189,9 @@ def test_deallocate_stock_for_orders_with_multiple_allocations_from_the_same_stoassert second_allocation.quantity_allocated == 0[email protected]("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+ "saleor.warehouse.webhooks.stock_events.trigger_product_variant_back_in_stock"+)def test_increase_stock_with_back_in_stock_webhook_not_triggered(product_variant_back_in_stock_webhook,allocation,@@ -1211,7 +1210,9 @@ def test_increase_stock_with_back_in_stock_webhook_not_triggered(product_variant_back_in_stock_webhook.assert_not_called()[email protected]("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")+ "saleor.warehouse.webhooks.stock_events.trigger_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,@@ -1230,7 +1231,7 @@ def test_increase_stock_with_back_in_stock_webhook_not_triggered_with_allocationproduct_variant_back_in_stock_webhook.assert_not_called()[email protected]("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")[email protected]("saleor.warehouse.management.trigger_product_variant_out_of_stock")def test_decrease_stock_with_out_of_stock_webhook_triggered(product_variant_out_of_stock_webhook_mock,allocation,@@ -1253,7 +1254,7 @@ def test_decrease_stock_with_out_of_stock_webhook_triggered(warehouse_pk=warehouse_pk,)],- manager=get_plugins_manager(allow_replica=False),+ requestor=None,)product_variant_out_of_stock_webhook_mock.assert_called_once()diff --git a/saleor/warehouse/tests/webhooks/__init__.py b/saleor/warehouse/tests/webhooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/warehouse/tests/webhooks/test_payloads.py b/saleor/warehouse/tests/webhooks/test_payloads.pynew file mode 100644index 0000000000..babf095142--- /dev/null+++ b/saleor/warehouse/tests/webhooks/test_payloads.py@@ -0,0 +1,60 @@+import json+from unittest.mock import ANY++import graphene++from .... import __version__+from ...webhooks.payloads import (+ generate_product_variant_with_stock_payload,+)+++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",+ "meta": {+ "issuing_principal": {"id": None, "type": None},+ "issued_at": ANY,+ "version": __version__,+ },+ },+ {+ "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",+ "meta": {+ "issuing_principal": {"id": None, "type": None},+ "issued_at": ANY,+ "version": __version__,+ },+ },+ ]+ assert payload == expected_payloaddiff --git a/saleor/warehouse/tests/webhooks/test_stock_events.py b/saleor/warehouse/tests/webhooks/test_stock_events.pynew file mode 100644index 0000000000..97b68e0882--- /dev/null+++ b/saleor/warehouse/tests/webhooks/test_stock_events.py@@ -0,0 +1,129 @@+from functools import partial+from unittest import mock++from saleor.warehouse.webhooks.stock_events import (+ trigger_product_variant_back_in_stock,+ trigger_product_variant_out_of_stock,+ trigger_product_variant_stocks_updated,+)+from saleor.webhook.event_types import WebhookEventAsyncType+from saleor.webhook.transport.asynchronous.transport import WebhookPayloadData++[email protected]("saleor.warehouse.webhooks.stock_events.trigger_webhooks_async")[email protected]("saleor.warehouse.webhooks.stock_events.get_webhooks_for_event")+def test_trigger_product_variant_out_of_stock_dispatches(+ mocked_get_webhooks, mocked_trigger, any_webhook, stock, staff_user+):+ # given+ mocked_get_webhooks.return_value = [any_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK++ # when+ trigger_product_variant_out_of_stock(stock, staff_user)++ # then+ mocked_get_webhooks.assert_called_once_with(event_type)+ mocked_trigger.assert_called_once()+ args, kwargs = mocked_trigger.call_args+ assert args[0] is None+ assert args[1] == event_type+ assert args[2] == [any_webhook]+ assert kwargs["subscribable_object"] == stock+ assert kwargs["requestor"] is staff_user+ assert isinstance(kwargs["legacy_data_generator"], partial)++[email protected]("saleor.warehouse.webhooks.stock_events.trigger_webhooks_async")[email protected]("saleor.warehouse.webhooks.stock_events.get_webhooks_for_event")+def test_trigger_product_variant_out_of_stock_no_webhooks_skips(+ mocked_get_webhooks, mocked_trigger, stock, staff_user+):+ # given+ mocked_get_webhooks.return_value = []++ # when+ trigger_product_variant_out_of_stock(stock, staff_user)++ # then+ mocked_trigger.assert_not_called()++[email protected]("saleor.warehouse.webhooks.stock_events.trigger_webhooks_async")[email protected]("saleor.warehouse.webhooks.stock_events.get_webhooks_for_event")+def test_trigger_product_variant_out_of_stock_uses_passed_webhooks(+ mocked_get_webhooks, mocked_trigger, any_webhook, stock, staff_user+):+ # when+ trigger_product_variant_out_of_stock(stock, staff_user, webhooks=[any_webhook])++ # then+ mocked_get_webhooks.assert_not_called()+ mocked_trigger.assert_called_once()+ assert mocked_trigger.call_args.args[2] == [any_webhook]++[email protected]("saleor.warehouse.webhooks.stock_events.trigger_webhooks_async")[email protected]("saleor.warehouse.webhooks.stock_events.get_webhooks_for_event")+def test_trigger_product_variant_back_in_stock_dispatches(+ mocked_get_webhooks, mocked_trigger, any_webhook, stock, app+):+ # given+ mocked_get_webhooks.return_value = [any_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK++ # when+ trigger_product_variant_back_in_stock(stock, app)++ # then+ mocked_trigger.assert_called_once()+ args, kwargs = mocked_trigger.call_args+ assert args[1] == event_type+ assert args[2] == [any_webhook]+ assert kwargs["subscribable_object"] == stock+ assert kwargs["requestor"] is app+ assert isinstance(kwargs["legacy_data_generator"], partial)+++ "saleor.warehouse.webhooks.stock_events.trigger_webhooks_async_for_multiple_objects"+)[email protected]("saleor.warehouse.webhooks.stock_events.get_webhooks_for_event")+def test_trigger_product_variant_stocks_updated_dispatches(+ mocked_get_webhooks, mocked_trigger, any_webhook, stock, app+):+ # given+ mocked_get_webhooks.return_value = [any_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED++ # when+ trigger_product_variant_stocks_updated([stock], app)++ # then+ mocked_trigger.assert_called_once()+ args, kwargs = mocked_trigger.call_args+ assert args[0] == event_type+ assert args[1] == [any_webhook]+ payloads = kwargs["webhook_payloads_data"]+ assert len(payloads) == 1+ assert isinstance(payloads[0], WebhookPayloadData)+ assert payloads[0].subscribable_object == stock+ assert isinstance(payloads[0].legacy_data_generator, partial)+ assert kwargs["requestor"] is app+++ "saleor.warehouse.webhooks.stock_events.trigger_webhooks_async_for_multiple_objects"+)[email protected]("saleor.warehouse.webhooks.stock_events.get_webhooks_for_event")+def test_trigger_product_variant_stocks_updated_no_webhooks_skips(+ mocked_get_webhooks, mocked_trigger, stock+):+ # given+ mocked_get_webhooks.return_value = []++ # when+ trigger_product_variant_stocks_updated([stock], None)++ # then+ mocked_trigger.assert_not_called()diff --git a/saleor/warehouse/webhooks/__init__.py b/saleor/warehouse/webhooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/warehouse/webhooks/payloads.py b/saleor/warehouse/webhooks/payloads.pynew file mode 100644index 0000000000..58cd6578fa--- /dev/null+++ b/saleor/warehouse/webhooks/payloads.py@@ -0,0 +1,35 @@+from collections.abc import Iterable+from typing import TYPE_CHECKING, Optional++import graphene++from ...core.db.connection import allow_writer+from ...webhook import traced_payload_generator+from ...webhook.payload_helpers import generate_meta, generate_requestor+from ...webhook.payload_serializers import PayloadSerializer++if TYPE_CHECKING:+ from ...plugins.base_plugin import RequestorOrLazyObject+ from ..models import Stock+++@allow_writer()+@traced_payload_generator+def generate_product_variant_with_stock_payload(+ stocks: Iterable["Stock"], requestor: Optional["RequestorOrLazyObject"] = None+):+ 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,+ "meta": generate_meta(requestor_data=generate_requestor(requestor)),+ }+ return serializer.serialize(stocks, fields=[], extra_dict_data=extra_dict_data)diff --git a/saleor/warehouse/webhooks/stock_events.py b/saleor/warehouse/webhooks/stock_events.pynew file mode 100644index 0000000000..707b001877--- /dev/null+++ b/saleor/warehouse/webhooks/stock_events.py@@ -0,0 +1,97 @@+from collections.abc import Iterable+from functools import partial+from typing import TYPE_CHECKING++from ...account.models import User+from ...app.models import App+from ...webhook.event_types import WebhookEventAsyncType+from ...webhook.transport.asynchronous.transport import (+ WebhookPayloadData,+ trigger_webhooks_async,+ trigger_webhooks_async_for_multiple_objects,+)+from ...webhook.utils import get_webhooks_for_event+from .payloads import generate_product_variant_with_stock_payload++if TYPE_CHECKING:+ from django.db.models import QuerySet++ from ...webhook.models import Webhook+ from ..models import Stock+++T_REQUESTOR = User | App | None+++def trigger_product_variant_out_of_stock(+ stock: "Stock",+ requestor: T_REQUESTOR,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK+ if webhooks is None:+ webhooks = get_webhooks_for_event(event_type)+ if not webhooks:+ return+ legacy_data_generator = partial(+ generate_product_variant_with_stock_payload, [stock], requestor+ )+ trigger_webhooks_async(+ None,+ event_type,+ webhooks,+ subscribable_object=stock,+ requestor=requestor,+ legacy_data_generator=legacy_data_generator,+ )+++def trigger_product_variant_back_in_stock(+ stock: "Stock",+ requestor: T_REQUESTOR,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK+ if webhooks is None:+ webhooks = get_webhooks_for_event(event_type)+ if not webhooks:+ return+ legacy_data_generator = partial(+ generate_product_variant_with_stock_payload, [stock], requestor+ )+ trigger_webhooks_async(+ None,+ event_type,+ webhooks,+ subscribable_object=stock,+ requestor=requestor,+ legacy_data_generator=legacy_data_generator,+ )+++def trigger_product_variant_stocks_updated(+ stocks: Iterable["Stock"],+ requestor: T_REQUESTOR,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED+ if webhooks is None:+ webhooks = get_webhooks_for_event(event_type)+ if not webhooks:+ return+ webhook_payloads_data = [+ WebhookPayloadData(+ subscribable_object=stock,+ legacy_data_generator=partial(+ generate_product_variant_with_stock_payload, [stock], requestor+ ),+ data=None,+ )+ for stock in stocks+ ]+ trigger_webhooks_async_for_multiple_objects(+ event_type,+ webhooks,+ webhook_payloads_data=webhook_payloads_data,+ requestor=requestor,+ )diff --git a/saleor/webhook/payload_helpers.py b/saleor/webhook/payload_helpers.pynew file mode 100644index 0000000000..8a16162a79--- /dev/null+++ b/saleor/webhook/payload_helpers.py@@ -0,0 +1,38 @@+from typing import TYPE_CHECKING, Any, Optional++import graphene+from django.utils import timezone+from graphene.utils.str_converters import to_camel_case++from .. import __version__+from ..account.models import User++if TYPE_CHECKING:+ from ..plugins.base_plugin import RequestorOrLazyObject+++def generate_requestor(requestor: Optional["RequestorOrLazyObject"] = None):+ if not requestor:+ return {"id": None, "type": None}+ if isinstance(requestor, User):+ return {"id": graphene.Node.to_global_id("User", requestor.id), "type": "user"}+ return {"id": requestor.name, "type": "app"} # type: ignore[union-attr]+++def generate_meta(*, requestor_data: dict[str, Any], camel_case=False, **kwargs):+ meta_result = {+ "issued_at": timezone.now().isoformat(),+ "version": __version__,+ "issuing_principal": requestor_data,+ }++ meta_result.update(kwargs)++ if camel_case:+ meta = {}+ for key, value in meta_result.items():+ meta[to_camel_case(key)] = value+ else:+ meta = meta_result++ return metadiff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex d6215437f7..af254fa453 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -9,10 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional, Unionimport graphenefrom django.contrib.sites.models import Sitefrom django.db.models import F, QuerySet, Sum-from django.utils import timezone-from graphene.utils.str_converters import to_camel_case-from .. import __version__from ..account.models import Userfrom ..attribute.models import AttributeValueTranslationfrom ..checkout import base_calculations@@ -39,9 +36,10 @@ from ..product.models import Collection, Product, ProductMedia, ProductVariantfrom ..shipping.models import ShippingMethodfrom ..tax.models import TaxClassCountryRatefrom ..thumbnail.models import Thumbnail-from ..warehouse.models import Stock, Warehouse+from ..warehouse.models import Warehousefrom . import traced_payload_generatorfrom .event_types import WebhookEventAsyncType+from .payload_helpers import generate_meta, generate_requestorfrom .payload_serializers import PayloadSerializerfrom .serializers import (serialize_checkout_lines,@@ -109,33 +107,6 @@ ORDER_PRICE_FIELDS = ()-def generate_requestor(requestor: Optional["RequestorOrLazyObject"] = None):- if not requestor:- return {"id": None, "type": None}- if isinstance(requestor, User):- return {"id": graphene.Node.to_global_id("User", requestor.id), "type": "user"}- return {"id": requestor.name, "type": "app"} # type: ignore[union-attr]---def generate_meta(*, requestor_data: dict[str, Any], camel_case=False, **kwargs):- meta_result = {- "issued_at": timezone.now().isoformat(),- "version": __version__,- "issuing_principal": requestor_data,- }-- meta_result.update(kwargs)-- if camel_case:- meta = {}- for key, value in meta_result.items():- meta[to_camel_case(key)] = value- else:- meta = meta_result-- return meta--@allow_writer()@traced_payload_generatordef generate_metadata_updated_payload(@@ -844,28 +815,6 @@ def generate_product_variant_media_payload(product_variant):]-@allow_writer()-@traced_payload_generator-def generate_product_variant_with_stock_payload(- stocks: Iterable["Stock"], requestor: Optional["RequestorOrLazyObject"] = None-):- 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,- "meta": generate_meta(requestor_data=generate_requestor(requestor)),- }- return serializer.serialize(stocks, fields=[], extra_dict_data=extra_dict_data)--@allow_writer()@traced_payload_generatordef generate_product_variant_payload(diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 85a9c1ffdb..09d91d7dec 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -51,7 +51,6 @@ from ..payloads import (generate_product_media_payload,generate_product_payload,generate_product_variant_payload,- generate_product_variant_with_stock_payload,generate_requestor,generate_sale_payload,generate_sale_toggle_payload,@@ -349,7 +348,7 @@ def test_generate_fulfillment_lines_payload(order_with_lines):)fulfill_order_lines([OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],- get_plugins_manager(allow_replica=False),+ requestor=None,)payload = json.loads(generate_fulfillment_lines_payload(fulfillment))[0]@@ -397,7 +396,7 @@ def test_generate_fulfillment_lines_payload_deleted_variant(order_with_lines):fulfillment.lines.create(order_line=line, quantity=line.quantity, stock=stock)fulfill_order_lines([OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],- get_plugins_manager(allow_replica=False),+ requestor=None,)# when@@ -651,57 +650,6 @@ def test_generate_collection_metadata_updated_payload(}-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",- "meta": {- "issuing_principal": {"id": None, "type": None},- "issued_at": ANY,- "version": __version__,- },- },- {- "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",- "meta": {- "issuing_principal": {"id": None, "type": None},- "issued_at": ANY,- "version": __version__,- },- },- ]- assert payload == expected_payload--@freeze_time()def test_generate_product_metadata_updated_payload(product_with_variant_with_two_attributes,diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 9832ae845b..9e12363fe8 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -33,7 +33,6 @@ from ....graphql.webhook.subscription_payload import (get_pre_save_payload_key,initialize_request,)-from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAPfrom ... import observabilityfrom ...event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ...observability import WebhookData@@ -107,6 +106,8 @@ def create_deliveries_for_multiple_subscription_objects(:return: List of event deliveries to send via webhook tasks.:param allow_replica: use replica database."""+ from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP+if event_type not in WEBHOOK_TYPES_MAP:logger.info("Skipping subscription webhook. Event %s is not subscribable.", event_type