Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add channel-scoped stock availability webhooks (#19144) (#19150)
Iga Karbowiaka876b8a7a799
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 096596a08c..2a7904eddd 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -836,6 +836,7 @@ def _create_order(order_lines_info,country_code,checkout_info.channel,+ site_settings,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,@@ -1265,6 +1266,7 @@ def _handle_allocations_of_order_lines(checkout_info: CheckoutInfo,checkout_lines: list[CheckoutLineInfo],order_lines_info: list[OrderLineInfo],+ site_settings: "SiteSettings",requestor: "App | User | None",reservation_enabled: bool,calculate_stocks_with_shipping_zones: bool,@@ -1277,6 +1279,7 @@ def _handle_allocations_of_order_lines(order_lines_info,country_code,checkout_info.channel,+ site_settings,requestor,calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,collection_point_pk=checkout_info.get_delivery_method_info().warehouse_pk,@@ -1512,6 +1515,7 @@ def _create_order_from_checkout(checkout_info=checkout_info,checkout_lines=checkout_lines_info,order_lines_info=order_lines_info,+ site_settings=site_settings,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/order/bulk_mutations/order_bulk_cancel.py b/saleor/graphql/order/bulk_mutations/order_bulk_cancel.pyindex e7aa430871..2644d6b509 100644--- a/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py+++ b/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py@@ -12,6 +12,7 @@ from ...core import ResolveInfofrom ...core.mutations import BaseBulkWithRestrictedChannelAccessMutationfrom ...core.types import NonNullList, OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ..mutations.order_cancel import clean_order_cancelfrom ..types import Order@@ -40,12 +41,14 @@ class OrderBulkCancel(BaseBulkWithRestrictedChannelAccessMutation):WEBHOOK_EVENTS_FOR_ORDER_CANCELED)manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()for order in queryset:cancel_order(order=order,user=info.context.user,app=get_app_promise(info.context).get(),manager=manager,+ site_settings=site.settings,webhook_event_map=webhook_event_map,)diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex a9a5348f26..e6da7869c1 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -215,6 +215,7 @@ class DraftOrderComplete(BaseMutation):[line_data],country,channel,+ site_settings,requestor,check_reservations=is_reservation_enabled(site_settingsdiff --git a/saleor/graphql/order/mutations/fulfillment_refund_products.py b/saleor/graphql/order/mutations/fulfillment_refund_products.pyindex f63f035a2c..499681e0fb 100644--- a/saleor/graphql/order/mutations/fulfillment_refund_products.py+++ b/saleor/graphql/order/mutations/fulfillment_refund_products.py@@ -14,6 +14,7 @@ from ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.scalars import PositiveDecimalfrom ...core.types import BaseInputObjectType, NonNullList, OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ..types import Fulfillment, Orderfrom .fulfillment_refund_and_return_product_base import (FulfillmentRefundAndReturnProductBase,@@ -143,6 +144,7 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):order = cleaned_input["order"]cls.check_channel_permissions(info, [order.channel_id])manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()try:app = get_app_promise(info.context).get()refund_fulfillment = create_refund_fulfillment(@@ -153,6 +155,7 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):cleaned_input.get("order_lines", []),cleaned_input.get("fulfillment_lines", []),manager,+ site.settings,cleaned_input["amount_to_refund"],cleaned_input["include_shipping_costs"],)diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.pyindex 600e74d6e7..b3b18ce45b 100644--- a/saleor/graphql/order/mutations/fulfillment_return_products.py+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py@@ -14,6 +14,7 @@ from ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.scalars import PositiveDecimalfrom ...core.types import BaseInputObjectType, NonNullList, OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ..types import Fulfillment, Orderfrom .fulfillment_refund_and_return_product_base import (FulfillmentRefundAndReturnProductBase,@@ -166,6 +167,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):order = cleaned_input["order"]cls.check_channel_permissions(info, [order.channel_id])manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()try:app = get_app_promise(info.context).get()response = create_fulfillments_for_returned_products(@@ -176,6 +178,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):cleaned_input.get("order_lines", []),cleaned_input.get("fulfillment_lines", []),manager,+ site.settings,cleaned_input["refund"],cleaned_input.get("amount_to_refund"),cleaned_input["include_shipping_costs"],diff --git a/saleor/graphql/order/mutations/order_cancel.py b/saleor/graphql/order/mutations/order_cancel.pyindex fb468d5f06..0429c12a50 100644--- a/saleor/graphql/order/mutations/order_cancel.py+++ b/saleor/graphql/order/mutations/order_cancel.py@@ -14,6 +14,7 @@ from ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ..types import Order@@ -53,12 +54,14 @@ class OrderCancel(BaseMutation):user = info.context.userapp = get_app_promise(info.context).get()manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()with traced_atomic_transaction():cancel_order(order=order,user=user,app=app,manager=manager,+ site_settings=site.settings,)deactivate_order_gift_cards(order.id, user, app)return OrderCancel(order=SyncWebhookControlContext(order))diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.pyindex 52ade39ebd..7b4e8b5bb3 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 ...site.dataloaders import get_site_promisefrom ...utils import get_user_or_app_from_contextfrom ..types import Order, OrderLinefrom .utils import EditableOrderValidationMixin, call_event_by_order_status@@ -47,6 +48,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):cls, _root, info: ResolveInfo, /, *, id):manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()requestor = get_user_or_app_from_context(info.context)line = cls.get_node_or_error(info,@@ -75,7 +77,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):variant=line.variant,warehouse_pk=warehouse_pk,)- delete_order_line(line_info, requestor)+ delete_order_line(line_info, site.settings, requestor)line.id = db_idupdated_fields = []diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.pyindex a3d26d9b76..ad10540b55 100644--- a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py@@ -241,6 +241,7 @@ def test_fulfillment_approve_gift_cards_created(permission_group_manage_orders,gift_card_shippable_order_line,gift_card_non_shippable_order_line,+ site_settings,):permission_group_manage_orders.user_set.add(staff_api_client.user)fulfillment = full_fulfillment_awaiting_approval@@ -269,6 +270,7 @@ def test_fulfillment_approve_gift_cards_created(warehouse_pk=stock_2.warehouse.pk,),],+ site_settings=site_settings,requestor=None,)diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.pyindex aee0b4bdb4..0ef2cebac9 100644--- a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py@@ -59,6 +59,7 @@ def test_order_bulk_cancel(user=staff_api_client.user,app=None,manager=ANY,+ site_settings=ANY,webhook_event_map=webhook_event_map,)for order in orders@@ -154,6 +155,7 @@ def test_order_bulk_cancel_as_app(user=None,app=app_api_client.app,manager=ANY,+ site_settings=ANY,webhook_event_map=webhook_event_map,)for order in orders@@ -205,6 +207,7 @@ def test_order_bulk_cancel_without_sku(user=staff_api_client.user,app=None,manager=ANY,+ site_settings=ANY,webhook_event_map=webhook_event_map,)for order in ordersdiff --git a/saleor/graphql/order/tests/mutations/test_order_cancel.py b/saleor/graphql/order/tests/mutations/test_order_cancel.pyindex 8442286ff1..0d80952a3b 100644--- a/saleor/graphql/order/tests/mutations/test_order_cancel.py+++ b/saleor/graphql/order/tests/mutations/test_order_cancel.py@@ -49,7 +49,11 @@ def test_order_cancel(mock_clean_order_cancel.assert_called_once_with(order)mock_cancel_order.assert_called_once_with(- order=order, user=staff_api_client.user, app=None, manager=ANY+ order=order,+ user=staff_api_client.user,+ app=None,+ manager=ANY,+ site_settings=ANY,)@@ -75,7 +79,11 @@ def test_order_cancel_as_app(mock_clean_order_cancel.assert_called_once_with(order)mock_cancel_order.assert_called_once_with(- order=order, user=None, app=app_api_client.app, manager=ANY+ order=order,+ user=None,+ app=app_api_client.app,+ manager=ANY,+ site_settings=ANY,)@@ -103,7 +111,11 @@ def test_order_cancel_with_bought_gift_cards(mock_clean_order_cancel.assert_called_once_with(order)mock_cancel_order.assert_called_once_with(- order=order, user=staff_api_client.user, app=None, manager=ANY+ order=order,+ user=staff_api_client.user,+ app=None,+ manager=ANY,+ site_settings=ANY,)gift_card.refresh_from_db()diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.pyindex 91a2a975ca..dd7324a610 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py@@ -6,6 +6,9 @@ from django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissions+from ....warehouse.channel_stock_availability import (+ trigger_back_in_stock_in_channel_events_for_stocks,+)from ....warehouse.error_codes import StockErrorCodefrom ....warehouse.webhooks.stock_events import (trigger_product_variant_back_in_stock,@@ -17,6 +20,7 @@ from ...core.context import ChannelContextfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.mutations import BaseMutationfrom ...core.types import BulkStockError, NonNullList+from ...site.dataloaders import get_site_promisefrom ...utils import get_user_or_app_from_contextfrom ...warehouse.dataloaders import StocksByProductVariantIdLoaderfrom ...warehouse.types import Warehouse@@ -74,6 +78,14 @@ class ProductVariantStocksCreate(BaseMutation):requestor=requestor,)+ site_settings = get_site_promise(info.context).get().settings+ if not site_settings.use_legacy_shipping_zone_stock_availability:+ call_event(+ trigger_back_in_stock_in_channel_events_for_stocks,+ new_stocks,+ site_settings,+ )+StocksByProductVariantIdLoader(info.context).clear(variant.id)variant = ChannelContext(node=variant, channel_slug=None)diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.pyindex 0e8b853cd7..87e6d78259 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py@@ -6,6 +6,9 @@ from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....warehouse import models as warehouse_models+from ....warehouse.channel_stock_availability import (+ trigger_out_of_stock_in_channel_events_for_stocks,+)from ....warehouse.management import delete_stocksfrom ....warehouse.webhooks.stock_events import (trigger_product_variant_out_of_stock,@@ -18,6 +21,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 ...site.dataloaders import get_site_promisefrom ...utils import get_user_or_app_from_contextfrom ...warehouse.dataloaders import StocksByProductVariantIdLoaderfrom ...warehouse.types import Warehouse@@ -79,15 +83,26 @@ class ProductVariantStocksDelete(BaseMutation):webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK)+ stocks_to_delete_list = list(stocks_to_delete)requestor = get_user_or_app_from_context(info.context)- for stock in stocks_to_delete:+ for stock in stocks_to_delete_list:call_event(trigger_product_variant_out_of_stock,stock,webhooks=webhooks,requestor=requestor,)- delete_stocks([stock.id for stock in stocks_to_delete])++ site_settings = get_site_promise(info.context).get().settings+ if not site_settings.use_legacy_shipping_zone_stock_availability:+ # Channel-event queries run on_commit after the deletion is applied,+ # but the in-memory stock objects are still safe to pass.+ call_event(+ trigger_out_of_stock_in_channel_events_for_stocks,+ stocks_to_delete_list,+ site_settings,+ )+ delete_stocks([stock.id for stock in stocks_to_delete_list])StocksByProductVariantIdLoader(info.context).clear(variant.id)diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.pyindex 7a19d9333d..a7f3ad0d2b 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py@@ -8,6 +8,10 @@ from ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....warehouse import models as warehouse_models+from ....warehouse.channel_stock_availability import (+ trigger_back_in_stock_in_channel_events_for_stocks,+ trigger_out_of_stock_in_channel_events_for_stocks,+)from ....warehouse.management import stock_bulk_updatefrom ....warehouse.webhooks.stock_events import (trigger_product_variant_back_in_stock,@@ -21,6 +25,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 ...site.dataloaders import get_site_promisefrom ...utils import get_user_or_app_from_contextfrom ...warehouse.dataloaders import StocksByProductVariantIdLoaderfrom ...warehouse.types import Warehouse@@ -83,8 +88,11 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):warehouse_ids, "warehouse", only_type=Warehouse)+ site_settings = get_site_promise(info.context).get().settingsrequestor = get_user_or_app_from_context(info.context)- cls.update_or_create_variant_stocks(variant, stocks, warehouses, requestor)+ cls.update_or_create_variant_stocks(+ variant, stocks, warehouses, site_settings, requestor+ )StocksByProductVariantIdLoader(info.context).clear(variant.id)@@ -94,9 +102,11 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):@classmethod@traced_atomic_transaction()def update_or_create_variant_stocks(- cls, variant, stocks_data, warehouses, requestor+ cls, variant, stocks_data, warehouses, site_settings, requestor):stocks = []+ back_in_stock_stocks: list[warehouse_models.Stock] = []+ out_of_stock_stocks: list[warehouse_models.Stock] = []webhooks_stock_in = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK)@@ -106,14 +116,18 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):webhooks_stock_update = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED)+ use_legacy_stock_availability = (+ site_settings.use_legacy_shipping_zone_stock_availability+ )for stock_data, warehouse in zip(stocks_data, warehouses, strict=False):stock, is_created = warehouse_models.Stock.objects.get_or_create(product_variant=variant, warehouse=warehouse)- if is_created or (- (stock.quantity - stock.quantity_allocated)- <= 0- < stock_data["quantity"]+ old_available = stock.quantity - stock.quantity_allocated+ new_available = stock_data["quantity"] - stock.quantity_allocated++ if (is_created and new_available > 0) or (+ old_available <= 0 < new_available):call_event(trigger_product_variant_back_in_stock,@@ -121,16 +135,16 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):webhooks=webhooks_stock_in,requestor=requestor,)+ back_in_stock_stocks.append(stock)- if stock_data["quantity"] <= 0 or (- stock_data["quantity"] - stock.quantity_allocated <= 0- ):+ if old_available > 0 >= new_available:call_event(trigger_product_variant_out_of_stock,stock,webhooks=webhooks_stock_out,requestor=requestor,)+ out_of_stock_stocks.append(stock)stock.quantity = stock_data["quantity"]stocks.append(stock)@@ -142,3 +156,17 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):)stock_bulk_update(stocks, ["quantity"])++ if not use_legacy_stock_availability:+ if back_in_stock_stocks:+ call_event(+ trigger_back_in_stock_in_channel_events_for_stocks,+ back_in_stock_stocks,+ site_settings,+ )+ if out_of_stock_stocks:+ call_event(+ trigger_out_of_stock_in_channel_events_for_stocks,+ out_of_stock_stocks,+ site_settings,+ )diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_create.pyindex b28a2adaae..39fb9494ce 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_create.py@@ -1,5 +1,8 @@+from unittest import mock+import graphene+from .....warehouse import WarehouseClickAndCollectOptionfrom .....warehouse.error_codes import StockErrorCodefrom .....warehouse.models import Stock, Warehousefrom ....tests.utils import get_graphql_content@@ -277,3 +280,159 @@ def test_invalidate_stocks_dataloader_on_create_stocks(# stocks are returned in the second mutation, after dataloader invalidationassert len(create_stocks_data["stocks"]) == len(warehouse_ids)+++ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_back_in_stock_in_channel"+)+def test_create_stocks_triggers_back_in_stock_in_channel_for_non_cc_warehouses(+ mocked_trigger,+ staff_api_client,+ variant,+ warehouses,+ channel_USD,+ site_settings,+ permission_manage_products,+):+ # given - creating stocks in two non-C&C warehouses+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ warehouses[0].channels.add(channel_USD)+ warehouses[1].channels.add(channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", warehouse.pk)+ for warehouse in warehouses+ ]+ variables = {+ "variantId": variant_id,+ "stocks": [+ {"warehouse": warehouse_ids[0], "quantity": 10},+ {"warehouse": warehouse_ids[1], "quantity": 5},+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_CREATE_MUTATION,+ variables=variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then - fires once per (variant, channel), dedup across the two warehouses+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant.id+ assert stock_infos[0].channel_slug == channel_USD.slug+++ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_back_in_stock_for_click_and_collect"+)+def test_create_stocks_triggers_back_in_stock_for_click_and_collect(+ mocked_trigger,+ staff_api_client,+ variant,+ channel_USD,+ address,+ site_settings,+ permission_manage_products,+):+ # given - creating stocks in two C&C warehouses+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ cc_warehouses = Warehouse.objects.bulk_create(+ [+ Warehouse(+ address=address.get_copy(),+ name="cc-1",+ slug="cc-1",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ ),+ Warehouse(+ address=address.get_copy(),+ name="cc-2",+ slug="cc-2",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ ),+ ]+ )+ for warehouse in cc_warehouses:+ warehouse.channels.add(channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", warehouse.pk)+ for warehouse in cc_warehouses+ ]+ variables = {+ "variantId": variant_id,+ "stocks": [+ {"warehouse": warehouse_ids[0], "quantity": 10},+ {"warehouse": warehouse_ids[1], "quantity": 5},+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_CREATE_MUTATION,+ variables=variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant.id+ assert stock_infos[0].channel_slug == channel_USD.slug+++ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_back_in_stock_in_channel"+)+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_back_in_stock_for_click_and_collect"+)+def test_create_stocks_skips_channel_events_when_legacy_flag_enabled(+ mocked_back_cc,+ mocked_back,+ staff_api_client,+ variant,+ warehouses,+ site_settings,+ permission_manage_products,+):+ # given - legacy flag is on; creating stocks in two warehouses+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", warehouse.pk)+ for warehouse in warehouses+ ]+ variables = {+ "variantId": variant_id,+ "stocks": [+ {"warehouse": warehouse_ids[0], "quantity": 10},+ {"warehouse": warehouse_ids[1], "quantity": 5},+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_CREATE_MUTATION,+ variables=variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_back.assert_not_called()+ mocked_back_cc.assert_not_called()diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_delete.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_delete.pyindex f448a03adb..6cfb0b0011 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_delete.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_delete.py@@ -1,6 +1,9 @@+from unittest import mock+import graphenefrom .....product.error_codes import ProductErrorCode+from .....warehouse import WarehouseClickAndCollectOptionfrom .....warehouse.models import Stock, Warehousefrom ....tests.utils import get_graphql_content@@ -181,3 +184,147 @@ def test_invalidate_stocks_dataloader_on_removing_stocks(# stocks are empty in the second mutationassert remove_stocks_data["stocks"] == []+++ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_in_channel"+)+def test_delete_stocks_triggers_out_of_stock_in_channel_for_non_cc_warehouses(+ mocked_trigger,+ staff_api_client,+ variant_with_many_stocks,+ channel_USD,+ site_settings,+ permission_manage_products,+):+ # given - `variant_with_many_stocks` has stocks in non-C&C warehouses+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = list(variant.stocks.all())+ for stock in stocks:+ stock.warehouse.channels.add(channel_USD)+ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", stock.warehouse_id) for stock in stocks+ ]+ variables = {"variantId": variant_id, "warehouseIds": warehouse_ids}++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_DELETE_MUTATION,+ variables=variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then - fires once per (variant, channel), dedup across warehouses+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant.id+ assert stock_infos[0].channel_slug == channel_USD.slug+++ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_for_click_and_collect"+)+def test_delete_stocks_triggers_out_of_stock_for_click_and_collect(+ mocked_trigger,+ staff_api_client,+ variant,+ channel_USD,+ address,+ site_settings,+ permission_manage_products,+):+ # given - two C&C warehouses with stocks+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ cc_warehouses = Warehouse.objects.bulk_create(+ [+ Warehouse(+ address=address.get_copy(),+ name="cc-1",+ slug="cc-1",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ ),+ Warehouse(+ address=address.get_copy(),+ name="cc-2",+ slug="cc-2",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ ),+ ]+ )+ for warehouse in cc_warehouses:+ warehouse.channels.add(channel_USD)+ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=cc_warehouses[0], quantity=10),+ Stock(product_variant=variant, warehouse=cc_warehouses[1], quantity=5),+ ]+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", warehouse.pk)+ for warehouse in cc_warehouses+ ]+ variables = {"variantId": variant_id, "warehouseIds": warehouse_ids}++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_DELETE_MUTATION,+ variables=variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant.id+ assert stock_infos[0].channel_slug == channel_USD.slug+++ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_in_channel"+)+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_for_click_and_collect"+)+def test_delete_stocks_skips_channel_events_when_legacy_flag_enabled(+ mocked_out_cc,+ mocked_out,+ staff_api_client,+ variant_with_many_stocks,+ site_settings,+ permission_manage_products,+):+ # given - legacy flag is on+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = list(variant.stocks.all())+ warehouse_ids = [+ graphene.Node.to_global_id("Warehouse", stock.warehouse_id) for stock in stocks+ ]+ variables = {"variantId": variant_id, "warehouseIds": warehouse_ids}++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_DELETE_MUTATION,+ variables=variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_out.assert_not_called()+ mocked_out_cc.assert_not_called()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 f0427c1741..ad83a41f0f 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@@ -5,7 +5,6 @@ import pytestfrom django.core.exceptions import ValidationErrorfrom django.db.models import Sum-from .....plugins.manager import get_plugins_managerfrom .....warehouse.error_codes import StockErrorCodefrom .....warehouse.models import Stock, Warehousefrom ....tests.utils import get_graphql_content@@ -222,7 +221,7 @@ def test_create_stocks_failed(product_with_single_variant, warehouse):create_stocks(variant, stocks_data, warehouses)-def test_update_or_create_variant_stocks(variant, warehouses):+def test_update_or_create_variant_stocks(variant, warehouses, site_settings):Stock.objects.create(product_variant=variant,warehouse=warehouses[0],@@ -234,7 +233,11 @@ def test_update_or_create_variant_stocks(variant, warehouses):]ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, get_plugins_manager(allow_replica=False)+ variant,+ stocks_data,+ warehouses,+ site_settings,+ None,)variant.refresh_from_db()@@ -267,6 +270,7 @@ def test_update_or_create_variant_stocks_when_stock_out_of_quantity(warehouses,any_webhook,settings,+ site_settings,django_capture_on_commit_callbacks,):# given@@ -281,7 +285,11 @@ def test_update_or_create_variant_stocks_when_stock_out_of_quantity(with django_capture_on_commit_callbacks(execute=True):ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, get_plugins_manager(allow_replica=False)+ variant,+ stocks_data,+ warehouses,+ site_settings,+ None,)variant.refresh_from_db()@@ -298,7 +306,9 @@ def test_update_or_create_variant_stocks_when_stock_out_of_quantity(assert variant.stocks.all()[0].quantity == 10-def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):+def test_update_or_create_variant_stocks_empty_stocks_data(+ variant, warehouses, site_settings+):Stock.objects.create(product_variant=variant,warehouse=warehouses[0],@@ -306,7 +316,7 @@ def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):)ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, [], warehouses, get_plugins_manager(allow_replica=False)+ variant, [], warehouses, site_settings, None)variant.refresh_from_db()@@ -338,6 +348,7 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(product_variant_stocks_updated_webhook,mocked_get_webhooks_for_event,settings,+ site_settings,variant,warehouses,any_webhook,@@ -351,7 +362,6 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success()mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- plugins = get_plugins_manager(allow_replica=False)stocks_data = [{"quantity": 10, "warehouse": "123"},]@@ -359,7 +369,7 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(with django_capture_on_commit_callbacks(execute=True):ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, plugins+ variant, stocks_data, warehouses, site_settings, None)assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10@@ -396,32 +406,35 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,settings,+ site_settings,variant,warehouses,any_webhook,django_capture_on_commit_callbacks,):+ # given — stocks currently have availability, update drops both to 0Stock.objects.bulk_create([- Stock(product_variant=variant, warehouse=warehouse)+ Stock(product_variant=variant, warehouse=warehouse, quantity=5)for warehouse in warehouses])mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- plugins = get_plugins_manager(allow_replica=False)stocks_data = [{"quantity": 0, "warehouse": "123"},]- assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0+ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10+ # whenwith django_capture_on_commit_callbacks(execute=True):ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, plugins+ variant, stocks_data, warehouses, site_settings, None)- assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0+ # then — updated stock transitioned from available (5) to out of stock (0)+ assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 5stock = Stock.objects.all()[1]product_variant_back_in_stock_webhook.assert_not_called()@@ -456,6 +469,7 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(product_variant_stocks_updated_webhook,mocked_get_webhooks_for_event,settings,+ site_settings,variant,warehouse,any_webhook,@@ -469,7 +483,6 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(# givenmocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- plugins = get_plugins_manager(allow_replica=False)stock.quantity_allocated = stock_quantitystock.save(update_fields=["quantity_allocated"])stocks_data = [@@ -479,7 +492,7 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(# whenwith django_capture_on_commit_callbacks(execute=True):ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, [warehouse], plugins+ variant, stocks_data, [warehouse], site_settings, None)# thenproduct_variant_back_in_stock_webhook.assert_called_once_with(@@ -513,6 +526,7 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(product_variant_stocks_updated_webhook,mocked_get_webhooks_for_event,settings,+ site_settings,variant,warehouse,any_webhook,@@ -526,7 +540,6 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(# givenmocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- plugins = get_plugins_manager(allow_replica=False)stock.quantity_allocated = stock_quantity - 1stock.save(update_fields=["quantity_allocated"])stocks_data = [@@ -536,7 +549,7 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(# whenwith django_capture_on_commit_callbacks(execute=True):ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, [warehouse], plugins+ variant, stocks_data, [warehouse], site_settings, None)# thenproduct_variant_stock_out_of_stock_webhook.assert_called_once_with(@@ -570,6 +583,7 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,settings,+ site_settings,variant,warehouses,any_webhook,@@ -585,8 +599,6 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- plugins = get_plugins_manager(allow_replica=False)-stocks_data = [{"quantity": 0, "warehouse": "123"},{"quantity": 2, "warehouse": "321"},@@ -595,7 +607,7 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10with django_capture_on_commit_callbacks(execute=True):ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, plugins+ variant, stocks_data, warehouses, site_settings, None)assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 2@@ -671,3 +683,213 @@ def test_invalidate_stocks_dataloader_on_update_stocks(# stock is updated in the second mutationassert update_stocks_data["stocks"][0]["quantity"] == new_quantity+++@patch(+ "saleor.graphql.product.bulk_mutations.product_variant_stocks_update"+ ".trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_update_stocks_triggers_back_in_stock_channel_events(+ mocked_trigger,+ staff_api_client,+ variant,+ warehouses,+ site_settings,+ permission_manage_products,+):+ # given - two stocks at 0; update sets both positive+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ stocks = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouses[0], quantity=0),+ Stock(product_variant=variant, warehouse=warehouses[1], quantity=0),+ ]+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {+ "variantId": variant_id,+ "stocks": [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[0].pk),+ "quantity": 10,+ },+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[1].pk),+ "quantity": 5,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_UPDATE_MUTATIONS,+ variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_trigger.assert_called_once()+ triggered_stocks, triggered_site_settings = mocked_trigger.call_args.args+ assert {stock.pk for stock in triggered_stocks} == {stock.pk for stock in stocks}+ assert triggered_site_settings == site_settings+++@patch(+ "saleor.graphql.product.bulk_mutations.product_variant_stocks_update"+ ".trigger_out_of_stock_in_channel_events_for_stocks"+)+def test_update_stocks_triggers_out_of_stock_channel_events(+ mocked_trigger,+ staff_api_client,+ variant,+ warehouses,+ site_settings,+ permission_manage_products,+):+ # given - two stocks with availability; update sets both to 0+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ stocks = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouses[0], quantity=10),+ Stock(product_variant=variant, warehouse=warehouses[1], quantity=5),+ ]+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {+ "variantId": variant_id,+ "stocks": [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[0].pk),+ "quantity": 0,+ },+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[1].pk),+ "quantity": 0,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_UPDATE_MUTATIONS,+ variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_trigger.assert_called_once()+ triggered_stocks, triggered_site_settings = mocked_trigger.call_args.args+ assert {stock.pk for stock in triggered_stocks} == {stock.pk for stock in stocks}+ assert triggered_site_settings == site_settings+++@patch(+ "saleor.graphql.product.bulk_mutations.product_variant_stocks_update"+ ".trigger_out_of_stock_in_channel_events_for_stocks"+)+@patch(+ "saleor.graphql.product.bulk_mutations.product_variant_stocks_update"+ ".trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_update_stocks_skips_channel_events_when_legacy_flag_enabled(+ mocked_back,+ mocked_out,+ staff_api_client,+ variant,+ warehouses,+ site_settings,+ permission_manage_products,+):+ # given - legacy flag is on; two stocks at 0 updated to positive+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouses[0], quantity=0),+ Stock(product_variant=variant, warehouse=warehouses[1], quantity=0),+ ]+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {+ "variantId": variant_id,+ "stocks": [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[0].pk),+ "quantity": 10,+ },+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[1].pk),+ "quantity": 5,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_UPDATE_MUTATIONS,+ variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_back.assert_not_called()+ mocked_out.assert_not_called()+++@patch(+ "saleor.graphql.product.bulk_mutations.product_variant_stocks_update"+ ".trigger_out_of_stock_in_channel_events_for_stocks"+)+@patch(+ "saleor.graphql.product.bulk_mutations.product_variant_stocks_update"+ ".trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_update_stocks_does_not_trigger_channel_events_when_quantity_remains(+ mocked_back,+ mocked_out,+ staff_api_client,+ variant,+ warehouses,+ site_settings,+ permission_manage_products,+):+ # given - two stocks with availability; update reduces but keeps positive+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouses[0], quantity=10),+ Stock(product_variant=variant, warehouse=warehouses[1], quantity=8),+ ]+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {+ "variantId": variant_id,+ "stocks": [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[0].pk),+ "quantity": 5,+ },+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouses[1].pk),+ "quantity": 3,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_STOCKS_UPDATE_MUTATIONS,+ variables,+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_back.assert_not_called()+ mocked_out.assert_not_called()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex dd8e3bbb67..aec7f450a0 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2051,6 +2051,34 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""A product variant stock is updated"""PRODUCT_VARIANT_STOCK_UPDATED++ """+ A product variant becomes out of stock across all non click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL++ """+ A product variant becomes available again across non click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL++ """+ A product variant becomes out of stock across all click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT++ """+ A product variant becomes available again across click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECTPRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED"""A new checkout is created."""@@ -2627,6 +2655,34 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""A product variant stock is updated"""PRODUCT_VARIANT_STOCK_UPDATED++ """+ A product variant becomes out of stock across all non click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL++ """+ A product variant becomes available again across non click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL++ """+ A product variant becomes out of stock across all click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT++ """+ A product variant becomes available again across click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.+ """+ PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECTPRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED"""A new checkout is created."""@@ -14147,6 +14203,10 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {PRODUCT_VARIANT_OUT_OF_STOCKPRODUCT_VARIANT_BACK_IN_STOCKPRODUCT_VARIANT_STOCK_UPDATED+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL+ PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL+ PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT+ PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECTPRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATEDCHECKOUT_CREATEDCHECKOUT_UPDATED@@ -33774,6 +33834,70 @@ type Subscription @doc(category: "Miscellaneous") {"""channels: [String!]): ProductVariantDiscountedPriceUpdated @doc(category: "Products")++ """+ Event sent when a product variant becomes out of stock across all non click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++ Added in Saleor 3.23.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ productVariantOutOfStockInChannel(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): ProductVariantOutOfStockInChannel @doc(category: "Products")++ """+ Event sent when a product variant becomes available again across non click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++ Added in Saleor 3.23.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ productVariantBackInStockInChannel(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): ProductVariantBackInStockInChannel @doc(category: "Products")++ """+ Event sent when a product variant becomes out of stock across all click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++ Added in Saleor 3.23.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ productVariantOutOfStockForClickAndCollect(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): ProductVariantOutOfStockForClickAndCollect @doc(category: "Products")++ """+ Event sent when a product variant becomes available again across click-and-collect warehouses in a channel.++ Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++ Added in Saleor 3.23.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ productVariantBackInStockForClickAndCollect(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): ProductVariantBackInStockForClickAndCollect @doc(category: "Products")}interface Event {@@ -34193,6 +34317,114 @@ type ProductVariantDiscountedPriceUpdated implements Event @doc(category: "ProdunewPrice: Money!}+"""+Event sent when a product variant becomes out of stock across all non click-and-collect warehouses in a channel.++Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++Added in Saleor 3.23.+"""+type ProductVariantOutOfStockInChannel implements Event @doc(category: "Products") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The product variant the event relates to."""+ productVariant: ProductVariant!++ """The channel the stock availability changed in."""+ channel: Channel!+}++"""+Event sent when a product variant becomes available again across non click-and-collect warehouses in a channel.++Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++Added in Saleor 3.23.+"""+type ProductVariantBackInStockInChannel implements Event @doc(category: "Products") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The product variant the event relates to."""+ productVariant: ProductVariant!++ """The channel the stock availability changed in."""+ channel: Channel!+}++"""+Event sent when a product variant becomes out of stock across all click-and-collect warehouses in a channel.++Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++Added in Saleor 3.23.+"""+type ProductVariantOutOfStockForClickAndCollect implements Event @doc(category: "Products") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The product variant the event relates to."""+ productVariant: ProductVariant!++ """The channel the stock availability changed in."""+ channel: Channel!+}++"""+Event sent when a product variant becomes available again across click-and-collect warehouses in a channel.++Note: Only triggered when the `useLegacyShippingZoneStockAvailability` shop setting is disabled.++Added in Saleor 3.23.+"""+type ProductVariantBackInStockForClickAndCollect implements Event @doc(category: "Products") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The product variant the event relates to."""+ productVariant: ProductVariant!++ """The channel the stock availability changed in."""+ channel: Channel!+}+enum DistanceUnitsEnum {MMCMdiff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex beafaa6c6a..224d3ce6e5 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -645,7 +645,9 @@ class StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader(context_key = "stocks_with_available_quantity_by_productvariant_and_channel"def batch_load(self, keys: Iterable[VariantIdChannelSlug]):- channel_slugs = list({channel_slug for _, channel_slug in keys})+ channel_slugs = list(+ {channel_slug for _, channel_slug in keys if channel_slug is not None}+ )def with_channels(channels):def with_warehouses(warehouses_by_channel):diff --git a/saleor/graphql/warehouse/mutations/warehouse_delete.py b/saleor/graphql/warehouse/mutations/warehouse_delete.pyindex 21e1f482ed..2e05a92b08 100644--- a/saleor/graphql/warehouse/mutations/warehouse_delete.py+++ b/saleor/graphql/warehouse/mutations/warehouse_delete.py@@ -4,6 +4,10 @@ from ....core.tracing import traced_atomic_transactionfrom ....core.utils.events import call_eventfrom ....permission.enums import ProductPermissionsfrom ....warehouse import models+from ....warehouse.channel_stock_availability import (+ get_source_warehouses_data,+ trigger_out_of_stock_in_channel_events_for_stocks,+)from ....warehouse.webhooks.stock_events import (trigger_product_variant_out_of_stock,)@@ -11,6 +15,7 @@ from ...core import ResolveInfofrom ...core.mutations import ModelDeleteMutationfrom ...core.types import WarehouseErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ...utils import get_user_or_app_from_contextfrom ..types import Warehouse@@ -36,11 +41,22 @@ class WarehouseDelete(ModelDeleteMutation):if instance:cls.clean_instance(info, instance)- stocks = (stock for stock in instance.stock_set.only("product_variant"))+ stocks = list(instance.stock_set.only("product_variant"))address_id = instance.address_idaddress = instance.addressdb_id = instance.id+ site_settings = get_site_promise(info.context).get().settings+ fire_stock_channel_events = bool(+ stocks and not site_settings.use_legacy_shipping_zone_stock_availability+ )+ # Snapshot source warehouse channel + C&C data while the warehouse still+ # exist.+ source_warehouses_data = (+ get_source_warehouses_data([instance.id])+ if fire_stock_channel_events+ else None+ )with traced_atomic_transaction():instance.delete()@@ -65,6 +81,14 @@ class WarehouseDelete(ModelDeleteMutation):stock,requestor=requestor,)++ if fire_stock_channel_events:+ call_event(+ trigger_out_of_stock_in_channel_events_for_stocks,+ stocks,+ site_settings,+ source_warehouses_data=source_warehouses_data,+ )return cls.success_response(instance)@classmethoddiff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.pyindex 22808b7ec3..dfdf560bbd 100644--- a/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py@@ -6,10 +6,16 @@ from django.utils.functional import SimpleLazyObjectfrom .....account.models import Addressfrom .....core.utils.json_serializer import CustomJsonEncoder+from .....warehouse import WarehouseClickAndCollectOptionfrom .....warehouse.models import Stock, Warehousefrom .....webhook.event_types import WebhookEventAsyncTypefrom ....tests.utils import get_graphql_content+OUT_OF_STOCK_IN_CHANNEL_PATH = (+ "saleor.graphql.warehouse.mutations.warehouse_delete"+ ".trigger_out_of_stock_in_channel_events_for_stocks"+)+MUTATION_DELETE_WAREHOUSE = """mutation deleteWarehouse($id: ID!) {deleteWarehouse(id: $id) {@@ -173,3 +179,175 @@ def test_delete_warehouse_deletes_associated_address(errors = content["data"]["deleteWarehouse"]["errors"]assert len(errors) == 0assert not Address.objects.exists()+++@patch(OUT_OF_STOCK_IN_CHANNEL_PATH)+def test_delete_warehouse_triggers_channel_out_of_stock_events(+ mocked_trigger,+ staff_api_client,+ warehouse,+ variant,+ channel_USD,+ site_settings,+ permission_manage_products,+):+ # given - warehouse is the only one in the channel+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ expected_stocks = list(warehouse.stock_set.all())+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # when+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then - channel-scoped trigger fired with the warehouse's stocks+ mocked_trigger.assert_called_once()+ passed_stocks, passed_site_settings = mocked_trigger.call_args.args+ assert {s.pk for s in passed_stocks} == {s.pk for s in expected_stocks}+ assert passed_site_settings == site_settings+++@patch(OUT_OF_STOCK_IN_CHANNEL_PATH)+def test_delete_warehouse_skips_channel_events_when_legacy_flag_enabled(+ mocked_trigger,+ staff_api_client,+ warehouse,+ variant,+ channel_USD,+ site_settings,+ permission_manage_products,+):+ # given - legacy flag is on+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=5)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # when+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_trigger.assert_not_called()+++@patch(OUT_OF_STOCK_IN_CHANNEL_PATH)+def test_delete_warehouse_skips_channel_events_when_no_stocks(+ mocked_trigger,+ staff_api_client,+ warehouse,+ site_settings,+ permission_manage_products,+):+ # given - warehouse has no stocks+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # when+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then+ mocked_trigger.assert_not_called()+++@patch(+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_in_channel"+)+def test_delete_warehouse_fires_out_of_stock_in_channel_per_variant(+ mocked_inner_trigger,+ staff_api_client,+ warehouse,+ variant,+ channel_USD,+ site_settings,+ permission_manage_products,+):+ # given - non-C&C warehouse is the only availability source in the channel+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ warehouse_stocks = list(warehouse.stock_set.all())+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # when+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then - one channel event per (variant, channel) pair+ expected_pairs = {+ (s.product_variant_id, channel_USD.slug) for s in warehouse_stocks+ }+ fired_pairs = {+ (info.variant_id, info.channel_slug)+ for call in mocked_inner_trigger.call_args_list+ for info in call.args[0]+ }+ assert fired_pairs == expected_pairs+++@patch(+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_in_channel"+)+def test_delete_warehouse_does_not_fire_channel_event_when_another_warehouse_covers(+ mocked_inner_trigger,+ staff_api_client,+ warehouse,+ channel_USD,+ address,+ site_settings,+ permission_manage_products,+):+ # given - another non-C&C warehouse in the same channel still has stock for+ # every variant held in the deleted warehouse+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ warehouse_stocks = list(warehouse.stock_set.all())+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.bulk_create(+ [+ Stock(+ product_variant_id=stock.product_variant_id,+ warehouse=other_warehouse,+ quantity=3,+ )+ for stock in warehouse_stocks+ ]+ )+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # when+ response = staff_api_client.post_graphql(+ MUTATION_DELETE_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_products],+ )+ get_graphql_content(response)++ # then - other warehouse covers every (variant, channel), no event fires+ mocked_inner_trigger.assert_not_called()diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex 6bd6491f5b..6d186af2e9 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -174,6 +174,30 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED: ("A product variant stock is updated"),+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL: (+ "A product variant becomes out of stock across all non click-and-collect "+ "warehouses in a channel. "+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled."+ ),+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL: (+ "A product variant becomes available again across non click-and-collect "+ "warehouses in a channel. "+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled."+ ),+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT: (+ "A product variant becomes out of stock across all click-and-collect "+ "warehouses in a channel. "+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled."+ ),+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT: (+ "A product variant becomes available again across click-and-collect "+ "warehouses in a channel. "+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled."+ ),WebhookEventAsyncType.PRODUCT_EXPORT_COMPLETED: "A product export is completed.",WebhookEventAsyncType.SHIPPING_PRICE_CREATED: "A new shipping price is created.",WebhookEventAsyncType.SHIPPING_PRICE_UPDATED: "A shipping price is updated.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex d17195fc02..b3153a9174 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -55,6 +55,7 @@ from ..core.descriptions import (ADDED_IN_320,ADDED_IN_321,ADDED_IN_322,+ ADDED_IN_323,DEPRECATED_IN_3X_EVENT,PREVIEW_FEATURE,)@@ -86,6 +87,7 @@ from ..warehouse.dataloaders import WarehouseByIdLoaderif TYPE_CHECKING:from ...channel.models import Channelfrom ...product.interface import VariantDiscountedPriceChange+ from ...warehouse.interface import VariantChannelStockInfoTRANSLATIONS_TYPES_MAP = {ProductTranslation: translation_types.ProductTranslation,@@ -1127,6 +1129,101 @@ class ProductVariantDiscountedPriceUpdated(SubscriptionObjectType):return Money(amount=price_info.new_price_amount, currency=price_info.currency)+class ProductVariantChannelStockBase(SubscriptionObjectType):+ product_variant = graphene.Field(+ "saleor.graphql.product.types.ProductVariant",+ description="The product variant the event relates to.",+ required=True,+ )+ channel = graphene.Field(+ "saleor.graphql.channel.types.Channel",+ description="The channel the stock availability changed in.",+ required=True,+ )++ class Meta:+ abstract = True++ @staticmethod+ def resolve_product_variant(+ root: tuple[str, "VariantChannelStockInfo"],+ info: ResolveInfo,+ ) -> Promise["ChannelContext"]:+ _, stock_info = root+ channel_slug = stock_info.channel_slug+ return (+ ProductVariantByIdLoader(info.context)+ .load(stock_info.variant_id)+ .then(+ lambda variant: ChannelContext(node=variant, channel_slug=channel_slug)+ )+ )++ @staticmethod+ def resolve_channel(+ root: tuple[str, "VariantChannelStockInfo"],+ info: ResolveInfo,+ ) -> Promise["Channel"]:+ _, stock_info = root+ return ChannelBySlugLoader(info.context).load(stock_info.channel_slug)+++class ProductVariantOutOfStockInChannel(ProductVariantChannelStockBase):+ class Meta:+ root_type = None+ enable_dry_run = False+ interfaces = (Event,)+ description = (+ "Event sent when a product variant becomes out of stock across all "+ "non click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_PRODUCTS+++class ProductVariantBackInStockInChannel(ProductVariantChannelStockBase):+ class Meta:+ root_type = None+ enable_dry_run = False+ interfaces = (Event,)+ description = (+ "Event sent when a product variant becomes available again across "+ "non click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_PRODUCTS+++class ProductVariantOutOfStockForClickAndCollect(ProductVariantChannelStockBase):+ class Meta:+ root_type = None+ enable_dry_run = False+ interfaces = (Event,)+ description = (+ "Event sent when a product variant becomes out of stock across all "+ "click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_PRODUCTS+++class ProductVariantBackInStockForClickAndCollect(ProductVariantChannelStockBase):+ class Meta:+ root_type = None+ enable_dry_run = False+ interfaces = (Event,)+ description = (+ "Event sent when a product variant becomes available again across "+ "click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_PRODUCTS++class ProductExportCompleted(SubscriptionObjectType):export = graphene.Field("saleor.graphql.csv.types.ExportFile",@@ -2914,6 +3011,54 @@ class Subscription(SubscriptionObjectType):channels=channels_argument,doc_category=DOC_CATEGORY_PRODUCTS,)+ product_variant_out_of_stock_in_channel = BaseField(+ ProductVariantOutOfStockInChannel,+ description=(+ "Event sent when a product variant becomes out of stock across all "+ "non click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_PRODUCTS,+ )+ product_variant_back_in_stock_in_channel = BaseField(+ ProductVariantBackInStockInChannel,+ description=(+ "Event sent when a product variant becomes available again across "+ "non click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_PRODUCTS,+ )+ product_variant_out_of_stock_for_click_and_collect = BaseField(+ ProductVariantOutOfStockForClickAndCollect,+ description=(+ "Event sent when a product variant becomes out of stock across all "+ "click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_PRODUCTS,+ )+ product_variant_back_in_stock_for_click_and_collect = BaseField(+ ProductVariantBackInStockForClickAndCollect,+ description=(+ "Event sent when a product variant becomes available again across "+ "click-and-collect warehouses in a channel."+ "\n\nNote: Only triggered when the `useLegacyShippingZoneStockAvailability` "+ "shop setting is disabled." + ADDED_IN_323 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_PRODUCTS,+ )class Meta:doc_category = DOC_CATEGORY_MISC@@ -3095,6 +3240,10 @@ ASYNC_WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK: ProductVariantBackInStock,WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED: ProductVariantStockUpdated,WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED: ProductVariantDiscountedPriceUpdated,+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL: ProductVariantOutOfStockInChannel,+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL: ProductVariantBackInStockInChannel,+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT: ProductVariantOutOfStockForClickAndCollect,+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT: ProductVariantBackInStockForClickAndCollect,WebhookEventAsyncType.PRODUCT_VARIANT_DELETED: ProductVariantDeleted,WebhookEventAsyncType.PRODUCT_VARIANT_METADATA_UPDATED: (ProductVariantMetadataUpdateddiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 92959844df..0ad3936737 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -423,6 +423,7 @@ def cancel_order(user: User | None,app: Optional["App"],manager: "PluginsManager",+ site_settings: "SiteSettings",webhook_event_map: dict[str, set["Webhook"]] | None = None,):"""Cancel order.@@ -432,7 +433,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], app or user)+ deallocate_stock_for_orders([order.id], site_settings, app or user)order.status = OrderStatus.CANCELEDorder.save(update_fields=["status", "updated_at"])if not webhook_event_map:@@ -920,6 +921,7 @@ def approve_fulfillment(decrease_stock(lines_to_fulfill,+ settings,app or user,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,)@@ -1072,6 +1074,7 @@ def _increase_order_line_quantity(order_lines_info):def fulfill_order_lines(order_lines_info: list["OrderLineInfo"],+ site_settings: "SiteSettings",requestor: "App | User | None",allow_stock_to_be_exceeded: bool = False,):@@ -1081,6 +1084,7 @@ def fulfill_order_lines(with traced_atomic_transaction():decrease_stock(order_lines_info,+ site_settings,requestor,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,)@@ -1093,6 +1097,7 @@ def _create_fulfillment_lines(lines_data: list[OrderFulfillmentLineInfo],channel_slug: str,gift_card_lines_info: list[GiftCardLineData],+ site_settings: "SiteSettings",requestor: "App | User | None",*,calculate_stocks_with_shipping_zones: bool,@@ -1116,6 +1121,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.+ site_settings (SiteSettings): Site settings 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.@@ -1203,6 +1209,7 @@ def _create_fulfillment_lines(if should_decrease_stock:decrease_stock(lines_info,+ site_settings,requestor,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,)@@ -1303,6 +1310,7 @@ def create_fulfillments(fulfillment_lines_for_warehouses[warehouse_pk],order.channel.slug,gift_card_lines_info,+ site_settings,app or user,should_decrease_stock=auto_approved,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,@@ -1376,6 +1384,7 @@ def _get_fulfillment_line(def _move_order_lines_to_target_fulfillment(order_lines_to_move: list[OrderLineInfo],target_fulfillment: Fulfillment,+ site_settings: "SiteSettings",requestor: "App | User | None",) -> list[FulfillmentLine]:"""Move order lines with given quantity to the target fulfillment."""@@ -1415,7 +1424,7 @@ def _move_order_lines_to_target_fulfillment(if lines_to_dellocate:try:- deallocate_stock(lines_to_dellocate, requestor)+ deallocate_stock(lines_to_dellocate, site_settings, requestor)except AllocationError as e:lines = [str(line.pk) for line in e.order_lines]logger.warning(@@ -1504,6 +1513,7 @@ def create_refund_fulfillment(order_lines_to_refund: list[OrderLineInfo],fulfillment_lines_to_refund: list[FulfillmentLineData],manager: "PluginsManager",+ site_settings: "SiteSettings",amount=None,refund_shipping_costs=False,):@@ -1540,6 +1550,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,+ site_settings=site_settings,requestor=app or user,)@@ -1671,6 +1682,7 @@ def _move_lines_to_return_fulfillment(order: "Order",total_refund_amount: Decimal | None,shipping_refund_amount: Decimal | None,+ site_settings: "SiteSettings",requestor: "App | User | None",) -> Fulfillment:target_fulfillment = Fulfillment.objects.create(@@ -1682,6 +1694,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,+ site_settings=site_settings,requestor=requestor,)@@ -1727,6 +1740,7 @@ def _move_lines_to_replace_fulfillment(order_lines_to_replace: list[OrderLineInfo],fulfillment_lines_to_replace: list[FulfillmentLineData],order: "Order",+ site_settings: "SiteSettings",requestor: "App | User | None",) -> Fulfillment:target_fulfillment = Fulfillment.objects.create(@@ -1735,6 +1749,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,+ site_settings=site_settings,requestor=requestor,)_move_fulfillment_lines_to_target_fulfillment(@@ -1753,6 +1768,7 @@ def create_return_fulfillment(fulfillment_lines: list[FulfillmentLineData],total_refund_amount: Decimal | None,shipping_refund_amount: Decimal | None,+ site_settings: "SiteSettings",) -> Fulfillment:status = FulfillmentStatus.RETURNEDif total_refund_amount is not None:@@ -1765,6 +1781,7 @@ def create_return_fulfillment(order=order,total_refund_amount=total_refund_amount,shipping_refund_amount=shipping_refund_amount,+ site_settings=site_settings,requestor=app or user,)returned_lines: dict[OrderLineIDType, tuple[QuantityType, OrderLine]] = {}@@ -1805,6 +1822,7 @@ def process_replace(order_lines: list[OrderLineInfo],fulfillment_lines: list[FulfillmentLineData],manager: "PluginsManager",+ site_settings: "SiteSettings",) -> tuple[Fulfillment, Optional["Order"]]:"""Create replace fulfillment and new draft order.@@ -1817,6 +1835,7 @@ def process_replace(order_lines_to_replace=order_lines,fulfillment_lines_to_replace=fulfillment_lines,order=order,+ site_settings=site_settings,requestor=app or user,)new_order = create_replace_order(@@ -1850,6 +1869,7 @@ def create_fulfillments_for_returned_products(order_lines: list[OrderLineInfo],fulfillment_lines: list[FulfillmentLineData],manager: "PluginsManager",+ site_settings: "SiteSettings",refund: bool = False,amount: Decimal | None = None,refund_shipping_costs=False,@@ -1908,6 +1928,7 @@ def create_fulfillments_for_returned_products(order_lines=replace_order_lines,fulfillment_lines=replace_fulfillment_lines,manager=manager,+ site_settings=site_settings,)return_fulfillment = create_return_fulfillment(user=user,@@ -1917,6 +1938,7 @@ def create_fulfillments_for_returned_products(fulfillment_lines=return_fulfillment_lines,total_refund_amount=total_refund_amount,shipping_refund_amount=shipping_refund_amount,+ site_settings=site_settings,)Fulfillment.objects.filter(order=order,diff --git a/saleor/order/tasks.py b/saleor/order/tasks.pyindex 6b88b23ae8..73d52eef01 100644--- a/saleor/order/tasks.py+++ b/saleor/order/tasks.py@@ -3,6 +3,7 @@ import loggingfrom collections import Counterfrom django.conf import settings+from django.contrib.sites.models import Sitefrom django.db.models import Exists, F, Func, OuterRef, Subquery, Valuefrom django.db.models.functions import Greatestfrom django.utils import timezone@@ -140,7 +141,7 @@ def _order_expired_events(order_ids):@allow_writer()-def _expire_orders(manager, now):+def _expire_orders(manager, now, site_settings):time_diff_func_in_minutes = (Func(Value("day"), now - OuterRef("created_at"), function="DATE_PART") * 24+ Func(Value("hour"), now - OuterRef("created_at"), function="DATE_PART") * 60@@ -166,7 +167,7 @@ def _expire_orders(manager, now):)_bulk_release_voucher_usage(ids_batch)_order_expired_events(ids_batch)- deallocate_stock_for_orders(ids_batch, requestor=None)+ deallocate_stock_for_orders(ids_batch, site_settings, requestor=None)_call_expired_order_events(ids_batch, manager)@@ -174,7 +175,8 @@ def _expire_orders(manager, now):def expire_orders_task():now = timezone.now()manager = get_plugins_manager(allow_replica=True)- _expire_orders(manager, now)+ site_settings = Site.objects.get_current().settings+ _expire_orders(manager, now, site_settings)@app.taskdiff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.pyindex bca83d84d8..85fe453235 100644--- a/saleor/order/tests/fixtures/order.py+++ b/saleor/order/tests/fixtures/order.py@@ -988,7 +988,7 @@ def order_events(order):@pytest.fixture-def fulfilled_order(order_with_lines):+def fulfilled_order(order_with_lines, site_settings):order = order_with_linesorder.invoices.create(url="http://www.example.com/invoice.pdf",@@ -1014,6 +1014,7 @@ def fulfilled_order(order_with_lines):line=line_2, quantity=line_2.quantity, warehouse_pk=warehouse_2_pk),],+ site_settings=site_settings,requestor=None,)order.status = OrderStatus.FULFILLED@@ -1032,6 +1033,7 @@ def unconfirmed_order_with_lines(order_with_lines):@pytest.fixturedef fulfilled_order_without_inventory_tracking(order_with_line_without_inventory_tracking,+ site_settings,):order = order_with_line_without_inventory_trackingfulfillment = order.fulfillments.create(tracking_number="123")@@ -1041,6 +1043,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)],+ site_settings=site_settings,requestor=None,)order.status = OrderStatus.FULFILLEDdiff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 2f9254f94f..a41c233a46 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -722,10 +722,12 @@ def test_order_weight_change_line_quantity(staff_user, lines_info, site_settingsassert order.weight == _calculate_order_weight_from_lines(order)-def test_order_weight_delete_line(lines_info):+def test_order_weight_delete_line(lines_info, site_settings):order = lines_info[0].line.orderline_info = lines_info[0]- delete_order_line(line_info, get_plugins_manager(allow_replica=False))+ delete_order_line(+ line_info, get_plugins_manager(allow_replica=False), site_settings+ )assert order.weight == _calculate_order_weight_from_lines(order)diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex fb9ec450aa..acd303beb4 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -590,6 +590,7 @@ def test_cancel_order(send_order_canceled_confirmation_mock,fulfilled_order_with_all_cancelled_fulfillments,django_capture_on_commit_callbacks,+ site_settings,):# givenorder = fulfilled_order_with_all_cancelled_fulfillments@@ -601,7 +602,7 @@ def test_cancel_order(# whenwith django_capture_on_commit_callbacks(execute=True):- cancel_order(order, None, None, manager)+ cancel_order(order, None, None, manager, site_settings)# thenorder_event = order.events.last()@@ -634,6 +635,7 @@ def test_cancel_order_dont_trigger_webhooks(order_with_lines,settings,django_capture_on_commit_callbacks,+ site_settings,):# givenplugins_manager = get_plugins_manager(False)@@ -657,7 +659,7 @@ def test_cancel_order_dont_trigger_webhooks(# whenwith django_capture_on_commit_callbacks(execute=True):- cancel_order(order, None, None, plugins_manager)+ cancel_order(order, None, None, plugins_manager, site_settings)# then# confirm that event delivery was generated for each async webhook.@@ -1396,7 +1398,7 @@ def test_order_charged_triggers_webhooks(assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT-def test_fulfill_order_lines(order_with_lines):+def test_fulfill_order_lines(order_with_lines, site_settings):order = order_with_linesline = order.lines.first()quantity_fulfilled_before = line.quantity_fulfilled@@ -1413,7 +1415,8 @@ def test_fulfill_order_lines(order_with_lines):warehouse_pk=stock.warehouse.pk,)],- None,+ site_settings=site_settings,+ requestor=None,)stock.refresh_from_db()@@ -1421,7 +1424,7 @@ def test_fulfill_order_lines(order_with_lines):assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity-def test_fulfill_order_lines_multiple_lines(order_with_lines):+def test_fulfill_order_lines_multiple_lines(order_with_lines, site_settings):order = order_with_lineslines = order.lines.all()@@ -1452,7 +1455,8 @@ def test_fulfill_order_lines_multiple_lines(order_with_lines):warehouse_pk=stock_2.warehouse.pk,),],- None,+ site_settings=site_settings,+ requestor=None,)stock_1.refresh_from_db()@@ -1468,7 +1472,7 @@ def test_fulfill_order_lines_multiple_lines(order_with_lines):)-def test_fulfill_order_lines_with_variant_deleted(order_with_lines):+def test_fulfill_order_lines_with_variant_deleted(order_with_lines, site_settings):line = order_with_lines.lines.first()line.variant.delete()@@ -1476,11 +1480,14 @@ def test_fulfill_order_lines_with_variant_deleted(order_with_lines):fulfill_order_lines([OrderLineInfo(line=line, quantity=line.quantity)],- None,+ site_settings=site_settings,+ requestor=None,)-def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):+def test_fulfill_order_lines_without_inventory_tracking(+ order_with_lines, site_settings+):order = order_with_linesline = order.lines.first()quantity_fulfilled_before = line.quantity_fulfilled@@ -1501,7 +1508,8 @@ def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):warehouse_pk=stock.warehouse.pk,)],- None,+ site_settings=site_settings,+ requestor=None,)stock.refresh_from_db()diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.pyindex e572f3c835..26a28febec 100644--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py@@ -23,6 +23,7 @@ def test_create_return_fulfillment_only_order_lines(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):order_with_lines.payments.add(payment_dummy_fully_charged)payment = order_with_lines.get_last_payment()@@ -49,6 +50,7 @@ def test_create_return_fulfillment_only_order_lines(],fulfillment_lines=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment, replaced_fulfillment, replace_order = response@@ -101,6 +103,7 @@ def test_create_return_fulfillment_only_order_lines_with_refund(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):order_with_lines.payments.add(payment_dummy_fully_charged)payment = order_with_lines.get_last_payment()@@ -128,6 +131,7 @@ def test_create_return_fulfillment_only_order_lines_with_refund(order_lines=order_lines_to_refund,fulfillment_lines=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,refund=True,)returned_fulfillment, replaced_fulfillment, replace_order = response@@ -181,6 +185,7 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):order_with_lines.payments.add(payment_dummy_fully_charged)payment = order_with_lines.get_last_payment()@@ -208,6 +213,7 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(order_lines=order_lines_to_refund,fulfillment_lines=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,refund=True,refund_shipping_costs=True,)@@ -267,6 +273,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):order_with_lines.payments.add(payment_dummy_fully_charged)payment = order_with_lines.get_last_payment()@@ -304,6 +311,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(order_lines=order_lines_data,fulfillment_lines=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment, replaced_fulfillment, replace_order = response@@ -402,6 +410,7 @@ def test_create_return_fulfillment_only_fulfillment_lines(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):fulfilled_order.payments.add(payment_dummy_fully_charged)payment = fulfilled_order.get_last_payment()@@ -421,6 +430,7 @@ def test_create_return_fulfillment_only_fulfillment_lines(for line in fulfillment_lines],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment, replaced_fulfillment, replace_order = response@@ -453,6 +463,7 @@ def test_create_return_fulfillment_only_fulfillment_lines_replace_order(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):fulfilled_order.payments.add(payment_dummy_fully_charged)payment = fulfilled_order.get_last_payment()@@ -479,6 +490,7 @@ def test_create_return_fulfillment_only_fulfillment_lines_replace_order(order_lines=[],fulfillment_lines=fulfillment_lines_to_return,manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment, replaced_fulfillment, replace_order = response@@ -567,6 +579,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(variant,warehouse,django_capture_on_commit_callbacks,+ site_settings,):fulfilled_order.payments.add(payment_dummy_fully_charged)payment = fulfilled_order.get_last_payment()@@ -626,6 +639,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(order_lines=[],fulfillment_lines=fulfillment_lines_to_process,manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,refund=True,)@@ -677,6 +691,7 @@ def test_create_return_fulfillment_only_order_lines_with_old_ids(payment_dummy_fully_charged,staff_user,django_capture_on_commit_callbacks,+ site_settings,):order_with_lines.payments.add(payment_dummy_fully_charged)payment = order_with_lines.get_last_payment()@@ -705,6 +720,7 @@ def test_create_return_fulfillment_only_order_lines_with_old_ids(],fulfillment_lines=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment, replaced_fulfillment, replace_order = responsediff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.pyindex 2b36291450..336d7bc902 100644--- a/saleor/order/tests/test_order_actions_refund_products.py+++ b/saleor/order/tests/test_order_actions_refund_products.py@@ -19,6 +19,7 @@ def test_create_refund_fulfillment_only_order_lines(order_with_lines,payment_dummy,django_capture_on_commit_callbacks,+ site_settings,):payment_dummy.captured_amount = payment_dummy.totalpayment_dummy.charge_status = ChargeStatus.FULLY_CHARGED@@ -48,6 +49,7 @@ def test_create_refund_fulfillment_only_order_lines(order_lines_to_refund=order_refund_lines,fulfillment_lines_to_refund=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment_lines = returned_fulfillemnt.lines.all()@@ -93,6 +95,7 @@ def test_create_refund_fulfillment_included_shipping_costs(order_with_lines,payment_dummy,django_capture_on_commit_callbacks,+ site_settings,):payment_dummy.captured_amount = payment_dummy.totalpayment_dummy.charge_status = ChargeStatus.FULLY_CHARGED@@ -118,6 +121,7 @@ def test_create_refund_fulfillment_included_shipping_costs(order_lines_to_refund=order_refund_lines,fulfillment_lines_to_refund=[],manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,refund_shipping_costs=True,)@@ -159,6 +163,7 @@ def test_create_refund_fulfillment_only_fulfillment_lines(fulfilled_order,payment_dummy,django_capture_on_commit_callbacks,+ site_settings,):payment_dummy.captured_amount = payment_dummy.totalpayment_dummy.charge_status = ChargeStatus.FULLY_CHARGED@@ -183,6 +188,7 @@ def test_create_refund_fulfillment_only_fulfillment_lines(order_lines_to_refund=[],fulfillment_lines_to_refund=fulfillment_refund_lines,manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,)returned_fulfillment_lines = returned_fulfillemnt.lines.all()@@ -220,6 +226,7 @@ def test_create_refund_fulfillment_custom_amount(fulfilled_order,payment_dummy,django_capture_on_commit_callbacks,+ site_settings,):payment_dummy.captured_amount = payment_dummy.totalpayment_dummy.charge_status = ChargeStatus.FULLY_CHARGED@@ -245,6 +252,7 @@ def test_create_refund_fulfillment_custom_amount(order_lines_to_refund=[],fulfillment_lines_to_refund=fulfillment_refund_lines,manager=get_plugins_manager(allow_replica=False),+ site_settings=site_settings,amount=amount,)diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 7054c0bd1d..a6516dc557 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -337,6 +337,7 @@ def create_order_line()],channel,+ site_settings=site_settings,requestor=requestor,calculate_stocks_with_shipping_zones=(site_settings.use_legacy_shipping_zone_stock_availability@@ -546,12 +547,13 @@ def _update_allocations_for_line(increase_allocations([line_info],channel,+ site_settings,requestor,calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,)else:line_info.quantity = old_quantity - new_quantity- decrease_allocations([line_info], requestor)+ decrease_allocations([line_info], site_settings, requestor)def change_order_line_quantity(@@ -621,7 +623,7 @@ def change_order_line_quantity()else:- delete_order_line(line_info, app or user)+ delete_order_line(line_info, site_settings, app or user)quantity_diff = old_quantity - new_quantity@@ -648,10 +650,12 @@ def create_order_event(line, user, app, quantity_diff):)-def delete_order_line(line_info, requestor: "App | User | None"):+def delete_order_line(+ line_info, site_settings: "SiteSettings", requestor: "App | User | None"+):"""Delete an order line from an order."""if line_info.line.order.is_unconfirmed():- decrease_allocations([line_info], requestor)+ decrease_allocations([line_info], site_settings, requestor)line_info.line.delete()diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 2d0c4aa2ae..749c419a93 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -120,7 +120,7 @@ from ...webhook.transport.utils import (get_meta_description_key,get_sqs_message_group_id,)-from ...webhook.utils import get_webhooks_for_event+from ...webhook.utils import filter_webhooks_for_channel, get_webhooks_for_eventfrom ..base_plugin import BasePluginif TYPE_CHECKING:@@ -776,17 +776,7 @@ class WebhookPlugin(BasePlugin):"""if webhooks is None:webhooks = get_webhooks_for_event(event_type)- filtered_webhooks = []- for webhook in webhooks:- if not webhook.subscription_query:- filtered_webhooks.append(webhook)- continue- filterable_channel_slugs = list(webhook.filterable_channel_slugs)- if not filterable_channel_slugs:- filtered_webhooks.append(webhook)- continue- if channel_slug in filterable_channel_slugs:- filtered_webhooks.append(webhook)+ filtered_webhooks = filter_webhooks_for_channel(webhooks, channel_slug)return filtered_webhooksdef order_created(diff --git a/saleor/warehouse/channel_stock_availability.py b/saleor/warehouse/channel_stock_availability.pynew file mode 100644index 0000000000..962bafbb4f--- /dev/null+++ b/saleor/warehouse/channel_stock_availability.py@@ -0,0 +1,379 @@+from collections import defaultdict+from dataclasses import dataclass+from typing import TYPE_CHECKING+from uuid import UUID++from django.db.models import Exists, OuterRef++from . import WarehouseClickAndCollectOption+from .interface import VariantChannelStockInfo+from .models import ChannelWarehouse, Stock, Warehouse+from .webhooks.channel_stock_events import (+ trigger_product_variant_back_in_stock_for_click_and_collect,+ trigger_product_variant_back_in_stock_in_channel,+ trigger_product_variant_out_of_stock_for_click_and_collect,+ trigger_product_variant_out_of_stock_in_channel,+)++if TYPE_CHECKING:+ from django.db.models import QuerySet++ from ..account.models import User+ from ..app.models import App+ from ..site.models import SiteSettings+ from ..webhook.models import Webhook+++CC_OPTIONS = [+ WarehouseClickAndCollectOption.LOCAL_STOCK,+ WarehouseClickAndCollectOption.ALL_WAREHOUSES,+]+++@dataclass(frozen=True)+class SourceWarehouseData:+ """Pre-delete data of a source warehouse's channel + C&C data.++ Required by `trigger_out_of_stock_in_channel_events_for_stocks` when the+ source warehouse will no longer be reachable at event-fire time (e.g.+ `WarehouseDelete`): the trigger normally queries `ChannelWarehouse` and+ `Warehouse.click_and_collect_option`, both of which cascade on delete.+ Capture the data before the delete and forward via `call_event`.+ """++ channels: list[tuple[int, str]]+ cc_option: str+++def trigger_out_of_stock_in_channel_events_for_stocks(+ stocks: list[Stock],+ site_settings: "SiteSettings",+ requestor: "User | App | None" = None,+ webhooks: "QuerySet[Webhook] | None" = None,+ source_warehouses_data: dict[UUID, SourceWarehouseData] | None = None,+) -> None:+ """Fire channel-scoped OUT_OF_STOCK events for each `stock`'s variant.++ For each channel where `stock`'s warehouse belongs, fires+ OUT_OF_STOCK_IN_CHANNEL (for regular warehouses) or+ OUT_OF_STOCK_FOR_CLICK_AND_COLLECT (for C&C warehouses) when no other+ warehouse of the same kind in that channel has remaining availability.++ Pass `source_warehouses_data` when the source warehouses (and their+ `ChannelWarehouse` rows) will no longer be reachable at event-fire time.+ """+ if not stocks:+ return++ cc_stocks, non_cc_stocks = _split_stocks_by_click_and_collect(+ stocks, source_warehouses_data+ )++ NON_CC_OPTIONS = [WarehouseClickAndCollectOption.DISABLED]+ stocks_trigger_cc_options = [+ (+ cc_stocks,+ trigger_product_variant_out_of_stock_for_click_and_collect,+ CC_OPTIONS,+ ),+ (+ non_cc_stocks,+ trigger_product_variant_out_of_stock_in_channel,+ NON_CC_OPTIONS,+ ),+ ]+ for grouped_stocks, trigger, cc_options in stocks_trigger_cc_options:+ if not grouped_stocks:+ continue++ stock_infos = [+ VariantChannelStockInfo(variant_id=variant_id, channel_slug=channel_slug)+ for variant_id, channel_slug in (+ _get_variant_channels_without_other_availability(+ grouped_stocks,+ cc_options,+ source_warehouses_data=source_warehouses_data,+ )+ )+ ]+ if not stock_infos:+ continue+ trigger(+ stock_infos,+ site_settings,+ requestor=requestor,+ webhooks=webhooks,+ )+++def trigger_back_in_stock_in_channel_events_for_stocks(+ stocks: list[Stock],+ site_settings: "SiteSettings",+ requestor: "User | App | None" = None,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ """Fire channel-scoped BACK_IN_STOCK events for each `stock`'s variant.++ For each channel where `stock`'s warehouse belongs, fires+ BACK_IN_STOCK_IN_CHANNEL (for regular warehouses) or+ BACK_IN_STOCK_FOR_CLICK_AND_COLLECT (for C&C warehouses) when no other+ warehouse of the same kind in that channel has availability — i.e. `stock`+ is the first one back.+ """+ if not stocks:+ return++ cc_stocks, non_cc_stocks = _split_stocks_by_click_and_collect(stocks)++ NON_CC_OPTIONS = [WarehouseClickAndCollectOption.DISABLED]+ stocks_trigger_cc_options = [+ (+ cc_stocks,+ trigger_product_variant_back_in_stock_for_click_and_collect,+ CC_OPTIONS,+ ),+ (+ non_cc_stocks,+ trigger_product_variant_back_in_stock_in_channel,+ NON_CC_OPTIONS,+ ),+ ]+ for grouped_stocks, trigger, cc_options in stocks_trigger_cc_options:+ if not grouped_stocks:+ continue++ stock_infos = [+ VariantChannelStockInfo(variant_id=variant_id, channel_slug=channel_slug)+ for variant_id, channel_slug in (+ _get_variant_channels_without_other_availability(+ grouped_stocks, cc_options+ )+ )+ ]+ if not stock_infos:+ continue+ trigger(+ stock_infos,+ site_settings,+ requestor=requestor,+ webhooks=webhooks,+ )+++def _split_stocks_by_click_and_collect(+ stocks: list[Stock],+ source_warehouses_data: dict[UUID, SourceWarehouseData] | None = None,+) -> tuple[list[Stock], list[Stock]]:+ """Partition stocks into (cc_stocks, non_cc_stocks) with a single DB query.++ Queries which warehouses among the stocks' warehouses are non-C&C+ (`click_and_collect_option=DISABLED`); everything else is treated as C&C.++ When `source_warehouses_data` is provided the split is resolved from+ the snapshot without querying — needed when source warehouses are already+ deleted.+ """+ if source_warehouses_data is not None:+ non_cc_warehouse_ids: set[UUID] = {+ warehouse_id+ for warehouse_id, warehouse_data in source_warehouses_data.items()+ if warehouse_data.cc_option == WarehouseClickAndCollectOption.DISABLED+ }+ else:+ warehouse_ids = {stock.warehouse_id for stock in stocks}+ non_cc_warehouse_ids = set(+ Warehouse.objects.filter(+ id__in=warehouse_ids,+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ ).values_list("id", flat=True)+ )++ cc_stocks: list[Stock] = []+ non_cc_stocks: list[Stock] = []+ for stock in stocks:+ if stock.warehouse_id in non_cc_warehouse_ids:+ non_cc_stocks.append(stock)+ else:+ cc_stocks.append(stock)+ return cc_stocks, non_cc_stocks+++def _get_variant_channels_without_other_availability(+ stocks: list[Stock],+ cc_options: list[str],+ source_warehouses_data: dict[UUID, SourceWarehouseData] | None = None,+) -> set[tuple[int, str]]:+ """Return (variant_id, channel_slug) pairs where the source stocks are the only availability.++ For each stock, inspects every channel its warehouse belongs to. A pair is+ included when no other warehouse of the same kind (C&C or non-C&C) in that+ channel has available quantity for the stock's variant. Deduplicated so that+ multiple stocks for the same variant produce only one entry per channel.++ When `source_warehouses_data` is provided, it is used for the source+ warehouses instead of querying `ChannelWarehouse` — needed when source+ warehouses are already deleted by the time this runs.+ """+ source_warehouse_ids = {stock.warehouse_id for stock in stocks}++ available_by_warehouse_and_variant = (+ _fetch_other_warehouses_availability_per_variant(+ stocks, cc_options, source_warehouses_data+ )+ )++ availability_warehouse_ids = {+ warehouse_id for warehouse_id, _ in available_by_warehouse_and_variant+ }+ if source_warehouses_data is not None:+ other_ids = availability_warehouse_ids - set(source_warehouses_data)+ warehouse_id_to_channels_map = {+ warehouse_id: snapshot.channels+ for warehouse_id, snapshot in source_warehouses_data.items()+ } | get_warehouse_to_channels_map(list(other_ids))+ else:+ warehouse_id_to_channels_map = get_warehouse_to_channels_map(+ list(availability_warehouse_ids | source_warehouse_ids)+ )++ channel_available_per_stock = _sum_channel_availability_per_stock(+ stocks, available_by_warehouse_and_variant, warehouse_id_to_channels_map+ )++ result: set[tuple[int, str]] = set()+ for stock in stocks:+ for channel_id, channel_slug in warehouse_id_to_channels_map.get(+ stock.warehouse_id, []+ ):+ if channel_available_per_stock.get((stock.id, channel_id), 0) == 0:+ result.add((stock.product_variant_id, channel_slug))++ return result+++def _fetch_other_warehouses_availability_per_variant(+ stocks: list[Stock],+ cc_options: list[str],+ source_warehouses_data: dict[UUID, SourceWarehouseData] | None = None,+) -> dict[tuple[UUID, int], int]:+ """Fetch available quantity per (warehouse_id, variant_id) excluding source stocks.++ Considers only warehouses of the matching C&C kind in channels that contain+ any source stock's warehouse. Source warehouses themselves are included in+ the scope because warehouse A may serve as "the other warehouse" for a stock+ in warehouse B. The source stock rows are excluded from the aggregation so+ the returned map represents availability from everywhere *except* the+ source stocks.++ When `source_warehouses_data` is provided, the source channel IDs are+ derived from the snapshot instead of from `ChannelWarehouse` — needed when+ source warehouses are already deleted.+ """+ stock_ids = [stock.id for stock in stocks]+ warehouse_ids = list({stock.warehouse_id for stock in stocks})+ variant_ids = list({stock.product_variant_id for stock in stocks})++ if source_warehouses_data is not None:+ source_channel_ids = {+ channel_id+ for snapshot in source_warehouses_data.values()+ for channel_id, _ in snapshot.channels+ }+ channel_warehouses = ChannelWarehouse.objects.filter(+ channel_id__in=source_channel_ids+ )+ else:+ source_channels = ChannelWarehouse.objects.filter(+ warehouse_id__in=warehouse_ids,+ channel_id=OuterRef("channel_id"),+ )+ channel_warehouses = ChannelWarehouse.objects.filter(Exists(source_channels))+ matching_warehouses = Warehouse.objects.filter(+ Exists(channel_warehouses.filter(warehouse_id=OuterRef("pk"))),+ click_and_collect_option__in=cc_options,+ )++ available_rows = (+ Stock.objects.filter(+ Exists(matching_warehouses.filter(pk=OuterRef("warehouse_id"))),+ product_variant_id__in=variant_ids,+ )+ .exclude(id__in=stock_ids)+ .annotate_available_quantity()+ .values_list("warehouse_id", "product_variant_id", "available_quantity")+ )++ available_by_warehouse_variant: dict[tuple[UUID, int], int] = defaultdict(int)+ for warehouse_id, variant_id, available_quantity in available_rows:+ available_by_warehouse_variant[(warehouse_id, variant_id)] += max(+ available_quantity, 0+ )+ return available_by_warehouse_variant+++def _sum_channel_availability_per_stock(+ stocks: list[Stock],+ available_by_warehouse_variant: dict[tuple[UUID, int], int],+ warehouse_id_to_channels_map: dict[UUID, list[tuple[int, str]]],+) -> dict[tuple[int, int], int]:+ """Sum available quantity per (stock_id, channel_id) from warehouses other than the stock's own.++ For each availability row, distributes its quantity across the channels its+ warehouse belongs to, attributing it to every stock of the same variant+ except the stock located in the same warehouse.+ """+ variant_id_to_stocks: dict[int, list[Stock]] = defaultdict(list)+ for stock in stocks:+ variant_id_to_stocks[stock.product_variant_id].append(stock)++ channel_available_per_stock: dict[tuple[int, int], int] = defaultdict(int)+ for (+ warehouse_id,+ variant_id,+ ), available_quantity in available_by_warehouse_variant.items():+ warehouse_channels = warehouse_id_to_channels_map.get(warehouse_id, [])+ for stock in variant_id_to_stocks.get(variant_id, []):+ if warehouse_id == stock.warehouse_id:+ continue+ for channel_id, _ in warehouse_channels:+ channel_available_per_stock[(stock.id, channel_id)] += (+ available_quantity+ )+ return channel_available_per_stock+++def get_warehouse_to_channels_map(+ warehouse_ids: list[UUID],+) -> dict[UUID, list[tuple[int, str]]]:+ """Return `{warehouse_id: [(channel_id, channel_slug), ...]}` for given warehouses."""+ warehouse_to_channels: dict[UUID, list[tuple[int, str]]] = defaultdict(list)+ for channel_id, channel_slug, warehouse_id in ChannelWarehouse.objects.filter(+ warehouse_id__in=warehouse_ids+ ).values_list("channel_id", "channel__slug", "warehouse_id"):+ warehouse_to_channels[warehouse_id].append((channel_id, channel_slug))+ return warehouse_to_channels+++def get_source_warehouses_data(+ warehouse_ids: list[UUID],+) -> dict[UUID, SourceWarehouseData]:+ """Capture `SourceWarehouseData` for each warehouse in a single round-trip.++ Call before a warehouse delete, then forward via+ `trigger_out_of_stock_in_channel_events_for_stocks(..., source_warehouses_data=...)`+ through `call_event` so the channel trigger can fire post-commit without+ hitting the deleted rows.+ """+ warehouse_to_channels = get_warehouse_to_channels_map(warehouse_ids)+ warehouse_cc_options = dict(+ Warehouse.objects.filter(id__in=warehouse_ids).values_list(+ "id", "click_and_collect_option"+ )+ )+ return {+ warehouse_id: SourceWarehouseData(+ channels=warehouse_to_channels.get(warehouse_id, []),+ cc_option=cc_option,+ )+ for warehouse_id, cc_option in warehouse_cc_options.items()+ }diff --git a/saleor/warehouse/interface.py b/saleor/warehouse/interface.pynew file mode 100644index 0000000000..5d01f98c59--- /dev/null+++ b/saleor/warehouse/interface.py@@ -0,0 +1,16 @@+from dataclasses import dataclass+++@dataclass+class VariantChannelStockInfo:+ variant_id: int+ channel_slug: str++ @property+ def pk(self) -> tuple[int, str]:+ """Required by deferred payload mechanism to group deliveries per object.++ Uses (variant_id, channel_slug) because the same variant can have+ separate stock-availability events per channel.+ """+ return (self.variant_id, self.channel_slug)diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 377b60c5d1..71ad543982 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -1,6 +1,7 @@import mathfrom collections import defaultdictfrom collections.abc import Iterable+from functools import partialfrom typing import TYPE_CHECKING, Any, NamedTuple, castfrom uuid import UUID@@ -45,6 +46,7 @@ from .webhooks.stock_events import (if TYPE_CHECKING:from ..channel.models import Channel+ from ..site.models import SiteSettingsT_REQUESTOR = App | User | None@@ -90,6 +92,7 @@ def allocate_stocks(order_lines_info: list["OrderLineInfo"],country_code: str,channel: "Channel",+ site_settings: "SiteSettings",requestor: T_REQUESTOR,*,calculate_stocks_with_shipping_zones: bool,@@ -107,6 +110,13 @@ def allocate_stocks(for order line, until allocated all required quantity for the order line.If there is less quantity in stocks then rise InsufficientStock exception."""+ # local import: channel_stock_availability transitively pulls in the+ # webhook transport + graphql subscription types, which would create a+ # circular import at `warehouse.management` top-level load time.+ from .channel_stock_availability import (+ trigger_out_of_stock_in_channel_events_for_stocks,+ )+# allocation only applied to order lines with variants with track inventory# set to Trueorder_lines_info = get_order_lines_with_track_inventory(order_lines_info)@@ -202,6 +212,10 @@ def allocate_stocks(Stock.objects.bulk_update(stocks_to_update_map.values(), ["quantity_allocated"])+ legacy_stock_availability = (+ site_settings.use_legacy_shipping_zone_stock_availability+ )+ out_of_stock_stocks: list[Stock] = []for allocation in allocations:allocated_stock = (Allocation.objects.filter(stock_id=allocation.stock_id).aggregate(@@ -215,6 +229,15 @@ def allocate_stocks(allocation.stock, requestor=requestor))+ out_of_stock_stocks.append(allocation.stock)+ if out_of_stock_stocks and not legacy_stock_availability:+ transaction.on_commit(+ partial(+ trigger_out_of_stock_in_channel_events_for_stocks,+ out_of_stock_stocks,+ site_settings,+ )+ )def _prepare_stock_to_reserved_quantity_map(@@ -333,7 +356,11 @@ def _create_allocations(return [], allocations-def deallocate_stock(order_lines_data: list["OrderLineInfo"], requestor: T_REQUESTOR):+def deallocate_stock(+ order_lines_data: list["OrderLineInfo"],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR,+):"""Deallocate stocks for given `order_lines`.Function lock for update stocks and allocations related to given `order_lines`.@@ -342,6 +369,11 @@ def deallocate_stock(order_lines_data: list["OrderLineInfo"], requestor: T_REQUEquantity for the order line. If there is less quantity in stocks thenraise an exception."""+ # local import: to be removed when all webhook logic will be moved outside plugin+ from .channel_stock_availability import (+ trigger_back_in_stock_in_channel_events_for_stocks,+ )+lines = [line_info.line for line_info in order_lines_data]lines_allocations = allocation_with_stock_qs_select_for_update().filter(order_line__in=lines@@ -387,6 +419,10 @@ def deallocate_stock(order_lines_data: list["OrderLineInfo"], requestor: T_REQUEAllocation.objects.bulk_update(allocations_to_update, ["quantity_allocated"])+ legacy_stock_availability = (+ site_settings.use_legacy_shipping_zone_stock_availability+ )+ back_in_stock_stocks: list[Stock] = []for allocation_before_update in allocations_before_update:available_stock_now = Allocation.objects.available_quantity_for_stock(allocation_before_update.stock@@ -400,6 +436,15 @@ def deallocate_stock(order_lines_data: list["OrderLineInfo"], requestor: T_REQUEallocation_before_update.stock, requestor=requestor))+ back_in_stock_stocks.append(allocation_before_update.stock)+ if back_in_stock_stocks and not legacy_stock_availability:+ transaction.on_commit(+ partial(+ trigger_back_in_stock_in_channel_events_for_stocks,+ back_in_stock_stocks,+ site_settings,+ )+ )Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])@@ -475,6 +520,7 @@ def _reduce_quantity_allocated_for_stocks(def increase_allocations(lines_info: list["OrderLineInfo"],channel: "Channel",+ site_settings: "SiteSettings",requestor: T_REQUESTOR,calculate_stocks_with_shipping_zones: bool,):@@ -513,18 +559,23 @@ def increase_allocations(lines_info,country_code,channel,+ site_settings,requestor,calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,)-def decrease_allocations(lines_info: list["OrderLineInfo"], requestor: T_REQUESTOR):+def decrease_allocations(+ lines_info: list["OrderLineInfo"],+ site_settings: "SiteSettings",+ 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, requestor)+ deallocate_stock(lines_info, site_settings, requestor)except AllocationError as exc:Allocation.objects.order_by("stock_id").filter(order_line__in=exc.order_lines@@ -534,6 +585,7 @@ def decrease_allocations(lines_info: list["OrderLineInfo"], requestor: T_REQUEST@traced_atomic_transaction()def decrease_stock(order_lines_info: list["OrderLineInfo"],+ site_settings: "SiteSettings",requestor: T_REQUESTOR,allow_stock_to_be_exceeded: bool = False,):@@ -546,7 +598,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, requestor)+ decrease_allocations(order_lines_info, site_settings, requestor)order_lines_info = get_order_lines_with_track_inventory(order_lines_info)if not order_lines_info:@@ -708,8 +760,17 @@ def get_order_lines_to_deallocate(@traced_atomic_transaction()-def deallocate_stock_for_orders(orders_ids: list[UUID], requestor: T_REQUESTOR):+def deallocate_stock_for_orders(+ orders_ids: list[UUID],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR,+):"""Remove all allocations for given orders."""+ # local import: to be removed when all webhook logic will be moved outside plugin+ from .channel_stock_availability import (+ trigger_back_in_stock_in_channel_events_for_stocks,+ )+lines = OrderLine.objects.filter(order_id__in=orders_ids)allocations = allocation_with_stock_qs_select_for_update().filter(Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0@@ -721,6 +782,10 @@ def deallocate_stock_for_orders(orders_ids: list[UUID], requestor: T_REQUESTOR):id__in=[allocation.id for allocation in allocations])+ legacy_stock_availability = (+ site_settings.use_legacy_shipping_zone_stock_availability+ )+ back_in_stock_stocks: list[Stock] = []for allocation in allocations_for_back_in_stock.annotate_stock_available_quantity():if allocation.stock_available_quantity <= 0:transaction.on_commit(@@ -728,6 +793,15 @@ def deallocate_stock_for_orders(orders_ids: list[UUID], requestor: T_REQUESTOR):allocation.stock, requestor=requestor))+ back_in_stock_stocks.append(allocation.stock)+ if back_in_stock_stocks and not legacy_stock_availability:+ transaction.on_commit(+ partial(+ trigger_back_in_stock_in_channel_events_for_stocks,+ back_in_stock_stocks,+ site_settings,+ )+ )allocations.update(quantity_allocated=0)Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])diff --git a/saleor/warehouse/tests/test_channel_stock_availability.py b/saleor/warehouse/tests/test_channel_stock_availability.pynew file mode 100644index 0000000000..445c48f279--- /dev/null+++ b/saleor/warehouse/tests/test_channel_stock_availability.py@@ -0,0 +1,1050 @@+from .. import WarehouseClickAndCollectOption+from ..channel_stock_availability import (+ trigger_back_in_stock_in_channel_events_for_stocks,+ trigger_out_of_stock_in_channel_events_for_stocks,+)+from ..interface import VariantChannelStockInfo+from ..models import Allocation, Stock, Warehouse++OUT_IN_CHANNEL = (+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_in_channel"+)+BACK_IN_CHANNEL = (+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_back_in_stock_in_channel"+)+OUT_CC = (+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_out_of_stock_for_click_and_collect"+)+BACK_CC = (+ "saleor.warehouse.channel_stock_availability"+ ".trigger_product_variant_back_in_stock_for_click_and_collect"+)+++def test_out_of_stock_fires_when_only_warehouse_in_bucket(+ variant, warehouse, channel_USD, site_settings, mocker+):+ # given - single non-C&C warehouse in the channel, stock just hit 0+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ mocked_out_cc = mocker.patch(OUT_CC)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ stock_infos = mocked_out.call_args.args[0]+ assert stock_infos == [+ VariantChannelStockInfo(variant_id=variant.id, channel_slug=channel_USD.slug)+ ]+ mocked_out_cc.assert_not_called()+++def test_out_of_stock_does_not_fire_when_another_warehouse_has_stock(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - second non-C&C warehouse in same channel still has availability+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=5)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ mocked_out.assert_not_called()+++def test_out_of_stock_fires_even_when_cc_warehouse_in_channel_has_stock(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - non-C&C stock at 0; C&C warehouse with stock must not block event+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ mocked_out_cc = mocker.patch(OUT_CC)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ cc_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="cc",+ slug="cc",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ )+ cc_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=cc_warehouse, quantity=5)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - non-C&C bucket is empty, event fires; C&C event is not raised+ mocked_out.assert_called_once()+ mocked_out_cc.assert_not_called()+++def test_out_of_stock_in_cc_warehouse_fires_click_and_collect_event(+ variant, channel_USD, address, site_settings, mocker+):+ # given - C&C-only warehouse, stock just hit 0+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ mocked_out_cc = mocker.patch(OUT_CC)+ cc_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="cc-only",+ slug="cc-only",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ )+ cc_warehouse.channels.add(channel_USD)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=cc_warehouse, quantity=0+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ stock_infos = mocked_out_cc.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].channel_slug == channel_USD.slug+ mocked_out.assert_not_called()+++def test_back_in_stock_fires_when_all_other_warehouses_in_bucket_are_empty(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - other non-C&C warehouse exists but has zero available+ mocked_back = mocker.patch(BACK_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=10+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=0)++ # when+ trigger_back_in_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ mocked_back.assert_called_once()+++def test_back_in_stock_does_not_fire_when_another_warehouse_already_has_stock(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - another warehouse already has stock, so this isn't the "first back"+ mocked_back = mocker.patch(BACK_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=10+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=4)++ # when+ trigger_back_in_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ mocked_back.assert_not_called()+++def test_does_not_fire_when_warehouse_belongs_to_no_channels(+ variant, address, site_settings, mocker+):+ # given - warehouse not attached to any channel+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ orphan = Warehouse.objects.create(+ address=address.get_copy(),+ name="orphan",+ slug="orphan",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ stock = Stock.objects.create(product_variant=variant, warehouse=orphan, quantity=0)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ mocked_out.assert_not_called()+++def test_fires_only_for_channels_whose_bucket_is_empty(+ variant, warehouse, channel_USD, channel_PLN, address, site_settings, mocker+):+ # given - warehouse belongs to two channels; only one has another warehouse+ # with remaining stock+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ warehouse.channels.add(channel_PLN)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other-usd",+ slug="other-usd",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=5)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - PLN bucket is empty (only `warehouse`), USD has another with stock+ mocked_out.assert_called_once()+ stock_infos = mocked_out.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].channel_slug == channel_PLN.slug+++def test_out_of_stock_fires_when_other_warehouse_has_only_fully_allocated_stock(+ variant, warehouse, channel_USD, address, site_settings, order_line, mocker+):+ # given - other warehouse has quantity but everything is allocated+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ other_stock = Stock.objects.create(+ product_variant=variant, warehouse=other_warehouse, quantity=5+ )+ Allocation.objects.create(+ order_line=order_line, stock=other_stock, quantity_allocated=5+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - other stock has 0 available -> event fires+ mocked_out.assert_called_once()+++def test_out_of_stock_ignores_stocks_of_other_variants_in_same_bucket(+ variant,+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - other warehouse has stock for a *different* variant+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ other_variant = product_with_two_variants.variants.first()+ Stock.objects.create(+ product_variant=other_variant, warehouse=other_warehouse, quantity=10+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - other variant's stock is irrelevant; bucket is empty for tested variant+ mocked_out.assert_called_once()+++def test_out_of_stock_ignores_warehouse_stock_attached_to_different_channel(+ variant, warehouse, channel_USD, channel_PLN, address, site_settings, mocker+):+ # given - other warehouse with stock exists, but only in a different channel+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="pln-only",+ slug="pln-only",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_PLN)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=5)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - the USD bucket has no other warehouses, event fires+ mocked_out.assert_called_once()+ stock_infos = mocked_out.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].channel_slug == channel_USD.slug+++def test_trigger_forwards_site_settings_requestor_and_webhooks(+ variant, warehouse, channel_USD, site_settings, mocker+):+ # given+ mocked_out = mocker.patch(OUT_IN_CHANNEL)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then+ args, kwargs = mocked_out.call_args+ assert args[1] is site_settings+ assert kwargs["requestor"] is None+ assert kwargs["webhooks"] is None+++def test_bulk_out_of_stock_fires_for_multiple_stocks_in_same_warehouse(+ product_with_two_variants, warehouse, channel_USD, site_settings, mocker+):+ # given - two variants in the same warehouse, both at 0+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 0+ Stock.objects.bulk_update(stocks, ["quantity"])++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then - one batched call carrying one info per (variant, channel)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ fired_variant_ids = {info.variant_id for info in stock_infos}+ assert fired_variant_ids == {variants[0].id, variants[1].id}+++def test_bulk_out_of_stock_does_not_fire_when_other_warehouse_covers_all_variants(+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - another non-C&C warehouse in the same channel has stock for both+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 0+ Stock.objects.bulk_update(stocks, ["quantity"])+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.bulk_create(+ [+ Stock(product_variant=variants[0], warehouse=other_warehouse, quantity=5),+ Stock(product_variant=variants[1], warehouse=other_warehouse, quantity=3),+ ]+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then+ mocked_trigger.assert_not_called()+++def test_bulk_out_of_stock_fires_selectively_when_other_warehouse_covers_only_one_variant(+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - another warehouse has stock only for variants[0], not variants[1]+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 0+ Stock.objects.bulk_update(stocks, ["quantity"])+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(+ product_variant=variants[0], warehouse=other_warehouse, quantity=5+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variants[1].id+++def test_bulk_out_of_stock_deduplicates_same_variant_across_warehouses_in_channel(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - two warehouses in the same channel, same variant, both at 0+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ stock_a, stock_b = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=0),+ Stock(product_variant=variant, warehouse=other_warehouse, quantity=0),+ ]+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock_a, stock_b], site_settings)++ # then - fires once per (variant, channel)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant.id+ assert stock_infos[0].channel_slug == channel_USD.slug+++def test_bulk_out_of_stock_warehouse_a_is_other_for_warehouse_b_stock(+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - warehouse A has variant X (at 0) and variant Y (qty 5)+ # warehouse B has variant Y at 0+ # For variant X in warehouse A: warehouse B has no stock → fires+ # For variant Y in warehouse B: warehouse A has stock → does not fire+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ variant_x, variant_y = variants[0], variants[1]++ stock_a_x = Stock.objects.get(product_variant=variant_x, warehouse=warehouse)+ stock_a_x.quantity = 0+ stock_a_y = Stock.objects.get(product_variant=variant_y, warehouse=warehouse)+ stock_a_y.quantity = 5+ Stock.objects.bulk_update([stock_a_x, stock_a_y], ["quantity"])++ warehouse_b = Warehouse.objects.create(+ address=address.get_copy(),+ name="warehouse-b",+ slug="warehouse-b",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ warehouse_b.channels.add(channel_USD)+ stock_b_y = Stock.objects.create(+ product_variant=variant_y, warehouse=warehouse_b, quantity=0+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(+ [stock_a_x, stock_b_y], site_settings+ )++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant_x.id+++def test_bulk_out_of_stock_mixed_cc_and_non_cc_stocks(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - one non-C&C stock and one C&C stock, both at 0+ mocked_non_cc = mocker.patch(OUT_IN_CHANNEL)+ mocked_cc = mocker.patch(OUT_CC)+ cc_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="cc",+ slug="cc",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ )+ cc_warehouse.channels.add(channel_USD)+ stock_non_cc, stock_cc = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=0),+ Stock(product_variant=variant, warehouse=cc_warehouse, quantity=0),+ ]+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(+ [stock_non_cc, stock_cc], site_settings+ )++ # then - each fires in its own event type+ mocked_non_cc.assert_called_once()+ non_cc_infos = mocked_non_cc.call_args.args[0]+ assert len(non_cc_infos) == 1+ assert non_cc_infos[0].variant_id == variant.id+ mocked_cc.assert_called_once()+ cc_infos = mocked_cc.call_args.args[0]+ assert len(cc_infos) == 1+ assert cc_infos[0].variant_id == variant.id+++def test_bulk_out_of_stock_multi_channel_fires_per_channel_independently(+ variant, warehouse, channel_USD, channel_PLN, address, site_settings, mocker+):+ # given - warehouse in both channels; another warehouse with stock only in USD+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ warehouse.channels.add(channel_PLN)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=0+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="usd-only",+ slug="usd-only",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=5)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - fires only for PLN (USD has other warehouse with stock)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].channel_slug == channel_PLN.slug+++def test_bulk_out_of_stock_empty_list_does_not_fire(site_settings, mocker):+ # given+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([], site_settings)++ # then+ mocked_trigger.assert_not_called()+++def test_bulk_out_of_stock_two_different_variants_fires_for_each(+ product_with_two_variants, warehouse, channel_USD, site_settings, mocker+):+ # given - two different variants in the same warehouse, both at 0, no other+ # warehouse in the channel+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 0+ Stock.objects.bulk_update(stocks, ["quantity"])++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ fired_pairs = {(info.variant_id, info.channel_slug) for info in stock_infos}+ assert fired_pairs == {+ (variants[0].id, channel_USD.slug),+ (variants[1].id, channel_USD.slug),+ }+++def test_bulk_out_of_stock_deduplicates_same_variant_multiple_warehouses_and_channels(+ variant, warehouse, channel_USD, channel_PLN, address, site_settings, mocker+):+ # given - same variant in two warehouses, both in two channels, both at 0+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ warehouse.channels.add(channel_PLN)+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD, channel_PLN)+ stock_a, stock_b = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=0),+ Stock(product_variant=variant, warehouse=other_warehouse, quantity=0),+ ]+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks([stock_a, stock_b], site_settings)++ # then - fires once per channel (2 channels), not once per stock+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 2+ fired_slugs = {info.channel_slug for info in stock_infos}+ assert fired_slugs == {channel_USD.slug, channel_PLN.slug}+++def test_bulk_out_of_stock_different_variants_partial_coverage_by_other_warehouse(+ product_with_two_variants,+ warehouse,+ channel_USD,+ channel_PLN,+ address,+ site_settings,+ mocker,+):+ # given - variant X is covered by other warehouse in USD but not PLN+ # variant Y has no coverage in either channel+ mocked_trigger = mocker.patch(OUT_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ variant_x, variant_y = variants[0], variants[1]++ warehouse.channels.add(channel_PLN)+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 0+ Stock.objects.bulk_update(stocks, ["quantity"])++ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ # other warehouse only in USD, only has stock for variant X+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(+ product_variant=variant_x, warehouse=other_warehouse, quantity=5+ )++ # when+ trigger_out_of_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then+ # variant X: covered in USD, uncovered in PLN → fires only for PLN+ # variant Y: uncovered everywhere → fires for both USD and PLN+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 3+ fired_pairs = {(info.variant_id, info.channel_slug) for info in stock_infos}+ assert fired_pairs == {+ (variant_x.id, channel_PLN.slug),+ (variant_y.id, channel_USD.slug),+ (variant_y.id, channel_PLN.slug),+ }+++def test_bulk_back_in_stock_fires_for_multiple_stocks_in_same_warehouse(+ product_with_two_variants, warehouse, channel_USD, site_settings, mocker+):+ # given - two variants in the same warehouse, both back at positive qty+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ # stocks are already at qty 10 from the fixture+ for stock in stocks:+ stock.quantity = 10+ Stock.objects.bulk_update(stocks, ["quantity"])++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then - one batched call carrying one info per (variant, channel)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ fired_variant_ids = {info.variant_id for info in stock_infos}+ assert fired_variant_ids == {variants[0].id, variants[1].id}+++def test_bulk_back_in_stock_does_not_fire_when_other_warehouse_covers_all_variants(+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - another non-C&C warehouse in the same channel already has stock+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 10+ Stock.objects.bulk_update(stocks, ["quantity"])+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.bulk_create(+ [+ Stock(product_variant=variants[0], warehouse=other_warehouse, quantity=5),+ Stock(product_variant=variants[1], warehouse=other_warehouse, quantity=3),+ ]+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then - other warehouse already had stock, these aren't "first back"+ mocked_trigger.assert_not_called()+++def test_bulk_back_in_stock_fires_selectively_when_other_warehouse_covers_only_one_variant(+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - another warehouse has stock only for variants[0], not variants[1]+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 10+ Stock.objects.bulk_update(stocks, ["quantity"])+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(+ product_variant=variants[0], warehouse=other_warehouse, quantity=5+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then - only variants[1] fires (variants[0] was already covered elsewhere)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variants[1].id+++def test_bulk_back_in_stock_deduplicates_same_variant_across_warehouses_in_channel(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - two warehouses in the same channel, same variant, both back at positive+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ stock_a, stock_b = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=10),+ Stock(product_variant=variant, warehouse=other_warehouse, quantity=10),+ ]+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(+ [stock_a, stock_b], site_settings+ )++ # then - fires once per (variant, channel)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant.id+ assert stock_infos[0].channel_slug == channel_USD.slug+++def test_bulk_back_in_stock_warehouse_a_is_other_for_warehouse_b_stock(+ product_with_two_variants,+ warehouse,+ channel_USD,+ address,+ site_settings,+ mocker,+):+ # given - warehouse A has variant X back (qty 10) and variant Y with qty 5+ # warehouse B has variant Y back (qty 10)+ # For variant X in warehouse A: warehouse B has no stock for X → fires+ # For variant Y in warehouse B: warehouse A has stock for Y → does not fire+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ variant_x, variant_y = variants[0], variants[1]++ stock_a_x = Stock.objects.get(product_variant=variant_x, warehouse=warehouse)+ stock_a_x.quantity = 10+ stock_a_y = Stock.objects.get(product_variant=variant_y, warehouse=warehouse)+ stock_a_y.quantity = 5+ Stock.objects.bulk_update([stock_a_x, stock_a_y], ["quantity"])++ warehouse_b = Warehouse.objects.create(+ address=address.get_copy(),+ name="warehouse-b",+ slug="warehouse-b",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ warehouse_b.channels.add(channel_USD)+ stock_b_y = Stock.objects.create(+ product_variant=variant_y, warehouse=warehouse_b, quantity=10+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(+ [stock_a_x, stock_b_y], site_settings+ )++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].variant_id == variant_x.id+++def test_bulk_back_in_stock_mixed_cc_and_non_cc_stocks(+ variant, warehouse, channel_USD, address, site_settings, mocker+):+ # given - one non-C&C stock and one C&C stock, both back at positive qty+ mocked_non_cc = mocker.patch(BACK_IN_CHANNEL)+ mocked_cc = mocker.patch(BACK_CC)+ cc_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="cc",+ slug="cc",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ )+ cc_warehouse.channels.add(channel_USD)+ stock_non_cc, stock_cc = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=10),+ Stock(product_variant=variant, warehouse=cc_warehouse, quantity=10),+ ]+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(+ [stock_non_cc, stock_cc], site_settings+ )++ # then - each fires in its own event type+ mocked_non_cc.assert_called_once()+ non_cc_infos = mocked_non_cc.call_args.args[0]+ assert len(non_cc_infos) == 1+ assert non_cc_infos[0].variant_id == variant.id+ mocked_cc.assert_called_once()+ cc_infos = mocked_cc.call_args.args[0]+ assert len(cc_infos) == 1+ assert cc_infos[0].variant_id == variant.id+++def test_bulk_back_in_stock_multi_channel_fires_per_channel_independently(+ variant, warehouse, channel_USD, channel_PLN, address, site_settings, mocker+):+ # given - warehouse in both channels; another warehouse with stock only in USD+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ warehouse.channels.add(channel_PLN)+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=10+ )+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="usd-only",+ slug="usd-only",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(product_variant=variant, warehouse=other_warehouse, quantity=5)++ # when+ trigger_back_in_stock_in_channel_events_for_stocks([stock], site_settings)++ # then - fires only for PLN (USD already has other warehouse with stock)+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 1+ assert stock_infos[0].channel_slug == channel_PLN.slug+++def test_bulk_back_in_stock_empty_list_does_not_fire(site_settings, mocker):+ # given+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)++ # when+ trigger_back_in_stock_in_channel_events_for_stocks([], site_settings)++ # then+ mocked_trigger.assert_not_called()+++def test_bulk_back_in_stock_two_different_variants_fires_for_each(+ product_with_two_variants, warehouse, channel_USD, site_settings, mocker+):+ # given - two different variants in the same warehouse, both back at positive,+ # no other warehouse in the channel+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 10+ Stock.objects.bulk_update(stocks, ["quantity"])++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ fired_pairs = {(info.variant_id, info.channel_slug) for info in stock_infos}+ assert fired_pairs == {+ (variants[0].id, channel_USD.slug),+ (variants[1].id, channel_USD.slug),+ }+++def test_bulk_back_in_stock_deduplicates_same_variant_multiple_warehouses_and_channels(+ variant, warehouse, channel_USD, channel_PLN, address, site_settings, mocker+):+ # given - same variant in two warehouses, both in two channels, both back at positive+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ warehouse.channels.add(channel_PLN)+ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ other_warehouse.channels.add(channel_USD, channel_PLN)+ stock_a, stock_b = Stock.objects.bulk_create(+ [+ Stock(product_variant=variant, warehouse=warehouse, quantity=10),+ Stock(product_variant=variant, warehouse=other_warehouse, quantity=10),+ ]+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(+ [stock_a, stock_b], site_settings+ )++ # then - fires once per channel, not once per stock+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 2+ fired_slugs = {info.channel_slug for info in stock_infos}+ assert fired_slugs == {channel_USD.slug, channel_PLN.slug}+++def test_bulk_back_in_stock_different_variants_partial_coverage_by_other_warehouse(+ product_with_two_variants,+ warehouse,+ channel_USD,+ channel_PLN,+ address,+ site_settings,+ mocker,+):+ # given - variant X is covered by other warehouse in USD but not PLN+ # variant Y has no coverage in either channel+ mocked_trigger = mocker.patch(BACK_IN_CHANNEL)+ variants = list(product_with_two_variants.variants.all())+ variant_x, variant_y = variants[0], variants[1]++ warehouse.channels.add(channel_PLN)+ stocks = list(+ Stock.objects.filter(product_variant__in=variants, warehouse=warehouse)+ )+ for stock in stocks:+ stock.quantity = 10+ Stock.objects.bulk_update(stocks, ["quantity"])++ other_warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="other",+ slug="other",+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,+ )+ # other warehouse only in USD, only has stock for variant X+ other_warehouse.channels.add(channel_USD)+ Stock.objects.create(+ product_variant=variant_x, warehouse=other_warehouse, quantity=5+ )++ # when+ trigger_back_in_stock_in_channel_events_for_stocks(stocks, site_settings)++ # then+ # variant X: USD already covered by other warehouse, PLN uncovered → fires only for PLN+ # variant Y: uncovered everywhere → fires for both USD and PLN+ mocked_trigger.assert_called_once()+ stock_infos = mocked_trigger.call_args.args[0]+ assert len(stock_infos) == 3+ fired_pairs = {(info.variant_id, info.channel_slug) for info in stock_infos}+ assert fired_pairs == {+ (variant_x.id, channel_PLN.slug),+ (variant_y.id, channel_USD.slug),+ (variant_y.id, channel_PLN.slug),+ }diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex efd7a368a0..9dc8815751 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -24,7 +24,7 @@ from ..models import Allocation, ChannelWarehouse, PreorderAllocationCOUNTRY_CODE = "US"-def test_allocate_stocks(order_line, stock, channel_USD):+def test_allocate_stocks(order_line, stock, channel_USD, site_settings):stock.quantity = 100stock.save(update_fields=["quantity"])@@ -34,6 +34,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):[line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -46,7 +47,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):def test_allocate_stocks_multiple_lines_the_highest_stock_strategy(- order_line, order, product, stock, channel_USD+ order_line, order, product, stock, channel_USD, site_settings):stock.quantity = 100stock.save(update_fields=["quantity"])@@ -75,6 +76,7 @@ def test_allocate_stocks_multiple_lines_the_highest_stock_strategy([line_data_1, line_data_2],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -90,7 +92,7 @@ def test_allocate_stocks_multiple_lines_the_highest_stock_strategy(def test_allocate_stock_many_stocks_the_highest_stock_strategy(- order_line, variant_with_many_stocks, channel_USD+ order_line, variant_with_many_stocks, channel_USD, site_settings):variant = variant_with_many_stocksstocks = variant.stocks.all()@@ -100,6 +102,7 @@ def test_allocate_stock_many_stocks_the_highest_stock_strategy([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -110,7 +113,7 @@ def test_allocate_stock_many_stocks_the_highest_stock_strategy(def test_allocate_stocks_the_highest_stock_strategy_with_collection_point(- order_line, variant_with_many_stocks, channel_USD, warehouse_for_cc+ order_line, variant_with_many_stocks, channel_USD, warehouse_for_cc, site_settings):"""Test that collection points take precedence during stock allocation.@@ -133,6 +136,7 @@ def test_allocate_stocks_the_highest_stock_strategy_with_collection_point([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,collection_point_pk=warehouse_for_cc.pk,@@ -145,7 +149,7 @@ def test_allocate_stocks_the_highest_stock_strategy_with_collection_point(def test_allocate_stock_many_stocks_prioritize_sorting_order_strategy(- order_line, variant_with_many_stocks, channel_USD+ order_line, variant_with_many_stocks, channel_USD, site_settings):# givenchannel_USD.allocation_strategy = AllocationStrategy.PRIORITIZE_SORTING_ORDER@@ -174,6 +178,7 @@ def test_allocate_stock_many_stocks_prioritize_sorting_order_strategy([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -197,7 +202,7 @@ def test_allocate_stock_many_stocks_prioritize_sorting_order_strategy(def test_allocate_stock_prioritize_sorting_order_strategy_with_collection_point(- order_line, variant_with_many_stocks, channel_USD, warehouse_for_cc+ order_line, variant_with_many_stocks, channel_USD, warehouse_for_cc, site_settings):"""Test that collection points take precedence during stock allocation.@@ -236,6 +241,7 @@ def test_allocate_stock_prioritize_sorting_order_strategy_with_collection_point([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,collection_point_pk=warehouse_for_cc.pk,@@ -253,6 +259,7 @@ def test_allocate_stock_with_reservations_the_highest_stock_strategy(variant_with_many_stocks,channel_USD,checkout_line_with_one_reservation,+ site_settings,):variant = variant_with_many_stocksstocks = variant.stocks.all()@@ -262,6 +269,7 @@ def test_allocate_stock_with_reservations_the_highest_stock_strategy([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,check_reservations=True,@@ -277,6 +285,7 @@ def test_allocate_stock_with_reservations_prioritize_sorting_order_strategy(variant_with_many_stocks,channel_USD,checkout_line_with_one_reservation,+ site_settings,):# given# set the prioritize sorting order stratefy@@ -309,6 +318,7 @@ def test_allocate_stock_with_reservations_prioritize_sorting_order_strategy([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,check_reservations=True,@@ -329,6 +339,7 @@ def test_allocate_stock_insufficient_stock_due_to_reservations(variant_with_many_stocks,channel_USD,checkout_line_with_reservation_in_many_stocks,+ site_settings,):variant = variant_with_many_stocksvariant.stocks.all()@@ -340,6 +351,7 @@ def test_allocate_stock_insufficient_stock_due_to_reservations([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,check_reservations=True,@@ -353,6 +365,7 @@ def test_allocate_stock_many_stocks_partially_allocated(order_line_with_allocation_in_many_stocks,order_line_with_one_allocation,channel_USD,+ site_settings,):# givenallocated_line = order_line_with_allocation_in_many_stocks@@ -370,6 +383,7 @@ def test_allocate_stock_many_stocks_partially_allocated([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -388,7 +402,7 @@ def test_allocate_stock_many_stocks_partially_allocated(def test_allocate_stock_partially_allocated_insufficient_stocks(- order_line, order_line_with_allocation_in_many_stocks, channel_USD+ order_line, order_line_with_allocation_in_many_stocks, channel_USD, site_settings):allocated_line = order_line_with_allocation_in_many_stocksvariant = allocated_line.variant@@ -400,6 +414,7 @@ def test_allocate_stock_partially_allocated_insufficient_stocks([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -409,7 +424,9 @@ def test_allocate_stock_partially_allocated_insufficient_stocks().exists()-def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_USD):+def test_allocate_stocks_no_channel_shipping_zones(+ order_line, stock, channel_USD, site_settings+):# givenchannel_USD.shipping_zones.clear()@@ -424,13 +441,14 @@ def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_US[line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)def test_allocate_stocks_no_channel_shipping_zones_excluded_from_stock_calculations(- order_line, stock, channel_USD+ order_line, stock, channel_USD, site_settings):# givenchannel_USD.shipping_zones.clear()@@ -445,13 +463,14 @@ def test_allocate_stocks_no_channel_shipping_zones_excluded_from_stock_calculati[line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=False,)def test_allocate_stock_insufficient_stocks(- order_line, variant_with_many_stocks, channel_USD+ order_line, variant_with_many_stocks, channel_USD, site_settings):variant = variant_with_many_stocksstocks = variant.stocks.all()@@ -462,6 +481,7 @@ def test_allocate_stock_insufficient_stocks([line_data],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -472,7 +492,7 @@ def test_allocate_stock_insufficient_stocks(def test_allocate_stock_insufficient_stocks_for_multiple_lines(- order_line, variant_with_many_stocks, product, channel_USD+ order_line, variant_with_many_stocks, product, channel_USD, site_settings):variant = variant_with_many_stocksstocks = variant.stocks.all()@@ -501,6 +521,7 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines([line_data_1, line_data_2],COUNTRY_CODE,channel_USD,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -512,7 +533,7 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines().exists()-def test_deallocate_stock(allocation):+def test_deallocate_stock(allocation, site_settings):stock = allocation.stockstock.quantity = 100stock.quantity_allocated = 80@@ -526,6 +547,7 @@ def test_deallocate_stock(allocation):line=allocation.order_line, quantity=80, variant=stock.product_variant)],+ site_settings=site_settings,requestor=None,)@@ -536,7 +558,7 @@ def test_deallocate_stock(allocation):assert allocation.quantity_allocated == 0-def test_deallocate_stock_when_quantity_less_than_zero(allocation):+def test_deallocate_stock_when_quantity_less_than_zero(allocation, site_settings):stock = allocation.stockstock.quantity = -10stock.save(update_fields=["quantity"])@@ -549,6 +571,7 @@ def test_deallocate_stock_when_quantity_less_than_zero(allocation):line=allocation.order_line, quantity=80, variant=stock.product_variant)],+ site_settings=site_settings,requestor=None,)@@ -558,7 +581,7 @@ def test_deallocate_stock_when_quantity_less_than_zero(allocation):assert allocation.quantity_allocated == 0-def test_deallocate_stock_partially(allocation):+def test_deallocate_stock_partially(allocation, site_settings):stock = allocation.stockstock.quantity = 100stock.quantity_allocated = 80@@ -572,6 +595,7 @@ def test_deallocate_stock_partially(allocation):line=allocation.order_line, quantity=50, variant=stock.product_variant)],+ site_settings=site_settings,requestor=None,)@@ -584,11 +608,13 @@ def test_deallocate_stock_partially(allocation):def test_deallocate_stock_many_allocations(order_line_with_allocation_in_many_stocks,+ site_settings,):order_line = order_line_with_allocation_in_many_stocksdeallocate_stock([OrderLineInfo(line=order_line, quantity=3, variant=order_line.variant)],+ site_settings=site_settings,requestor=None,)@@ -599,11 +625,13 @@ def test_deallocate_stock_many_allocations(def test_deallocate_stock_many_allocations_partially(order_line_with_allocation_in_many_stocks,+ site_settings,):order_line = order_line_with_allocation_in_many_stocksdeallocate_stock([OrderLineInfo(line=order_line, quantity=1, variant=order_line.variant)],+ site_settings=site_settings,requestor=None,)@@ -661,7 +689,7 @@ def test_increase_stock_with_new_allocation(order_line, stock):@pytest.mark.parametrize("quantity", [19, 20])-def test_increase_allocations(quantity, allocation):+def test_increase_allocations(quantity, allocation, site_settings):order_line = allocation.order_lineorder_line_info = OrderLineInfo(line=order_line,@@ -680,6 +708,7 @@ def test_increase_allocations(quantity, allocation):increase_allocations([order_line_info],order_line.order.channel,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -700,7 +729,7 @@ def test_increase_allocations(quantity, allocation):[(9, 20), (2, 19)],)def test_increase_allocations_with_multiple_allocations_for_the_same_stock(- first_quantity, second_quantity, allocations+ first_quantity, second_quantity, allocations, site_settings):# givenfirst_allocation = allocations[0]@@ -745,6 +774,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,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -767,7 +797,7 @@ def test_increase_allocations_with_multiple_allocations_for_the_same_stock()-def test_increase_allocation_insufficient_stock(allocation):+def test_increase_allocation_insufficient_stock(allocation, site_settings):order_line = allocation.order_lineorder_line_info = OrderLineInfo(line=order_line,@@ -787,6 +817,7 @@ def test_increase_allocation_insufficient_stock(allocation):increase_allocations([order_line_info],order_line.order.channel,+ site_settings=site_settings,requestor=None,calculate_stocks_with_shipping_zones=True,)@@ -822,7 +853,7 @@ def test_increase_stock_with_back_in_stock_webhook_triggered_without_allocation(product_variant_back_in_stock_webhook.assert_not_called()-def test_decrease_stock(allocation):+def test_decrease_stock(allocation, site_settings):stock = allocation.stockstock.quantity = 100stock.quantity_allocated = 80@@ -840,6 +871,7 @@ def test_decrease_stock(allocation):warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -851,7 +883,7 @@ def test_decrease_stock(allocation):@pytest.mark.parametrize(("quantity", "expected_allocated"), [(50, 30), (200, 0)])-def test_decrease_allocations(quantity, expected_allocated, allocation):+def test_decrease_allocations(quantity, expected_allocated, allocation, site_settings):stock = allocation.stockstock.quantity = 100stock.quantity_allocated = 80@@ -869,6 +901,7 @@ def test_decrease_allocations(quantity, expected_allocated, allocation):warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -879,7 +912,7 @@ def test_decrease_allocations(quantity, expected_allocated, allocation):assert allocation.quantity_allocated == expected_allocated-def test_decrease_stock_multiple_lines(allocations):+def test_decrease_stock_multiple_lines(allocations, site_settings):allocation_1 = allocations[0]allocation_2 = allocations[0]@@ -909,6 +942,7 @@ def test_decrease_stock_multiple_lines(allocations):warehouse_pk=warehouse_pk_2,),],+ site_settings=site_settings,requestor=None,)@@ -918,7 +952,9 @@ def test_decrease_stock_multiple_lines(allocations):assert allocation_1.quantity_allocated == 10-def test_decrease_stock_multiple_lines_deallocate_stock_raises_error(order_with_lines):+def test_decrease_stock_multiple_lines_deallocate_stock_raises_error(+ order_with_lines, site_settings+):"""Test that stock deallocations are immune to errors.Ensure that when some of the lines raise an error during the deallocation@@ -973,6 +1009,7 @@ def test_decrease_stock_multiple_lines_deallocate_stock_raises_error(order_with_warehouse_pk=warehouse_pk_2,),],+ site_settings=site_settings,requestor=None,)@@ -990,7 +1027,7 @@ def test_decrease_stock_multiple_lines_deallocate_stock_raises_error(order_with_assert allocation_2.quantity_allocated == allocation_2_qty_allocated - line_2_qty-def test_decrease_stock_partially(allocation):+def test_decrease_stock_partially(allocation, site_settings):stock = allocation.stockstock.quantity = 100stock.save(update_fields=["quantity"])@@ -1007,6 +1044,7 @@ def test_decrease_stock_partially(allocation):warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -1018,6 +1056,7 @@ def test_decrease_stock_partially(allocation):def test_decrease_stock_many_allocations(order_line_with_allocation_in_many_stocks,+ site_settings,):order_line = order_line_with_allocation_in_many_stocksallocations = order_line.allocations.all()@@ -1032,6 +1071,7 @@ def test_decrease_stock_many_allocations(warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -1043,6 +1083,7 @@ def test_decrease_stock_many_allocations(def test_decrease_stock_many_allocations_partially(order_line_with_allocation_in_many_stocks,+ site_settings,):order_line = order_line_with_allocation_in_many_stocksallocations = order_line.allocations.all()@@ -1057,6 +1098,7 @@ def test_decrease_stock_many_allocations_partially(warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -1068,6 +1110,7 @@ def test_decrease_stock_many_allocations_partially(def test_decrease_stock_more_then_allocated(order_line_with_allocation_in_many_stocks,+ site_settings,):order_line = order_line_with_allocation_in_many_stocksallocations = order_line.allocations.all()@@ -1086,6 +1129,7 @@ def test_decrease_stock_more_then_allocated(warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -1098,7 +1142,7 @@ def test_decrease_stock_more_then_allocated(assert allocations[1].stock.quantity == 3-def test_decrease_stock_insufficient_stock(allocation):+def test_decrease_stock_insufficient_stock(allocation, site_settings):stock = allocation.stockstock.quantity = 20stock.quantity_allocated = 80@@ -1117,6 +1161,7 @@ def test_decrease_stock_insufficient_stock(allocation):warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -1127,11 +1172,17 @@ def test_decrease_stock_insufficient_stock(allocation):assert allocation.quantity_allocated == 80-def test_deallocate_stock_for_orders(order_line_with_allocation_in_many_stocks):+def test_deallocate_stock_for_orders(+ order_line_with_allocation_in_many_stocks, site_settings+):order_line = order_line_with_allocation_in_many_stocksorder = order_line.order- deallocate_stock_for_orders([order.id], requestor=None)+ deallocate_stock_for_orders(+ [order.id],+ site_settings=site_settings,+ requestor=None,+ )allocations = order_line.allocations.all()assert (@@ -1148,6 +1199,7 @@ def test_deallocate_stock_for_orders(order_line_with_allocation_in_many_stocks):def test_deallocate_stock_for_orders_with_multiple_allocations_from_the_same_stock(allocations,+ site_settings,):# givenfirst_allocation = allocations[0]@@ -1177,7 +1229,11 @@ 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], requestor=None)+ deallocate_stock_for_orders(+ [order.id],+ site_settings=site_settings,+ requestor=None,+ )# thenfirst_allocation.refresh_from_db()@@ -1236,6 +1292,7 @@ def test_decrease_stock_with_out_of_stock_webhook_triggered(product_variant_out_of_stock_webhook_mock,allocation,django_capture_on_commit_callbacks,+ site_settings,):stock = allocation.stockstock.quantity = 50@@ -1254,6 +1311,7 @@ def test_decrease_stock_with_out_of_stock_webhook_triggered(warehouse_pk=warehouse_pk,)],+ site_settings=site_settings,requestor=None,)@@ -1408,3 +1466,247 @@ def test_allocate_preorders_with_global_reservations(check_reservations=True,checkout_lines=[checkout_line_with_reserved_preorder_item],)+++ "saleor.warehouse.channel_stock_availability.trigger_out_of_stock_in_channel_events_for_stocks"+)+def test_allocate_stocks_triggers_channel_out_of_stock_event_when_stock_runs_out(+ mocked_trigger,+ order_line,+ stock,+ channel_USD,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - allocation will drain the entire stock to 0 available+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ stock.quantity = 50+ stock.quantity_allocated = 0+ stock.save(update_fields=["quantity", "quantity_allocated"])+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ site_settings=site_settings,+ requestor=None,+ calculate_stocks_with_shipping_zones=True,+ )++ # then+ mocked_trigger.assert_called_once()+ fired_stocks, fired_settings = mocked_trigger.call_args.args+ assert len(fired_stocks) == 1+ assert fired_stocks[0].pk == stock.pk+ assert fired_settings is site_settings+++ "saleor.warehouse.channel_stock_availability.trigger_out_of_stock_in_channel_events_for_stocks"+)+def test_allocate_stocks_does_not_trigger_channel_event_when_stock_remains(+ mocked_trigger,+ order_line,+ stock,+ channel_USD,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - allocation only takes a fraction of the available stock+ stock.quantity = 100+ stock.quantity_allocated = 0+ stock.save(update_fields=["quantity", "quantity_allocated"])+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=10)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ site_settings=site_settings,+ requestor=None,+ calculate_stocks_with_shipping_zones=True,+ )++ # then+ mocked_trigger.assert_not_called()+++ "saleor.warehouse.channel_stock_availability.trigger_out_of_stock_in_channel_events_for_stocks"+)+def test_allocate_stocks_skips_channel_event_when_legacy_flag_enabled(+ mocked_trigger,+ order_line,+ stock,+ channel_USD,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - legacy flag is on; channel events should be skipped entirely+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ stock.quantity = 50+ stock.quantity_allocated = 0+ stock.save(update_fields=["quantity", "quantity_allocated"])+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ site_settings=site_settings,+ requestor=None,+ calculate_stocks_with_shipping_zones=True,+ )++ # then+ mocked_trigger.assert_not_called()+++ "saleor.warehouse.channel_stock_availability.trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_deallocate_stock_triggers_channel_back_in_stock_event_when_stock_returns(+ mocked_trigger,+ allocation,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - all of the stock is currently allocated (available = 0); deallocating+ # frees it back up+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ stock = allocation.stock+ stock.quantity = allocation.quantity_allocated+ stock.save(update_fields=["quantity"])+ line_info = OrderLineInfo(+ line=allocation.order_line,+ variant=stock.product_variant,+ quantity=allocation.quantity_allocated,+ warehouse_pk=stock.warehouse_id,+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ deallocate_stock(+ [line_info],+ site_settings=site_settings,+ requestor=None,+ )++ # then+ mocked_trigger.assert_called_once()+ fired_stocks, fired_settings = mocked_trigger.call_args.args+ assert len(fired_stocks) == 1+ assert fired_stocks[0].pk == stock.pk+ assert fired_settings is site_settings+++ "saleor.warehouse.channel_stock_availability.trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_deallocate_stock_skips_channel_event_when_legacy_flag_enabled(+ mocked_trigger,+ allocation,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - legacy flag is on+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ stock = allocation.stock+ stock.quantity = allocation.quantity_allocated+ stock.save(update_fields=["quantity"])+ line_info = OrderLineInfo(+ line=allocation.order_line,+ variant=stock.product_variant,+ quantity=allocation.quantity_allocated,+ warehouse_pk=stock.warehouse_id,+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ deallocate_stock(+ [line_info],+ site_settings=site_settings,+ requestor=None,+ )++ # then+ mocked_trigger.assert_not_called()+++ "saleor.warehouse.channel_stock_availability.trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_deallocate_stock_for_orders_triggers_channel_back_in_stock_event(+ mocked_trigger,+ order_line_with_allocation_in_many_stocks,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - drive every allocated stock down to zero available so the deallocation+ # qualifies as "back in stock"+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ order_line = order_line_with_allocation_in_many_stocks+ order = order_line.order+ stocks = []+ for allocation in Allocation.objects.filter(order_line__order=order):+ stock = allocation.stock+ stock.quantity = allocation.quantity_allocated+ stock.save(update_fields=["quantity"])+ stocks.append(stock)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ deallocate_stock_for_orders(+ [order.id],+ site_settings=site_settings,+ requestor=None,+ )++ # then - fires once with all affected stocks (bulk)+ mocked_trigger.assert_called_once()+ fired_stocks = mocked_trigger.call_args.args[0]+ assert len(fired_stocks) == len(stocks)+++ "saleor.warehouse.channel_stock_availability.trigger_back_in_stock_in_channel_events_for_stocks"+)+def test_deallocate_stock_for_orders_skips_channel_event_when_legacy_flag_enabled(+ mocked_trigger,+ order_line_with_allocation_in_many_stocks,+ site_settings,+ django_capture_on_commit_callbacks,+):+ # given - legacy flag is on+ site_settings.use_legacy_shipping_zone_stock_availability = True+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ order_line = order_line_with_allocation_in_many_stocks+ order = order_line.order+ for allocation in Allocation.objects.filter(order_line__order=order):+ stock = allocation.stock+ stock.quantity = allocation.quantity_allocated+ stock.save(update_fields=["quantity"])++ # when+ with django_capture_on_commit_callbacks(execute=True):+ deallocate_stock_for_orders(+ [order.id],+ site_settings=site_settings,+ requestor=None,+ )++ # then+ mocked_trigger.assert_not_called()diff --git a/saleor/warehouse/tests/webhooks/subscriptions/__init__.py b/saleor/warehouse/tests/webhooks/subscriptions/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/warehouse/tests/webhooks/subscriptions/test_channel_stock_events.py b/saleor/warehouse/tests/webhooks/subscriptions/test_channel_stock_events.pynew file mode 100644index 0000000000..054caec9f6--- /dev/null+++ b/saleor/warehouse/tests/webhooks/subscriptions/test_channel_stock_events.py@@ -0,0 +1,200 @@+import json++import graphene+import pytest++from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.transport.asynchronous.transport import (+ create_deliveries_for_subscriptions,+)+from ....interface import VariantChannelStockInfo++PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL = """+ subscription{+ event{+ ...on ProductVariantOutOfStockInChannel{+ productVariant{ id }+ channel{ slug }+ }+ }+ }+"""++PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL = """+ subscription{+ event{+ ...on ProductVariantBackInStockInChannel{+ productVariant{ id }+ channel{ slug }+ }+ }+ }+"""++PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT = """+ subscription{+ event{+ ...on ProductVariantOutOfStockForClickAndCollect{+ productVariant{ id }+ channel{ slug }+ }+ }+ }+"""++PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT = """+ subscription{+ event{+ ...on ProductVariantBackInStockForClickAndCollect{+ productVariant{ id }+ channel{ slug }+ }+ }+ }+"""+++def subscription_product_variant_out_of_stock_in_channel_webhook(subscription_webhook):+ return subscription_webhook(+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ )+++def subscription_product_variant_back_in_stock_in_channel_webhook(subscription_webhook):+ return subscription_webhook(+ PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL,+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL,+ )+++def subscription_product_variant_out_of_stock_for_click_and_collect_webhook(+ subscription_webhook,+):+ return subscription_webhook(+ PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT,+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT,+ )+++def subscription_product_variant_back_in_stock_for_click_and_collect_webhook(+ subscription_webhook,+):+ return subscription_webhook(+ PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT,+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT,+ )+++def test_product_variant_out_of_stock_in_channel(+ variant,+ channel_USD,+ subscription_product_variant_out_of_stock_in_channel_webhook,+):+ # given+ webhooks = [subscription_product_variant_out_of_stock_in_channel_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ stock_info = VariantChannelStockInfo(+ variant_id=variant.id, channel_slug=channel_USD.slug+ )++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, stock_info, webhooks)++ # then+ payload = json.loads(deliveries[0].payload.get_payload())+ assert payload == {+ "productVariant": {"id": variant_id},+ "channel": {"slug": channel_USD.slug},+ }+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_product_variant_back_in_stock_in_channel(+ variant,+ channel_USD,+ subscription_product_variant_back_in_stock_in_channel_webhook,+):+ # given+ webhooks = [subscription_product_variant_back_in_stock_in_channel_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ stock_info = VariantChannelStockInfo(+ variant_id=variant.id, channel_slug=channel_USD.slug+ )++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, stock_info, webhooks)++ # then+ payload = json.loads(deliveries[0].payload.get_payload())+ assert payload == {+ "productVariant": {"id": variant_id},+ "channel": {"slug": channel_USD.slug},+ }+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_product_variant_out_of_stock_for_click_and_collect(+ variant,+ channel_USD,+ subscription_product_variant_out_of_stock_for_click_and_collect_webhook,+):+ # given+ webhooks = [subscription_product_variant_out_of_stock_for_click_and_collect_webhook]+ event_type = (+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ stock_info = VariantChannelStockInfo(+ variant_id=variant.id, channel_slug=channel_USD.slug+ )++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, stock_info, webhooks)++ # then+ payload = json.loads(deliveries[0].payload.get_payload())+ assert payload == {+ "productVariant": {"id": variant_id},+ "channel": {"slug": channel_USD.slug},+ }+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_product_variant_back_in_stock_for_click_and_collect(+ variant,+ channel_USD,+ subscription_product_variant_back_in_stock_for_click_and_collect_webhook,+):+ # given+ webhooks = [+ subscription_product_variant_back_in_stock_for_click_and_collect_webhook+ ]+ event_type = (+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ stock_info = VariantChannelStockInfo(+ variant_id=variant.id, channel_slug=channel_USD.slug+ )++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, stock_info, webhooks)++ # then+ payload = json.loads(deliveries[0].payload.get_payload())+ assert payload == {+ "productVariant": {"id": variant_id},+ "channel": {"slug": channel_USD.slug},+ }+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]diff --git a/saleor/warehouse/tests/webhooks/test_channel_stock_events.py b/saleor/warehouse/tests/webhooks/test_channel_stock_events.pynew file mode 100644index 0000000000..b34591fbfa--- /dev/null+++ b/saleor/warehouse/tests/webhooks/test_channel_stock_events.py@@ -0,0 +1,287 @@+import json+from unittest import mock++import graphene+import pytest++from ....webhook.event_types import WebhookEventAsyncType+from ...interface import VariantChannelStockInfo+from ...webhooks.channel_stock_events import (+ _trigger,+ trigger_product_variant_back_in_stock_for_click_and_collect,+ trigger_product_variant_back_in_stock_in_channel,+ trigger_product_variant_out_of_stock_for_click_and_collect,+ trigger_product_variant_out_of_stock_in_channel,+)++TRIGGER_PATH = (+ "saleor.warehouse.webhooks.channel_stock_events"+ ".trigger_webhooks_async_for_multiple_objects"+)+GET_WEBHOOKS_PATH = (+ "saleor.warehouse.webhooks.channel_stock_events.get_webhooks_for_event"+)+++def stock_info():+ return VariantChannelStockInfo(variant_id=42, channel_slug="default")+++ ("trigger_fn", "event_type"),+ [+ (+ trigger_product_variant_out_of_stock_in_channel,+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ ),+ (+ trigger_product_variant_back_in_stock_in_channel,+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL,+ ),+ (+ trigger_product_variant_out_of_stock_for_click_and_collect,+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT,+ ),+ (+ trigger_product_variant_back_in_stock_for_click_and_collect,+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT,+ ),+ ],+)[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_dispatches(+ mocked_get_webhooks,+ mocked_trigger,+ any_webhook,+ stock_info,+ site_settings,+ trigger_fn,+ event_type,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ mocked_get_webhooks.return_value = [any_webhook]++ # when+ trigger_fn([stock_info], site_settings)++ # then+ mocked_get_webhooks.assert_called_once_with(event_type)+ mocked_trigger.assert_called_once()+ kwargs = mocked_trigger.call_args.kwargs+ assert kwargs["event_type"] == event_type+ assert kwargs["webhooks"] == [any_webhook]+ assert kwargs["requestor"] is None+ payloads = kwargs["webhook_payloads_data"]+ assert len(payloads) == 1+ assert payloads[0].subscribable_object is stock_info+ legacy_payload = json.loads(payloads[0].legacy_data_generator())+ assert legacy_payload == {+ "product_variant_id": graphene.Node.to_global_id(+ "ProductVariant", stock_info.variant_id+ ),+ "channel": {"slug": stock_info.channel_slug},+ }++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_skipped_when_legacy_flag_on(+ mocked_get_webhooks, mocked_trigger, stock_info, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = True++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [stock_info],+ site_settings,+ None,+ None,+ )++ # then+ mocked_get_webhooks.assert_not_called()+ mocked_trigger.assert_not_called()++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_empty_stock_infos_skips(+ mocked_get_webhooks, mocked_trigger, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [],+ site_settings,+ None,+ None,+ )++ # then+ mocked_get_webhooks.assert_not_called()+ mocked_trigger.assert_not_called()++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_no_webhooks_skips(+ mocked_get_webhooks, mocked_trigger, stock_info, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ mocked_get_webhooks.return_value = []++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [stock_info],+ site_settings,+ None,+ None,+ )++ # then+ mocked_trigger.assert_not_called()++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_uses_passed_webhooks(+ mocked_get_webhooks,+ mocked_trigger,+ any_webhook,+ stock_info,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [stock_info],+ site_settings,+ None,+ [any_webhook],+ )++ # then+ mocked_get_webhooks.assert_not_called()+ assert mocked_trigger.call_args.kwargs["webhooks"] == [any_webhook]++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_filters_webhooks_by_channel_slug(+ mocked_get_webhooks, mocked_trigger, stock_info, site_settings+):+ # given - webhook subscription only allows a different channel+ site_settings.use_legacy_shipping_zone_stock_availability = False+ webhook = mock.Mock()+ webhook.subscription_query = "subscription { event { ... } }"+ webhook.filterable_channel_slugs = ["other-channel"]+ mocked_get_webhooks.return_value = [webhook]++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [stock_info],+ site_settings,+ None,+ None,+ )++ # then+ mocked_trigger.assert_not_called()++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_passes_through_when_subscription_has_no_channel_filter(+ mocked_get_webhooks, mocked_trigger, stock_info, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ webhook = mock.Mock()+ webhook.subscription_query = "subscription { event { ... } }"+ webhook.filterable_channel_slugs = []+ mocked_get_webhooks.return_value = [webhook]++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [stock_info],+ site_settings,+ None,+ None,+ )++ # then+ mocked_trigger.assert_called_once()+ assert mocked_trigger.call_args.kwargs["webhooks"] == [webhook]++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_groups_multiple_channels_into_separate_calls(+ mocked_get_webhooks, mocked_trigger, any_webhook, site_settings+):+ # given - two stock infos in different channels, one shared subscription webhook+ site_settings.use_legacy_shipping_zone_stock_availability = False+ mocked_get_webhooks.return_value = [any_webhook]+ info_a = VariantChannelStockInfo(variant_id=1, channel_slug="default")+ info_b = VariantChannelStockInfo(variant_id=2, channel_slug="other")++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [info_a, info_b],+ site_settings,+ None,+ None,+ )++ # then - one call per channel, each with a single payload+ assert mocked_trigger.call_count == 2+ dispatched = {+ call.kwargs["webhook_payloads_data"][0].subscribable_object.channel_slug: [+ payload.subscribable_object.variant_id+ for payload in call.kwargs["webhook_payloads_data"]+ ]+ for call in mocked_trigger.call_args_list+ }+ assert dispatched == {"default": [info_a.variant_id], "other": [info_b.variant_id]}++[email protected](TRIGGER_PATH)[email protected](GET_WEBHOOKS_PATH)+def test_trigger_batches_multiple_variants_in_same_channel(+ mocked_get_webhooks, mocked_trigger, any_webhook, site_settings+):+ # given - two variants in the same channel+ site_settings.use_legacy_shipping_zone_stock_availability = False+ mocked_get_webhooks.return_value = [any_webhook]+ info_a = VariantChannelStockInfo(variant_id=1, channel_slug="default")+ info_b = VariantChannelStockInfo(variant_id=2, channel_slug="default")++ # when+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ [info_a, info_b],+ site_settings,+ None,+ None,+ )++ # then - one call carrying both payloads+ mocked_trigger.assert_called_once()+ payloads = mocked_trigger.call_args.kwargs["webhook_payloads_data"]+ assert [payload.subscribable_object for payload in payloads] == [info_a, info_b]diff --git a/saleor/warehouse/webhooks/channel_stock_events.py b/saleor/warehouse/webhooks/channel_stock_events.pynew file mode 100644index 0000000000..7bfdde05b6--- /dev/null+++ b/saleor/warehouse/webhooks/channel_stock_events.py@@ -0,0 +1,134 @@+import json+from collections import defaultdict+from functools import partial+from typing import TYPE_CHECKING++import graphene++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_for_multiple_objects,+)+from ...webhook.utils import filter_webhooks_for_channel, get_webhooks_for_event+from ..interface import VariantChannelStockInfo++if TYPE_CHECKING:+ from django.db.models import QuerySet++ from ...site.models import SiteSettings+ from ...webhook.models import Webhook+++T_REQUESTOR = User | App | None+++def _build_legacy_payload(stock_info: VariantChannelStockInfo) -> str:+ return json.dumps(+ {+ "product_variant_id": graphene.Node.to_global_id(+ "ProductVariant", stock_info.variant_id+ ),+ "channel": {"slug": stock_info.channel_slug},+ }+ )+++def _trigger(+ event_type: str,+ stock_infos: list[VariantChannelStockInfo],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR,+ webhooks: "QuerySet[Webhook] | None",+) -> None:+ # channel stock availability events are only triggered when legacy shipping+ # zone stock availability is disabled+ if site_settings.use_legacy_shipping_zone_stock_availability:+ return+ if not stock_infos:+ return+ if webhooks is None:+ webhooks = get_webhooks_for_event(event_type)++ stock_infos_by_channel: dict[str, list[VariantChannelStockInfo]] = defaultdict(list)+ for stock_info in stock_infos:+ stock_infos_by_channel[stock_info.channel_slug].append(stock_info)++ for channel_slug, channel_stock_infos in stock_infos_by_channel.items():+ channel_webhooks = filter_webhooks_for_channel(webhooks, channel_slug)+ if not channel_webhooks:+ continue+ trigger_webhooks_async_for_multiple_objects(+ event_type=event_type,+ webhooks=channel_webhooks,+ webhook_payloads_data=[+ WebhookPayloadData(+ subscribable_object=stock_info,+ legacy_data_generator=partial(_build_legacy_payload, stock_info),+ )+ for stock_info in channel_stock_infos+ ],+ requestor=requestor,+ )+++def trigger_product_variant_out_of_stock_in_channel(+ stock_infos: list[VariantChannelStockInfo],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR = None,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+ stock_infos,+ site_settings,+ requestor,+ webhooks,+ )+++def trigger_product_variant_back_in_stock_in_channel(+ stock_infos: list[VariantChannelStockInfo],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR = None,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL,+ stock_infos,+ site_settings,+ requestor,+ webhooks,+ )+++def trigger_product_variant_out_of_stock_for_click_and_collect(+ stock_infos: list[VariantChannelStockInfo],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR = None,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT,+ stock_infos,+ site_settings,+ requestor,+ webhooks,+ )+++def trigger_product_variant_back_in_stock_for_click_and_collect(+ stock_infos: list[VariantChannelStockInfo],+ site_settings: "SiteSettings",+ requestor: T_REQUESTOR = None,+ webhooks: "QuerySet[Webhook] | None" = None,+) -> None:+ _trigger(+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT,+ stock_infos,+ site_settings,+ requestor,+ webhooks,+ )diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 3a8df42377..46ab1d9cc5 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -138,12 +138,22 @@ class WebhookEventAsyncType:PRODUCT_VARIANT_UPDATED = "product_variant_updated"PRODUCT_VARIANT_DELETED = "product_variant_deleted"PRODUCT_VARIANT_METADATA_UPDATED = "product_variant_metadata_updated"+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED = (+ "product_variant_discounted_price_updated"+ )PRODUCT_VARIANT_OUT_OF_STOCK = "product_variant_out_of_stock"PRODUCT_VARIANT_BACK_IN_STOCK = "product_variant_back_in_stock"PRODUCT_VARIANT_STOCK_UPDATED = "product_variant_stock_updated"- PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED = (- "product_variant_discounted_price_updated"+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL = "product_variant_out_of_stock_in_channel"+ PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL = (+ "product_variant_back_in_stock_in_channel"+ )+ PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT = (+ "product_variant_out_of_stock_for_click_and_collect"+ )+ PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT = (+ "product_variant_back_in_stock_for_click_and_collect")CHECKOUT_CREATED = "checkout_created"@@ -617,6 +627,26 @@ class WebhookEventAsyncType:"name": "Product variant stock updated","permission": ProductPermissions.MANAGE_PRODUCTS,},+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL: {+ "name": "Product variant out of stock in channel",+ "permission": ProductPermissions.MANAGE_PRODUCTS,+ "is_deferred_payload": True,+ },+ PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL: {+ "name": "Product variant back in stock in channel",+ "permission": ProductPermissions.MANAGE_PRODUCTS,+ "is_deferred_payload": True,+ },+ PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT: {+ "name": "Product variant out of stock for click and collect",+ "permission": ProductPermissions.MANAGE_PRODUCTS,+ "is_deferred_payload": True,+ },+ PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT: {+ "name": "Product variant back in stock for click and collect",+ "permission": ProductPermissions.MANAGE_PRODUCTS,+ "is_deferred_payload": True,+ },PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED: {"name": "Product variant discounted price updated","permission": ProductPermissions.MANAGE_PRODUCTS,diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex d959faa0ab..ca201167c6 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -327,7 +327,7 @@ def test_generate_order_payload_no_user_email_but_user_set(assert payload["user_email"] == order.user.email-def test_generate_fulfillment_lines_payload(order_with_lines):+def test_generate_fulfillment_lines_payload(order_with_lines, site_settings):fulfillment = order_with_lines.fulfillments.create(tracking_number="123")line = order_with_lines.lines.first()line.sale_id = graphene.Node.to_global_id("Sale", 1)@@ -340,6 +340,7 @@ def test_generate_fulfillment_lines_payload(order_with_lines):)fulfill_order_lines([OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],+ site_settings=site_settings,requestor=None,)payload = json.loads(generate_fulfillment_lines_payload(fulfillment))[0]@@ -379,7 +380,9 @@ def test_generate_fulfillment_lines_payload(order_with_lines):}-def test_generate_fulfillment_lines_payload_deleted_variant(order_with_lines):+def test_generate_fulfillment_lines_payload_deleted_variant(+ order_with_lines, site_settings+):# givenfulfillment = order_with_lines.fulfillments.create(tracking_number="123")line = order_with_lines.lines.first()@@ -388,6 +391,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)],+ site_settings=site_settings,requestor=None,)diff --git a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.pyindex d8e67cf55f..84c1338da4 100644--- a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py+++ b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py@@ -16,6 +16,10 @@ from .....core import EventDeliveryStatusfrom .....core.models import EventDeliveryfrom .....core.telemetry import get_task_contextfrom .....product.interface import VariantDiscountedPriceChange+from .....warehouse.interface import VariantChannelStockInfo+from .....warehouse.tests.webhooks.subscriptions.test_channel_stock_events import (+ PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,+)from ....event_types import WebhookEventAsyncTypefrom ....tests.subscription_webhooks.subscription_queries import (PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED,@@ -472,6 +476,109 @@ def test_generate_deferred_payload_with_dataclass(assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk+ "saleor.webhook.transport.asynchronous.transport"+ ".generate_deferred_payloads.apply_async"+)+def test_call_trigger_webhook_async_deferred_payload_with_variant_channel_stock_info(+ mocked_generate_deferred_payloads,+ variant,+ channel_USD,+ subscription_webhook,+ staff_user,+):+ # given+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL+ webhook = subscription_webhook(PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL, event_type)+ webhooks = get_webhooks_for_event(event_type)++ stock_info = VariantChannelStockInfo(+ variant_id=variant.id, channel_slug=channel_USD.slug+ )++ # when+ trigger_webhooks_async(+ data=None,+ event_type=event_type,+ webhooks=webhooks,+ subscribable_object=stock_info,+ requestor=staff_user,+ )++ # then+ delivery = webhook.eventdelivery_set.first()+ call_kwargs = mocked_generate_deferred_payloads.call_args.kwargs+ deferred_payload_data = call_kwargs["kwargs"]["deferred_payload_data"]++ assert deferred_payload_data["model_name"] is None+ assert deferred_payload_data["object_id"] is None+ assert deferred_payload_data["subscribable_object_data"] == {+ "variant_id": variant.id,+ "channel_slug": channel_USD.slug,+ }+ assert deferred_payload_data["requestor_model_name"] == "account.user"+ assert deferred_payload_data["requestor_object_id"] == staff_user.pk+ assert call_kwargs["kwargs"]["event_delivery_ids"] == [delivery.id]++ assert delivery.event_type == event_type+ assert delivery.payload is None+ assert delivery.webhook == webhook+++ "saleor.webhook.transport.asynchronous.transport"+ ".send_webhook_request_async.apply_async"+)+def test_generate_deferred_payload_with_variant_channel_stock_info(+ mocked_send_webhook_request_async,+ variant,+ channel_USD,+ subscription_webhook,+ staff_user,+):+ # given+ variant_global_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL++ webhook = subscription_webhook(PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL, event_type)++ deferred_payload_data = DeferredPayloadData(+ subscribable_object_data={+ "variant_id": variant.id,+ "channel_slug": channel_USD.slug,+ },+ requestor_model_name="account.user",+ requestor_object_id=staff_user.pk,+ request_time=None,+ )+ delivery = EventDelivery(+ event_type=event_type,+ webhook=webhook,+ status=EventDeliveryStatus.PENDING,+ )+ delivery.save()++ # when+ generate_deferred_payloads(+ event_delivery_ids=[delivery.pk],+ deferred_payload_data=asdict(deferred_payload_data),+ )++ # then+ delivery.refresh_from_db()+ assert delivery.payload++ payload = json.loads(delivery.payload.get_payload())+ assert payload == {+ "productVariant": {"id": variant_global_id},+ "channel": {"slug": channel_USD.slug},+ }++ assert mocked_send_webhook_request_async.call_count == 1+ call_kwargs = mocked_send_webhook_request_async.call_args.kwargs+ assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk++def test_reconstruct_subscribable_object_with_invalid_data():# givenevent_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATEDdiff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.pyindex a774034d14..dd95a9224c 100644--- a/saleor/webhook/transport/utils.py+++ b/saleor/webhook/transport/utils.py@@ -41,6 +41,7 @@ from ...core.utils import build_absolute_urifrom ...core.utils.json_serializer import CustomJsonEncoderfrom ...core.utils.url import sanitize_url_for_loggingfrom ...product.interface import VariantDiscountedPriceChange+from ...warehouse.interface import VariantChannelStockInfofrom .. import observabilityfrom ..const import APP_ID_PREFIXfrom ..event_types import WebhookEventAsyncType@@ -108,6 +109,18 @@ DEFERRED_SUBSCRIBABLE_OBJECT_MAP: dict[str, type] = {WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED: (VariantDiscountedPriceChange),+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL: (+ VariantChannelStockInfo+ ),+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL: (+ VariantChannelStockInfo+ ),+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT: (+ VariantChannelStockInfo+ ),+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT: (+ VariantChannelStockInfo+ ),}diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.pyindex 6471454162..a5efd313dc 100644--- a/saleor/webhook/utils.py+++ b/saleor/webhook/utils.py@@ -152,3 +152,26 @@ def calculate_webhooks_for_multiple_events(if event not in active_event_map:active_event_map[event] = set()return active_event_map+++def filter_webhooks_for_channel(+ webhooks: Iterable[Webhook],+ channel_slug: str,+) -> list[Webhook]:+ """Return webhooks whose subscription query allows the given channel.++ Webhooks without a subscription query, or whose subscription query has no+ channel filter, are passed through unchanged.+ """+ filtered: list[Webhook] = []+ for webhook in webhooks:+ if not webhook.subscription_query:+ filtered.append(webhook)+ continue+ filterable_channel_slugs = list(webhook.filterable_channel_slugs)+ if not filterable_channel_slugs:+ filtered.append(webhook)+ continue+ if channel_slug in filterable_channel_slugs:+ filtered.append(webhook)+ return filtered