Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix empty sync webhooks for Order type (#16466)
Maciej Korycinskif4596c84f21f
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.pyindex 1f1924cef2..f68dc135d3 100644--- a/saleor/checkout/actions.py+++ b/saleor/checkout/actions.py@@ -5,7 +5,10 @@ from typing import TYPE_CHECKING, Callable, Optional, castfrom django.utils import timezone-from ..core.utils.events import call_event_including_protected_events+from ..core.utils.events import (+ call_event_including_protected_events,+ webhook_async_event_requires_sync_webhooks_to_trigger,+)from ..payment.models import TransactionItemfrom ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ..webhook.utils import get_webhooks_for_multiple_events@@ -26,26 +29,6 @@ if TYPE_CHECKING:from ..webhook.models import Webhook-def checkout_event_requires_sync_webhooks_to_trigger(- event_name: str, webhook_event_map: dict[str, set["Webhook"]]-) -> bool:- """Check if calling the event requires additional actions.-- In case of having active webhook with the `event_name`, the function will return- True, when any sync checkout's webhooks are active. `True` means that sync webhook- should be triggered first, before calling async webhook.- """-- if event_name not in webhook_event_map:- return False-- if not set(WebhookEventSyncType.CHECKOUT_EVENTS).intersection(- webhook_event_map.keys()- ):- return False- return True--def call_checkout_event_for_checkout(manager: "PluginsManager",event_func: Callable,@@ -55,8 +38,10 @@ def call_checkout_event_for_checkout(webhook_event_map = get_webhooks_for_multiple_events([event_name, *WebhookEventSyncType.CHECKOUT_EVENTS])- if not checkout_event_requires_sync_webhooks_to_trigger(- event_name, webhook_event_map+ if not webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name,+ webhook_event_map,+ possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,):call_event_including_protected_events(event_func, checkout)return@@ -97,8 +82,10 @@ def call_checkout_event_for_checkout_info(# No need to trigger additional sync webhook when we don't have active webhook or# we don't have active sync checkout webhooks- if not checkout_event_requires_sync_webhooks_to_trigger(- event_name, webhook_event_map+ if not webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name,+ webhook_event_map,+ possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,):call_event_including_protected_events(event_func, checkout)return Nonediff --git a/saleor/core/utils/events.py b/saleor/core/utils/events.pyindex b9e82d8ad5..9fe55bb1df 100644--- a/saleor/core/utils/events.py+++ b/saleor/core/utils/events.py@@ -2,6 +2,49 @@ from django.db import transactionfrom ...checkout.fetch import CheckoutInfofrom ...checkout.models import Checkout+from ...order.fetch import OrderInfo+from ...order.models import Order+from ...webhook.event_types import WebhookEventAsyncType+from ...webhook.models import Webhook+++def webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name: str,+ webhook_event_map: dict[str, set["Webhook"]],+ possible_sync_events: list[str],+) -> bool:+ """Check if calling the event requires additional actions.++ In case of having active webhook with the `event_name`, the function will return+ True, when any sync from `possible_sync_events`'s webhooks are active. `True`+ means that sync webhook should be triggered first, before calling async webhook.+ """+ is_async_event = event_name in WebhookEventAsyncType.ALL+ if not is_async_event:+ raise ValueError(f"Event {event_name} is not an async event.")++ if event_name not in webhook_event_map:+ raise ValueError(f"Event {event_name} not found in webhook_event_map.")++ missing_possible_sync_events_in_map = set(possible_sync_events).difference(+ webhook_event_map.keys()+ )+ if missing_possible_sync_events_in_map:+ raise ValueError(+ f"Event {missing_possible_sync_events_in_map} not found in webhook_event_map."+ )++ if not webhook_event_map[event_name] and not webhook_event_map.get(+ WebhookEventAsyncType.ANY+ ):+ return False++ active_webhook_events = set(+ [event for event, webhooks in webhook_event_map.items() if webhooks]+ )+ if not active_webhook_events.intersection(possible_sync_events):+ return False+ return Truedef call_event_including_protected_events(func_obj, *func_args, **func_kwargs):@@ -23,10 +66,16 @@ def call_event(func_obj, *func_args, **func_kwargs):Ensures that in atomic transaction event is called on_commit."""- is_checkout_instance = any(- [isinstance(arg, (Checkout, CheckoutInfo)) for arg in func_args]+ is_protected_instance = any(+ [+ isinstance(arg, (Checkout, CheckoutInfo, Order, OrderInfo))+ for arg in func_args+ ])-- if is_checkout_instance:+ func_obj_self = getattr(func_obj, "__self__", None)+ is_plugin_manager_method = "PluginsManager" in str(+ getattr(func_obj_self, "__class__", "")+ )+ if is_protected_instance and is_plugin_manager_method:raise NotImplementedError("`call_event` doesn't support checkout/order events.")call_event_including_protected_events(func_obj, *func_args, **func_kwargs)diff --git a/saleor/core/utils/tests/test_events.py b/saleor/core/utils/tests/test_events.pyindex 580dec8487..e154214df6 100644--- a/saleor/core/utils/tests/test_events.py+++ b/saleor/core/utils/tests/test_events.py@@ -1,6 +1,8 @@import pytest-from ..events import call_event+from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ....webhook.utils import get_webhooks_for_multiple_events+from ..events import call_event, webhook_async_event_requires_sync_webhooks_to_triggerdef test_call_event_cannot_be_used_with_checkout_info_object(@@ -13,3 +15,68 @@ def test_call_event_cannot_be_used_with_checkout_info_object(def test_call_event_cannot_be_used_with_checkout_object(checkout, plugins_manager):with pytest.raises(NotImplementedError):call_event(plugins_manager.checkout_updated, checkout)+++def test_webhook_async_event_requires_sync_webhooks_to_trigger_requires_event_in_map():+ # given+ event_name = WebhookEventAsyncType.ORDER_CREATED+ webhook_event_map = {}++ # when & then+ with pytest.raises(+ ValueError, match=f"Event {event_name} not found in webhook_event_map."+ ):+ webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name, webhook_event_map, []+ )+++def test_webhook_async_event_requires_sync_webhooks_to_trigger_not_async_event():+ # given+ event_name = WebhookEventSyncType.ORDER_CALCULATE_TAXES+ webhook_event_map = {}++ # when & then+ with pytest.raises(ValueError, match=f"Event {event_name} is not an async event."):+ webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name, webhook_event_map, []+ )+++def test_webhook_async_event_requires_sync_webhooks_to_trigger():+ # given+ event_name = WebhookEventAsyncType.ORDER_CREATED+ webhook_event_map = get_webhooks_for_multiple_events(+ [WebhookEventAsyncType.ORDER_CREATED, *WebhookEventSyncType.ORDER_EVENTS]+ )++ # when++ should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name, webhook_event_map, WebhookEventSyncType.ORDER_EVENTS+ )++ # then+ assert not should_trigger+++def test_webhook_async_event_requires_sync_webhooks_to_trigger_missing_event_in_map():+ # given+ event_name = WebhookEventAsyncType.ORDER_CREATED+ webhook_event_map = get_webhooks_for_multiple_events(+ [+ WebhookEventAsyncType.ORDER_CREATED,+ ]+ )++ # when & then+ with pytest.raises(+ ValueError,+ match=(+ f"Event {set(WebhookEventSyncType.ORDER_EVENTS)} not found in "+ "webhook_event_map."+ ),+ ):+ webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name, webhook_event_map, WebhookEventSyncType.ORDER_EVENTS+ )diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.pyindex ec44e7c982..b12e869539 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py@@ -1551,7 +1551,7 @@ def test_with_active_problems_flow("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_add_voucher_triggers_sync_webhooks(+def test_checkout_add_voucher_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.pyindex 09a971a131..ba98b16b49 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py@@ -654,7 +654,7 @@ def test_checkout_billing_address_skip_validation_by_app("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_billing_address_triggers_sync_webhooks(+def test_checkout_billing_address_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.pyindex 82f67cb2d1..388faf6c69 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py@@ -68,7 +68,7 @@ MUTATION_CHECKOUT_CREATE = """@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")-def test_checkout_create_triggers_webhooks(+def test_checkout_create_triggers_async_webhooks(mocked_webhook_trigger,mocked_get_webhooks_for_event,any_webhook,@@ -2656,7 +2656,7 @@ def test_checkout_create_skip_validation_billing_address_by_app("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_create_triggers_sync_webhooks(+def test_checkout_create_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.pyindex db8946de81..b0a55e3cbc 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py@@ -244,7 +244,7 @@ def test_with_active_problems_flow(user_api_client, checkout_with_problems):"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_customer_triggers_sync_webhooks(+def test_checkout_customer_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.pyindex 5635ed3e06..52a3567176 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py@@ -123,7 +123,7 @@ def test_with_active_problems_flow(user_api_client, checkout_with_problems):"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_customer_detach_triggers_sync_webhooks(+def test_checkout_customer_detach_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.pyindex d351a0dc15..1f1d494bb7 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py@@ -85,7 +85,7 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_customer_note_update_triggers_sync_webhooks(+def test_checkout_customer_note_update_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.pyindex 6fe2fb2ff5..d7b34621da 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py@@ -1017,7 +1017,7 @@ def test_checkout_delivery_method_update_from_cc_to_all_warehouses_disabled_cc("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_delivery_method_update_triggers_sync_webhooks(+def test_checkout_delivery_method_update_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,@@ -1093,7 +1093,7 @@ def test_checkout_delivery_method_update_triggers_sync_webhooks("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_delivery_method_update_cc_triggers_sync_webhooks(+def test_checkout_delivery_method_update_cc_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,@@ -1180,7 +1180,7 @@ def test_checkout_delivery_method_update_cc_triggers_sync_webhooks("saleor.graphql.checkout.mutations.checkout_delivery_method_update.""clean_delivery_method")-def test_checkout_delivery_method_update_external_shipping_triggers_sync_webhooks(+def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(mock_clean_delivery,mocked_send_webhook_request_async,mocked_send_webhook_request_sync,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.pyindex b8fdb9a8d6..a34966feb3 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py@@ -96,7 +96,7 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_email_update_triggers_sync_webhooks(+def test_checkout_email_update_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.pyindex 03c1268fa4..61e959b2d8 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py@@ -79,7 +79,7 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_update_language_code_triggers_sync_webhooks(+def test_checkout_update_language_code_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.pyindex cdc177e1bc..9cede21b29 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py@@ -214,7 +214,7 @@ def test_checkout_line_delete_non_removable_gift(user_api_client, checkout_line)"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_line_delete_triggers_sync_webhooks(+def test_checkout_line_delete_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex 9ebf8b44f5..3bf0c415be 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -1764,7 +1764,7 @@ def test_with_active_problems_flow("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_lines_add_triggers_sync_webhooks(+def test_checkout_lines_add_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.pyindex d23fd4832f..d0d729b9f3 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py@@ -211,7 +211,7 @@ def test_checkout_lines_delete_not_associated_with_checkout("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_lines_delete_triggers_sync_webhooks(+def test_checkout_lines_delete_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex 50bde58189..69a556da4a 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -1371,7 +1371,7 @@ def test_checkout_lines_update_quantity_gift(user_api_client, checkout_with_item"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_lines_update_triggers_sync_webhooks(+def test_checkout_lines_update_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.pyindex 6f471d45af..5f4ad5181f 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py@@ -716,7 +716,7 @@ def test_with_active_problems_flow("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_remove_triggers_sync_webhooks(+def test_checkout_remove_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.pyindex 8bbc22942f..9e52bf1f35 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py@@ -1086,7 +1086,7 @@ def test_checkout_shipping_address_skip_validation_by_app("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_shipping_address_update_triggers_sync_webhooks(+def test_checkout_shipping_address_update_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.pyindex 820449564a..4dbc711e24 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py@@ -487,7 +487,7 @@ def test_with_active_problems_flow("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_shipping_method_update_triggers_sync_webhooks(+def test_checkout_shipping_method_update_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,@@ -564,7 +564,7 @@ def test_checkout_shipping_method_update_triggers_sync_webhooks("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_shipping_method_update_external_shipping_triggers_sync_webhooks(+def test_checkout_shipping_method_update_external_shipping_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,@@ -655,7 +655,7 @@ def test_checkout_shipping_method_update_external_shipping_triggers_sync_webhook"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_checkout_shipping_method_update_to_none_triggers_sync_webhooks(+def test_checkout_shipping_method_update_to_none_triggers_webhooks(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/meta/extra_methods.py b/saleor/graphql/meta/extra_methods.pyindex 94aa4ee862..8653cfe1b0 100644--- a/saleor/graphql/meta/extra_methods.py+++ b/saleor/graphql/meta/extra_methods.py@@ -1,8 +1,7 @@-from ...checkout.actions import (- call_checkout_event_for_checkout_info,- checkout_event_requires_sync_webhooks_to_trigger,-)+from ...checkout.actions import call_checkout_event_for_checkout_infofrom ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ...core.utils.events import webhook_async_event_requires_sync_webhooks_to_trigger+from ...order.actions import call_order_eventfrom ...product.models import Product, ProductVariantfrom ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ...webhook.utils import get_webhooks_for_multiple_events@@ -21,10 +20,14 @@ def extra_checkout_actions(instance, info: ResolveInfo, **data):)# In case of having any active combination of async/sync webhooks for these events# we need to fetch checkout lines and checkout info to call sync webhook first.- if checkout_event_requires_sync_webhooks_to_trigger(- WebhookEventAsyncType.CHECKOUT_UPDATED, webhook_event_map- ) or checkout_event_requires_sync_webhooks_to_trigger(- WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED, webhook_event_map+ if webhook_async_event_requires_sync_webhooks_to_trigger(+ WebhookEventAsyncType.CHECKOUT_UPDATED,+ webhook_event_map,+ possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,+ ) or webhook_async_event_requires_sync_webhooks_to_trigger(+ WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED,+ webhook_event_map,+ possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,):lines_info, _ = fetch_checkout_lines(instance,@@ -77,7 +80,12 @@ def extra_gift_card_actions(instance, info: ResolveInfo, **data):def extra_order_actions(instance, info: ResolveInfo, **data):manager = get_plugin_manager_promise(info.context).get()- manager.order_metadata_updated(instance)+ call_order_event(+ manager,+ manager.order_metadata_updated,+ WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ instance,+ )def extra_product_actions(instance, info: ResolveInfo, **data):diff --git a/saleor/graphql/meta/tests/mutations/test_checkout.py b/saleor/graphql/meta/tests/mutations/test_checkout.pyindex 276c64324e..b3a7ea1f72 100644--- a/saleor/graphql/meta/tests/mutations/test_checkout.py+++ b/saleor/graphql/meta/tests/mutations/test_checkout.py@@ -372,7 +372,7 @@ def test_update_public_metadata_for_checkout_line(api_client, checkout_line):"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_add_metadata_for_checkout_triggers_sync_webhooks_with_checkout_updated(+def test_add_metadata_for_checkout_triggers_webhooks_with_checkout_updated(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,@@ -442,7 +442,7 @@ def test_add_metadata_for_checkout_triggers_sync_webhooks_with_checkout_updated("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])-def test_add_metadata_for_checkout_triggers_sync_webhooks_with_updated_metadata(+def test_add_metadata_for_checkout_triggers_webhooks_with_updated_metadata(mocked_send_webhook_request_async,mocked_send_webhook_request_sync,wrapped_call_checkout_event_for_checkout,diff --git a/saleor/graphql/meta/tests/mutations/test_order.py b/saleor/graphql/meta/tests/mutations/test_order.pyindex 08d08c57c8..6d0bb4a418 100644--- a/saleor/graphql/meta/tests/mutations/test_order.py+++ b/saleor/graphql/meta/tests/mutations/test_order.py@@ -1,6 +1,13 @@+from unittest.mock import call, patch+import graphene+from django.test import override_settings+from .....core.models import EventDelivery+from .....order import OrderStatus+from .....order.actions import call_order_eventfrom .....payment.models import TransactionItem+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUEfrom .test_delete_metadata import (execute_clear_public_metadata_for_item,@@ -578,3 +585,142 @@ def test_add_private_metadata_for_fulfillment(assert item_contains_proper_private_metadata(response["data"]["updatePrivateMetadata"]["item"], fulfillment, fulfillment_id)+++@patch(+ "saleor.graphql.meta.extra_methods.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_change_in_public_metadata_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ api_client,+ order_with_lines,+ django_capture_on_commit_callbacks,+ settings,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks([WebhookEventAsyncType.ORDER_METADATA_UPDATED])++ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ order_id = graphene.Node.to_global_id("Order", order.pk)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ execute_update_public_metadata_for_item(+ api_client, None, order_id, "Order", key="new-key"+ )++ # then+ order_metadata_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_metadata_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )++ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.called+++@patch(+ "saleor.graphql.meta.extra_methods.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_change_in_private_metadata_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ django_capture_on_commit_callbacks,+ settings,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks([WebhookEventAsyncType.ORDER_METADATA_UPDATED])++ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ order_id = graphene.Node.to_global_id("Order", order.pk)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ execute_update_private_metadata_for_item(+ staff_api_client, permission_manage_orders, order_id, "Order", key="new-key"+ )++ # then+ order_metadata_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_metadata_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )++ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py b/saleor/graphql/order/bulk_mutations/order_bulk_cancel.pyindex 50018a0afc..952f92a1fd 100644--- a/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py+++ b/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py@@ -5,10 +5,9 @@ from uuid import UUIDimport graphenefrom ....order import models-from ....order.actions import cancel_order+from ....order.actions import WEBHOOK_EVENTS_FOR_ORDER_CANCELED, cancel_orderfrom ....permission.enums import OrderPermissions-from ....webhook.event_types import WebhookEventAsyncType-from ....webhook.utils import get_webhooks_for_event+from ....webhook.utils import get_webhooks_for_multiple_eventsfrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.mutations import BaseBulkWithRestrictedChannelAccessMutation@@ -38,10 +37,9 @@ class OrderBulkCancel(BaseBulkWithRestrictedChannelAccessMutation):@classmethoddef bulk_action(cls, info: ResolveInfo, queryset, /) -> None:- webhooks_cancelled = get_webhooks_for_event(- WebhookEventAsyncType.ORDER_CANCELLED+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED)- webhooks_updated = get_webhooks_for_event(WebhookEventAsyncType.ORDER_UPDATED)manager = get_plugin_manager_promise(info.context).get()for order in queryset:cancel_order(@@ -49,8 +47,7 @@ class OrderBulkCancel(BaseBulkWithRestrictedChannelAccessMutation):user=info.context.user,app=get_app_promise(info.context).get(),manager=manager,- webhooks_cancelled=webhooks_cancelled,- webhooks_updated=webhooks_updated,+ webhook_event_map=webhook_event_map,)@classmethoddiff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 19ed9c0db7..5eb31aab08 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -16,6 +16,7 @@ from ....discount.utils.voucher import (increase_voucher_usage,)from ....order import OrderOrigin, OrderStatus, events, models+from ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCodefrom ....order.search import update_order_search_vectorfrom ....order.utils import (@@ -26,6 +27,7 @@ from ....order.utils import ()from ....permission.enums import OrderPermissionsfrom ....shipping.utils import convert_to_shipping_method_data+from ....webhook.event_types import WebhookEventAsyncTypefrom ...account.i18n import I18nMixinfrom ...account.mixins import AddressMetadataMixinfrom ...account.types import AddressInput@@ -574,12 +576,6 @@ class DraftOrderCreate(update_order_display_gross_prices(instance)- if is_new_instance:- cls.call_event(manager.draft_order_created, instance)-- else:- cls.call_event(manager.draft_order_updated, instance)-# Post-process the resultsupdated_fields.extend([@@ -596,6 +592,20 @@ class DraftOrderCreate(update_order_search_vector(instance, save=False)instance.save(update_fields=updated_fields)+ if is_new_instance:+ call_order_event(+ manager,+ manager.draft_order_created,+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,+ instance,+ )+ else:+ call_order_event(+ manager,+ manager.draft_order_updated,+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,+ instance,+ )@classmethoddef handle_order_voucher(cls, cleaned_input, instance, voucher):diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.pyindex 3e607a7aae..d89d77e2b0 100644--- a/saleor/graphql/order/mutations/draft_order_delete.py+++ b/saleor/graphql/order/mutations/draft_order_delete.py@@ -5,8 +5,10 @@ from ....core.tracing import traced_atomic_transactionfrom ....discount.models import VoucherCodefrom ....discount.utils.voucher import release_voucher_code_usagefrom ....order import OrderStatus, models+from ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCodefrom ....permission.enums import OrderPermissions+from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_310from ...core.mutations import (@@ -54,7 +56,12 @@ class DraftOrderDelete(manager = get_plugin_manager_promise(info.context).get()with traced_atomic_transaction():response = super().perform_mutation(_root, info, **data)- cls.call_event(manager.draft_order_deleted, order)+ call_order_event(+ manager,+ manager.draft_order_deleted,+ WebhookEventAsyncType.DRAFT_ORDER_DELETED,+ order,+ )return response@classmethoddiff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.pyindex bc502931bb..6aba2990b8 100644--- a/saleor/graphql/order/mutations/order_confirm.py+++ b/saleor/graphql/order/mutations/order_confirm.py@@ -7,12 +7,18 @@ from django.db import transactionfrom ....account.models import Userfrom ....core.tracing import traced_atomic_transactionfrom ....order import OrderStatus, models-from ....order.actions import order_charged, order_confirmed+from ....order.actions import (+ WEBHOOK_EVENTS_FOR_ORDER_CHARGED,+ WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED,+ order_charged,+ order_confirmed,+)from ....order.error_codes import OrderErrorCodefrom ....order.fetch import fetch_order_infofrom ....order.utils import update_order_display_gross_pricesfrom ....payment import gatewayfrom ....permission.enums import OrderPermissions+from ....webhook.utils import get_webhooks_for_multiple_eventsfrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.mutations import ModelMutation@@ -73,11 +79,15 @@ class OrderConfirm(ModelMutation):payment = order_info.paymentmanager = get_plugin_manager_promise(info.context).get()app = get_app_promise(info.context).get()+ webhook_events = WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED+ webhook_event_map = Nonewith traced_atomic_transaction():if payment and payment.is_authorized and payment.can_capture():authorized_payment = paymentgateway.capture(payment, manager, channel_slug=order.channel.slug)site = get_site_promise(info.context).get()+ webhook_events = webhook_events.union(WEBHOOK_EVENTS_FOR_ORDER_CHARGED)+ webhook_event_map = get_webhooks_for_multiple_events(webhook_events)transaction.on_commit(lambda: order_charged(order_info,@@ -88,8 +98,12 @@ class OrderConfirm(ModelMutation):manager,site.settings,payment.gateway,+ webhook_event_map=webhook_event_map,))+ if webhook_event_map is None:+ webhook_event_map = get_webhooks_for_multiple_events(webhook_events)+transaction.on_commit(lambda: order_confirmed(order,@@ -97,6 +111,7 @@ class OrderConfirm(ModelMutation):app,manager,send_confirmation_email=True,+ webhook_event_map=webhook_event_map,))return OrderConfirm(order=order)diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.pyindex f8e8804f98..1d821f0337 100644--- a/saleor/graphql/order/mutations/order_line_delete.py+++ b/saleor/graphql/order/mutations/order_line_delete.py@@ -20,7 +20,7 @@ from ...core.types import OrderErrorfrom ...core.utils import raise_validation_errorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order, OrderLine-from .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status+from .utils import EditableOrderValidationMixin, call_event_by_order_statusclass OrderLineDelete(EditableOrderValidationMixin, BaseMutation):@@ -98,8 +98,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):["should_refresh_prices", "weight", "search_vector", "updated_at"])order.save(update_fields=updated_fields)- func = get_webhook_handler_by_order_status(order.status, manager)- cls.call_event(func, order)+ call_event_by_order_status(order, manager)return OrderLineDelete(order=order, order_line=line)@classmethoddiff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex 162c1add81..808868744c 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -19,7 +19,7 @@ from ...core.types import OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order, OrderLinefrom .draft_order_create import OrderLineInput-from .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status+from .utils import EditableOrderValidationMixin, call_event_by_order_statusclass OrderLineUpdate(@@ -106,8 +106,7 @@ class OrderLineUpdate(recalculate_order_weight(instance.order)instance.order.save(update_fields=["should_refresh_prices", "weight"])- func = get_webhook_handler_by_order_status(instance.order.status, manager)- cls.call_event(func, instance.order)+ call_event_by_order_status(instance.order, manager)@classmethoddef success_response(cls, instance):diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.pyindex c9d02737bd..644ecd019f 100644--- a/saleor/graphql/order/mutations/order_lines_create.py+++ b/saleor/graphql/order/mutations/order_lines_create.py@@ -31,8 +31,8 @@ from ..utils import (from .draft_order_create import OrderLineCreateInputfrom .utils import (EditableOrderValidationMixin,+ call_event_by_order_status,get_variant_rule_info_map,- get_webhook_handler_by_order_status,)VariantData = namedtuple("VariantData", ["variant", "rules_info"])@@ -204,8 +204,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):"updated_at",])- func = get_webhook_handler_by_order_status(order.status, manager)- cls.call_event(func, order)+ call_event_by_order_status(order, manager)return OrderLinesCreate(order=order, order_lines=added_lines)diff --git a/saleor/graphql/order/mutations/order_note_add.py b/saleor/graphql/order/mutations/order_note_add.pyindex ca42ffd19e..a05445ffb7 100644--- a/saleor/graphql/order/mutations/order_note_add.py+++ b/saleor/graphql/order/mutations/order_note_add.py@@ -16,7 +16,7 @@ from ...core.types import BaseInputObjectType, Error, OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order, OrderEventfrom .order_note_common import OrderNoteCommon-from .utils import get_webhook_handler_by_order_status+from .utils import call_event_by_order_statusOrderNoteAddErrorCode = graphene.Enum.from_enum(error_codes.OrderNoteAddErrorCode)OrderNoteAddErrorCode.doc_category = DOC_CATEGORY_ORDERS@@ -62,8 +62,7 @@ class OrderNoteAdd(OrderNoteCommon):app=app,message=cleaned_input["message"],)- func = get_webhook_handler_by_order_status(order.status, manager)- cls.call_event(func, order)+ call_event_by_order_status(order, manager)return OrderNoteAdd(order=order, event=event)diff --git a/saleor/graphql/order/mutations/order_note_update.py b/saleor/graphql/order/mutations/order_note_update.pyindex d66d403aeb..9f37bee463 100644--- a/saleor/graphql/order/mutations/order_note_update.py+++ b/saleor/graphql/order/mutations/order_note_update.py@@ -11,7 +11,7 @@ from ...core.types import Errorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order, OrderEventfrom .order_note_common import OrderNoteCommon-from .utils import get_webhook_handler_by_order_status+from .utils import call_event_by_order_statusOrderNoteUpdateErrorCode = graphene.Enum.from_enum(error_codes.OrderNoteUpdateErrorCode)OrderNoteUpdateErrorCode.doc_category = DOC_CATEGORY_ORDERS@@ -63,6 +63,5 @@ class OrderNoteUpdate(OrderNoteCommon):message=cleaned_input["message"],related_event=order_event_to_update,)- func = get_webhook_handler_by_order_status(order.status, manager)- cls.call_event(func, order)+ call_event_by_order_status(order, manager)return OrderNoteUpdate(order=order, event=event)diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.pyindex 06012422d5..fafed8931a 100644--- a/saleor/graphql/order/mutations/order_update.py+++ b/saleor/graphql/order/mutations/order_update.py@@ -5,10 +5,12 @@ from ....account.models import Userfrom ....core.postgres import FlatConcatSearchVectorfrom ....core.tracing import traced_atomic_transactionfrom ....order import OrderStatus, models+from ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCodefrom ....order.search import prepare_order_search_vector_valuefrom ....order.utils import invalidate_order_pricesfrom ....permission.enums import OrderPermissions+from ....webhook.event_types import WebhookEventAsyncTypefrom ...account.types import AddressInputfrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_310@@ -105,4 +107,9 @@ class OrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):invalidate_order_prices(instance)instance.save()- cls.call_event(manager.order_updated, instance)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ instance,+ )diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.pyindex a6c3b11342..366021eb4c 100644--- a/saleor/graphql/order/mutations/order_update_shipping.py+++ b/saleor/graphql/order/mutations/order_update_shipping.py@@ -2,10 +2,12 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....order import OrderStatus, models+from ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCodefrom ....permission.enums import OrderPermissionsfrom ....shipping import models as shipping_modelsfrom ....shipping.utils import convert_to_shipping_method_data+from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.mutations import BaseMutation@@ -134,5 +136,7 @@ class OrderUpdateShipping(order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)# Post-process the results- cls.call_event(manager.order_updated, order)+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )return OrderUpdateShipping(order=order)diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.pyindex b0addd8f19..4d75e42f40 100644--- a/saleor/graphql/order/mutations/utils.py+++ b/saleor/graphql/order/mutations/utils.py@@ -9,6 +9,7 @@ from ....checkout.fetch import get_variant_channel_listingfrom ....core.taxes import zero_money, zero_taxed_moneyfrom ....discount.interface import fetch_variant_rules_infofrom ....order import ORDER_EDITABLE_STATUS, OrderStatus, events+from ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCodefrom ....order.utils import invalidate_order_pricesfrom ....payment import PaymentError@@ -17,6 +18,7 @@ from ....plugins.manager import PluginsManagerfrom ....product import models as product_modelsfrom ....shipping.interface import ShippingMethodDatafrom ....shipping.models import ShippingMethodChannelListing+from ....webhook.event_types import WebhookEventAsyncTypefrom ..utils import get_shipping_method_availability_errorSHIPPING_METHOD_UPDATE_FIELDS = [@@ -143,11 +145,18 @@ def clean_order_update_shipping(raise ValidationError({"shipping_method": error})-def get_webhook_handler_by_order_status(status, manager):- if status == OrderStatus.DRAFT:- return manager.draft_order_updated+def call_event_by_order_status(order, manager):+ if order.status == OrderStatus.DRAFT:+ call_order_event(+ manager,+ manager.draft_order_updated,+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,+ order,+ )else:- return manager.order_updated+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )def try_payment_action(order, user, app, payment, func, *args, **kwargs):diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex ce7a610e27..7e9d2e408a 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -1,6 +1,6 @@from datetime import datetime, timedeltafrom decimal import Decimal-from unittest.mock import patch+from unittest.mock import call, patchimport grapheneimport pytz@@ -17,6 +17,10 @@ from .....discount import DiscountValueTypefrom .....discount.models import VoucherCustomerfrom .....order import OrderOrigin, OrderStatusfrom .....order import events as order_events+from .....order.actions import (+ call_order_event,+ order_created,+)from .....order.calculations import fetch_order_prices_if_expiredfrom .....order.error_codes import OrderErrorCodefrom .....order.interface import OrderTaxedPricesData@@ -32,7 +36,7 @@ from .....plugins.webhook.conftest import ( # noqa: F401from .....product.models import ProductVariantfrom .....warehouse.models import Allocation, PreorderAllocation, Stockfrom .....warehouse.tests.utils import get_available_quantity_for_stock-from .....webhook.event_types import WebhookEventSyncType+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....payment.types import PaymentChargeStatusEnumfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -75,9 +79,14 @@ DRAFT_ORDER_COMPLETE_MUTATION = """"""+@patch(+ "saleor.graphql.order.mutations.draft_order_complete.order_created",+ wraps=order_created,+)@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_draft_order_complete(product_variant_out_of_stock_webhook_mock,+ order_created_mock,staff_api_client,permission_group_manage_orders,staff_user,@@ -128,6 +137,7 @@ def test_draft_order_complete(product_variant_out_of_stock_webhook_mock.assert_called_once_with(Stock.objects.last())+ assert order_created_mock.calleddef test_draft_order_complete_no_automatically_confirm_all_new_orders(@@ -1490,3 +1500,100 @@ def test_draft_order_complete_with_invalid_address(assert data["origin"] == OrderOrigin.DRAFT.upper()assert order.shipping_address.postal_code == wrong_postal_codeassert order.billing_address.postal_code == wrong_postal_code+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_draft_order_complete_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_group_manage_orders,+ draft_order,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_CREATED,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ ]+ )++ order = draft_order+ order.should_refresh_prices = True+ order.status = OrderStatus.DRAFT+ order.save()+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_COMPLETE_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["draftOrderComplete"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_confirmed_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CONFIRMED,+ )+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CREATED,+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ order_deliveries = [+ order_confirmed_delivery,+ order_updated_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex 6b2ce6a92b..41ed1679b6 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -1,25 +1,29 @@from datetime import datetime, timedeltafrom decimal import Decimal-from unittest.mock import Mock, patch+from unittest.mock import Mock, call, patchimport grapheneimport pytestimport pytz+from django.test import override_settingsfrom prices import Moneyfrom .....checkout import AddressType+from .....core.models import EventDeliveryfrom .....core.prices import quantize_pricefrom .....core.taxes import TaxError, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType, RewardType, RewardValueTypefrom .....discount.models import VoucherChannelListing, VoucherCode, VoucherCustomerfrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCodefrom .....order.models import Order, OrderEventfrom .....payment.model_helpers import get_subtotalfrom .....product.models import ProductVariantfrom .....tax import TaxCalculationStrategyfrom .....tests.utils import round_up+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentDRAFT_ORDER_CREATE_MUTATION = """@@ -3603,3 +3607,99 @@ def test_draft_order_create_voucher_with_usage_limit(assert not content["data"]["draftOrderCreate"]["errors"]data = content["data"]["draftOrderCreate"]["order"]assert data["voucherCode"] == code_1.code+++@patch(+ "saleor.graphql.order.mutations.draft_order_create.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_draft_order_create_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ app_api_client,+ permission_manage_orders,+ customer_user,+ shipping_method_channel_PLN,+ product_available_in_many_channels,+ channel_PLN,+ graphql_address_data,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ draft_order_created_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.DRAFT_ORDER_CREATED)++ variant = product_available_in_many_channels.variants.first()+ query = DRAFT_ORDER_CREATE_MUTATION++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variant_list = [+ {"variantId": variant_id, "quantity": 2},+ ]+ shipping_address = graphql_address_data+ shipping_id = graphene.Node.to_global_id(+ "ShippingMethod", shipping_method_channel_PLN.id+ )+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)+ redirect_url = "https://www.example.com"++ variables = {+ "input": {+ "user": user_id,+ "lines": variant_list,+ "billingAddress": shipping_address,+ "shippingAddress": shipping_address,+ "shippingMethod": shipping_id,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = app_api_client.post_graphql(+ query, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["draftOrderCreate"]["errors"]++ # confirm that event delivery was generated for each webhook.+ draft_order_created_delivery = EventDelivery.objects.get(+ webhook_id=draft_order_created_webhook.id+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": draft_order_created_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_delete.pyindex 491e217b0c..3734a1c203 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py@@ -1,9 +1,15 @@+from unittest.mock import patch+import grapheneimport pytest+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....discount.models import VoucherCodefrom .....order import OrderStatus+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCode+from .....webhook.event_types import WebhookEventAsyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentDRAFT_ORDER_DELETE_MUTATION = """@@ -256,3 +262,60 @@ def test_draft_order_delete_release_voucher_codes_single_use(# thenvoucher_code.refresh_from_db()assert voucher_code.is_active is True+++@patch(+ "saleor.graphql.order.mutations.draft_order_delete.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_draft_order_delete_do_not_trigger_sync_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ settings,+ django_capture_on_commit_callbacks,+ staff_api_client,+ permission_group_manage_orders,+ draft_order,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ draft_order_deleted_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.DRAFT_ORDER_DELETED)++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = draft_order+ query = DRAFT_ORDER_DELETE_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["draftOrderDelete"]["errors"]++ # confirm that event delivery was generated for each webhook.+ draft_order_deleted_delivery = EventDelivery.objects.get(+ webhook_id=draft_order_deleted_webhook.id+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": draft_order_deleted_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ assert not mocked_send_webhook_request_sync.called+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.pyindex 84982d53cd..384dc76b81 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py@@ -1,17 +1,22 @@from decimal import Decimal+from unittest.mock import call, patchimport grapheneimport pytest+from django.test import override_settingsfrom prices import TaxedMoney+from .....core.models import EventDeliveryfrom .....core.prices import quantize_pricefrom .....core.taxes import zero_moneyfrom .....discount import DiscountType, DiscountValueType, RewardValueType, VoucherTypefrom .....discount.models import OrderDiscount, Voucherfrom .....order import OrderStatus+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEventfrom .....payment.model_helpers import get_subtotal+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentDRAFT_ORDER_UPDATE_MUTATION = """@@ -2066,3 +2071,168 @@ def test_draft_order_update_replace_entire_order_voucher_with_shipping_voucher(assert order_discount.name == ""assert order_discount.type == DiscountType.VOUCHERassert order_discount.voucher_code == shipping_code+++@patch(+ "saleor.graphql.order.mutations.draft_order_create.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_draft_order_update_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ voucher,+ app_api_client,+ permission_manage_orders,+ draft_order,+ django_capture_on_commit_callbacks,+ settings,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ draft_order_updated_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.DRAFT_ORDER_UPDATED)++ order = draft_order+ order.voucher = voucher+ order.save(update_fields=["voucher"])++ voucher_listing = voucher.channel_listings.get(channel=order.channel)+ discount_amount = voucher_listing.discount_value+ order.discounts.create(+ voucher=voucher,+ value=discount_amount,+ type=DiscountType.VOUCHER,+ )++ query = DRAFT_ORDER_UPDATE_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {+ "id": order_id,+ "input": {+ "voucher": None,+ },+ }++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = app_api_client.post_graphql(+ query, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderUpdate"]+ assert not data["errors"]+ order.refresh_from_db()++ # confirm that event delivery was generated for each webhook.+ draft_order_updated_delivery = EventDelivery.objects.get(+ webhook_id=draft_order_updated_webhook.id+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": draft_order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.called+++@patch(+ "saleor.graphql.order.mutations.draft_order_create.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_draft_order_update_triggers_webhooks_when_tax_webhook_not_needed(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ voucher,+ app_api_client,+ permission_manage_orders,+ draft_order,+ django_capture_on_commit_callbacks,+ settings,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ draft_order_updated_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.DRAFT_ORDER_UPDATED)++ order = draft_order++ query = DRAFT_ORDER_UPDATE_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {+ "id": order_id,+ "input": {+ "customerNote": "New note",+ },+ }++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = app_api_client.post_graphql(+ query, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderUpdate"]+ assert not data["errors"]+ order.refresh_from_db()++ # confirm that event delivery was generated for each webhook.+ draft_order_updated_delivery = EventDelivery.objects.get(+ webhook_id=draft_order_updated_webhook.id+ )+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ assert not tax_delivery+ assert not order.should_refresh_prices+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": draft_order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_called_once_with(+ filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.pyindex e831aa599b..1847635045 100644--- a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py@@ -2,8 +2,10 @@ from unittest.mock import ANY, call, patchimport graphene+from .....order.actions import WEBHOOK_EVENTS_FOR_ORDER_CANCELED, cancel_orderfrom .....order.models import OrderLinefrom .....product.models import ProductVariant+from .....webhook.utils import get_webhooks_for_multiple_eventsfrom ....tests.utils import assert_no_permission, get_graphql_contentMUTATION_ORDER_BULK_CANCEL = """@@ -19,21 +21,23 @@ mutation CancelManyOrders($ids: [ID!]!) {"""-@patch("saleor.graphql.order.bulk_mutations.order_bulk_cancel.get_webhooks_for_event")-@patch("saleor.graphql.order.bulk_mutations.order_bulk_cancel.cancel_order")+@patch(+ "saleor.graphql.order.bulk_mutations.order_bulk_cancel.cancel_order",+ wraps=cancel_order,+)def test_order_bulk_cancel(mock_cancel_order,- mocked_get_webhooks_for_event,staff_api_client,order_list,fulfilled_order_with_all_cancelled_fulfillments,permission_group_manage_orders,- address,any_webhook,settings,):# given- mocked_get_webhooks_for_event.return_value = [any_webhook]+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED+ )settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -55,8 +59,7 @@ def test_order_bulk_cancel(user=staff_api_client.user,app=None,manager=ANY,- webhooks_cancelled=[any_webhook],- webhooks_updated=[any_webhook],+ webhook_event_map=webhook_event_map,)for order in orders]@@ -111,11 +114,12 @@ def test_order_bulk_cancel_with_back_in_stock_webhook(product_variant_back_in_stock_webhook_mock.assert_called_once()-@patch("saleor.graphql.order.bulk_mutations.order_bulk_cancel.get_webhooks_for_event")-@patch("saleor.graphql.order.bulk_mutations.order_bulk_cancel.cancel_order")+@patch(+ "saleor.graphql.order.bulk_mutations.order_bulk_cancel.cancel_order",+ wraps=cancel_order,+)def test_order_bulk_cancel_as_app(mock_cancel_order,- mocked_get_webhooks_for_event,app_api_client,order_list,fulfilled_order_with_all_cancelled_fulfillments,@@ -125,7 +129,9 @@ def test_order_bulk_cancel_as_app(settings,):# given- mocked_get_webhooks_for_event.return_value = [any_webhook]+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED+ )settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]orders = order_list@@ -148,8 +154,7 @@ def test_order_bulk_cancel_as_app(user=None,app=app_api_client.app,manager=ANY,- webhooks_cancelled=[any_webhook],- webhooks_updated=[any_webhook],+ webhook_event_map=webhook_event_map,)for order in orders]@@ -158,11 +163,12 @@ def test_order_bulk_cancel_as_app(assert mock_cancel_order.call_count == expected_count-@patch("saleor.graphql.order.bulk_mutations.order_bulk_cancel.get_webhooks_for_event")-@patch("saleor.graphql.order.bulk_mutations.order_bulk_cancel.cancel_order")+@patch(+ "saleor.graphql.order.bulk_mutations.order_bulk_cancel.cancel_order",+ wraps=cancel_order,+)def test_order_bulk_cancel_without_sku(mock_cancel_order,- mocked_get_webhooks_for_event,staff_api_client,order_list,fulfilled_order_with_all_cancelled_fulfillments,@@ -172,7 +178,9 @@ def test_order_bulk_cancel_without_sku(settings,):# given- mocked_get_webhooks_for_event.return_value = [any_webhook]+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED+ )settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -197,8 +205,7 @@ def test_order_bulk_cancel_without_sku(user=staff_api_client.user,app=None,manager=ANY,- webhooks_cancelled=[any_webhook],- webhooks_updated=[any_webhook],+ webhook_event_map=webhook_event_map,)for order in orders]diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.pyindex e3da0e3646..f2606a0c87 100644--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py@@ -1030,7 +1030,7 @@ def test_order_bulk_create_multiple_notes(assert event_2["message"] == note_2["message"]assert event_2["app"]["id"] == note_2["appId"]- db_events = OrderEvent.objects.all()+ db_events = OrderEvent.objects.all().order_by("pk")db_event_1 = db_events[0]assert db_event_1.parameters["message"] == note_1["message"]assert db_event_1.user == customer_userdiff --git a/saleor/graphql/order/tests/mutations/test_order_cancel.py b/saleor/graphql/order/tests/mutations/test_order_cancel.pyindex 05028700cd..2b45135345 100644--- a/saleor/graphql/order/tests/mutations/test_order_cancel.py+++ b/saleor/graphql/order/tests/mutations/test_order_cancel.py@@ -1,9 +1,14 @@-from unittest.mock import ANY, patch+from unittest.mock import ANY, call, patchimport graphene+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....giftcard import GiftCardEventsfrom .....giftcard.events import gift_cards_bought_event+from .....order import OrderStatus+from .....order.actions import call_order_event, cancel_order+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentMUTATION_ORDER_CANCEL = """@@ -22,7 +27,7 @@ mutation cancelOrder($id: ID!) {"""-@patch("saleor.graphql.order.mutations.order_cancel.cancel_order")+@patch("saleor.graphql.order.mutations.order_cancel.cancel_order", wraps=cancel_order)@patch("saleor.graphql.order.mutations.order_cancel.clean_order_cancel")def test_order_cancel(mock_clean_order_cancel,@@ -125,3 +130,92 @@ def test_order_cancel_no_channel_access(# thenassert_no_permission(response)+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+@patch("saleor.graphql.order.mutations.order_cancel.clean_order_cancel")+def test_order_cancel_skip_trigger_webhooks(+ mock_clean_order_cancel,+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [WebhookEventAsyncType.ORDER_UPDATED, WebhookEventAsyncType.ORDER_CANCELLED]+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = order_with_lines+ order.should_refresh_prices = True+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status", "should_refresh_prices"])+ mock_clean_order_cancel.return_value = order+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(MUTATION_ORDER_CANCEL, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderCancel"]+ assert not data["errors"]++ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_cancelled_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CANCELLED,+ )+ order_deliveries = [+ order_cancelled_delivery,+ order_updated_delivery,+ ]+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()++ assert not tax_delivery+ assert not filter_shipping_delivery++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ assert not mocked_send_webhook_request_sync.called+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_capture.py b/saleor/graphql/order/tests/mutations/test_order_capture.pyindex ce3b3aadc7..de5749542b 100644--- a/saleor/graphql/order/tests/mutations/test_order_capture.py+++ b/saleor/graphql/order/tests/mutations/test_order_capture.py@@ -1,13 +1,18 @@-from unittest.mock import ANY, patch+from unittest.mock import ANY, call, patchimport graphene+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....core.notify_events import NotifyEventTypefrom .....core.tests.utils import get_site_context_payload+from .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import call_order_event, order_chargedfrom .....order.notifications import get_default_order_payloadfrom .....payment import ChargeStatusfrom .....payment.models import Payment+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....payment.types import PaymentChargeStatusEnumfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -35,11 +40,15 @@ ORDER_CAPTURE_MUTATION = """"""+@patch(+ "saleor.graphql.order.mutations.order_capture.order_charged", wraps=order_charged+)@patch("saleor.giftcard.utils.fulfill_non_shippable_gift_cards")@patch("saleor.plugins.manager.PluginsManager.notify")def test_order_capture(mocked_notify,fulfill_non_shippable_gift_cards_mock,+ order_charged_mock,staff_api_client,permission_group_manage_orders,payment_txn_preauth,@@ -104,6 +113,7 @@ def test_order_capture(fulfill_non_shippable_gift_cards_mock.assert_called_once_with(order, list(order.lines.all()), site_settings, staff_api_client.user, None, ANY)+ assert order_charged_mock.calleddef test_order_capture_by_user_no_channel_access(@@ -155,3 +165,107 @@ def test_order_capture_by_app(assert data["paymentStatusDisplay"] == payment_status_displayassert data["isPaid"]assert data["totalCaptured"]["amount"] == float(amount)+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=[+ "saleor.plugins.webhook.plugin.WebhookPlugin",+ "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",+ ]+)+def test_order_capture_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_group_manage_orders,+ payment_txn_preauth,+ staff_user,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ ]+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = payment_txn_preauth.order+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])+ order_id = graphene.Node.to_global_id("Order", order.id)+ amount = float(payment_txn_preauth.total)+ variables = {"id": order_id, "amount": amount}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(ORDER_CAPTURE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderCapture"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_PAID,+ )+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_fully_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_PAID,+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ order_deliveries = [+ order_fully_paid_delivery,+ order_paid_delivery,+ order_updated_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_confirm.py b/saleor/graphql/order/tests/mutations/test_order_confirm.pyindex 54124f6ac0..e9f9b1b911 100644--- a/saleor/graphql/order/tests/mutations/test_order_confirm.py+++ b/saleor/graphql/order/tests/mutations/test_order_confirm.py@@ -1,17 +1,31 @@-from unittest.mock import ANY, patch+from unittest.mock import ANY, call, patchimport graphene+from django.test import override_settings+from .....core.models import EventDelivery+from .....core.notification.utils import get_site_contextfrom .....core.notify_events import NotifyEventType+from .....core.prices import quantize_pricefrom .....core.tests.utils import get_site_context_payloadfrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import (+ WEBHOOK_EVENTS_FOR_ORDER_CHARGED,+ WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED,+ call_order_event,+ handle_fully_paid_order,+ order_charged,+ order_confirmed,+)from .....order.error_codes import OrderErrorCodefrom .....order.fetch import fetch_order_infofrom .....order.models import OrderEventfrom .....order.notifications import get_default_order_payloadfrom .....order.utils import updates_amounts_for_orderfrom .....product.models import ProductVariant+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.utils import get_webhooks_for_multiple_eventsfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -30,12 +44,21 @@ ORDER_CONFIRM_MUTATION = """"""-@patch("saleor.order.actions.handle_fully_paid_order")+@patch("saleor.order.actions.handle_fully_paid_order", wraps=handle_fully_paid_order)+@patch(+ "saleor.graphql.order.mutations.order_confirm.order_confirmed",+ wraps=order_confirmed,+)+@patch(+ "saleor.graphql.order.mutations.order_confirm.order_charged", wraps=order_charged+)@patch("saleor.plugins.manager.PluginsManager.notify")@patch("saleor.payment.gateway.capture")def test_order_confirm(capture_mock,mocked_notify,+ order_charged_mock,+ order_confirmed_mock,handle_fully_paid_order_mock,staff_api_client,order_unconfirmed,@@ -44,6 +67,9 @@ def test_order_confirm(site_settings,):# given+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED.union(WEBHOOK_EVENTS_FOR_ORDER_CHARGED)+ )payment_txn_preauth.order = order_unconfirmedpayment_txn_preauth.captured_amount = order_unconfirmed.total.gross.amountpayment_txn_preauth.total = order_unconfirmed.total.gross.amount@@ -68,13 +94,19 @@ def test_order_confirm(assert order_data["status"] == OrderStatus.UNFULFILLED.upper()order_unconfirmed.refresh_from_db()assert order_unconfirmed.status == OrderStatus.UNFULFILLED- assert OrderEvent.objects.count() == 2+ assert OrderEvent.objects.count() == 3assert OrderEvent.objects.filter(order=order_unconfirmed,user=staff_api_client.user,type=order_events.OrderEvents.CONFIRMED,).exists()+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ user=staff_api_client.user,+ type=order_events.OrderEvents.ORDER_FULLY_PAID,+ ).exists()+assert OrderEvent.objects.filter(order=order_unconfirmed,user=staff_api_client.user,@@ -82,29 +114,78 @@ def test_order_confirm(parameters__amount=payment_txn_preauth.get_total().amount,).exists()+ order_info = fetch_order_info(order_unconfirmed)++ order_charged_mock.assert_called_once_with(+ order_info,+ staff_api_client.user,+ None,+ payment_txn_preauth.total,+ payment_txn_preauth,+ ANY,+ site_settings,+ payment_txn_preauth.gateway,+ webhook_event_map=webhook_event_map,+ )+ order_confirmed_mock.assert_called_once_with(+ order_unconfirmed,+ staff_api_client.user,+ None,+ ANY,+ send_confirmation_email=True,+ webhook_event_map=webhook_event_map,+ )+ handle_fully_paid_order_mock.assert_called_once_with(+ ANY,+ order_info,+ user=staff_api_client.user,+ app=None,+ site_settings=site_settings,+ gateway=payment_txn_preauth.gateway,+ webhook_event_map=webhook_event_map,+ )+capture_mock.assert_called_once_with(payment_txn_preauth, ANY, channel_slug=order_unconfirmed.channel.slug)- expected_payload = {+ expected_confirmed_payload = {"order": get_default_order_payload(order_unconfirmed, ""),"recipient_email": order_unconfirmed.user.email,"requester_user_id": to_global_id_or_none(staff_api_client.user),"requester_app_id": None,**get_site_context_payload(site_settings.site),}- mocked_notify.assert_called_once_with(- NotifyEventType.ORDER_CONFIRMED,- expected_payload,- channel_slug=order_unconfirmed.channel.slug,- )- order_info = fetch_order_info(order_unconfirmed)- handle_fully_paid_order_mock.assert_called_once_with(- ANY,- order_info,- staff_api_client.user,- None,- site_settings,- payment_txn_preauth.gateway,+ expected_payment_payload = {+ "order": get_default_order_payload(order_unconfirmed),+ "recipient_email": order_unconfirmed.user.email,+ "payment": {+ "created": payment_txn_preauth.created_at,+ "modified": payment_txn_preauth.modified_at,+ "charge_status": payment_txn_preauth.charge_status,+ "total": quantize_price(+ payment_txn_preauth.total, payment_txn_preauth.currency+ ),+ "captured_amount": quantize_price(+ payment_txn_preauth.captured_amount, payment_txn_preauth.currency+ ),+ "currency": payment_txn_preauth.currency,+ },+ **get_site_context(),+ }++ mocked_notify.has_calls(+ [+ call(+ NotifyEventType.ORDER_CONFIRMED,+ expected_confirmed_payload,+ channel_slug=order_unconfirmed.channel.slug,+ ),+ call(+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,+ expected_payment_payload,+ channel_slug=order_unconfirmed.channel.slug,+ ),+ ])@@ -300,12 +381,21 @@ def test_order_confirm_by_user_no_channel_access(assert_no_permission(response)-@patch("saleor.order.actions.handle_fully_paid_order")+@patch("saleor.order.actions.handle_fully_paid_order", wraps=handle_fully_paid_order)+@patch(+ "saleor.graphql.order.mutations.order_confirm.order_confirmed",+ wraps=order_confirmed,+)+@patch(+ "saleor.graphql.order.mutations.order_confirm.order_charged", wraps=order_charged+)@patch("saleor.plugins.manager.PluginsManager.notify")@patch("saleor.payment.gateway.capture")def test_order_confirm_by_app(capture_mock,mocked_notify,+ order_charged_mock,+ order_confirmed_mock,handle_fully_paid_order_mock,app_api_client,order_unconfirmed,@@ -314,6 +404,9 @@ def test_order_confirm_by_app(site_settings,):# given+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED.union(WEBHOOK_EVENTS_FOR_ORDER_CHARGED)+ )payment_txn_preauth.order = order_unconfirmedpayment_txn_preauth.captured_amount = order_unconfirmed.total.gross.amountpayment_txn_preauth.total = order_unconfirmed.total.gross.amount@@ -338,13 +431,19 @@ def test_order_confirm_by_app(assert order_data["status"] == OrderStatus.UNFULFILLED.upper()order_unconfirmed.refresh_from_db()assert order_unconfirmed.status == OrderStatus.UNFULFILLED- assert OrderEvent.objects.count() == 2+ assert OrderEvent.objects.count() == 3assert OrderEvent.objects.filter(order=order_unconfirmed,app=app_api_client.app,type=order_events.OrderEvents.CONFIRMED,).exists()+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ app=app_api_client.app,+ type=order_events.OrderEvents.ORDER_FULLY_PAID,+ ).exists()+assert OrderEvent.objects.filter(order=order_unconfirmed,app=app_api_client.app,@@ -352,29 +451,78 @@ def test_order_confirm_by_app(parameters__amount=payment_txn_preauth.get_total().amount,).exists()+ order_info = fetch_order_info(order_unconfirmed)++ order_charged_mock.assert_called_once_with(+ order_info,+ None,+ app_api_client.app,+ payment_txn_preauth.total,+ payment_txn_preauth,+ ANY,+ site_settings,+ payment_txn_preauth.gateway,+ webhook_event_map=webhook_event_map,+ )+ order_confirmed_mock.assert_called_once_with(+ order_unconfirmed,+ None,+ app_api_client.app,+ ANY,+ send_confirmation_email=True,+ webhook_event_map=webhook_event_map,+ )+ handle_fully_paid_order_mock.assert_called_once_with(+ ANY,+ order_info,+ user=None,+ app=app_api_client.app,+ site_settings=site_settings,+ gateway=payment_txn_preauth.gateway,+ webhook_event_map=webhook_event_map,+ )+capture_mock.assert_called_once_with(payment_txn_preauth, ANY, channel_slug=order_unconfirmed.channel.slug)- expected_payload = {+ expected_confirmed_payload = {"order": get_default_order_payload(order_unconfirmed, ""),"recipient_email": order_unconfirmed.user.email,"requester_user_id": None,"requester_app_id": to_global_id_or_none(app_api_client.app),**get_site_context_payload(site_settings.site),}- mocked_notify.assert_called_once_with(- NotifyEventType.ORDER_CONFIRMED,- expected_payload,- channel_slug=order_unconfirmed.channel.slug,- )- order_info = fetch_order_info(order_unconfirmed)- handle_fully_paid_order_mock.assert_called_once_with(- ANY,- order_info,- None,- app_api_client.app,- site_settings,- payment_txn_preauth.gateway,+ expected_payment_payload = {+ "order": get_default_order_payload(order_unconfirmed),+ "recipient_email": order_unconfirmed.user.email,+ "payment": {+ "created": payment_txn_preauth.created_at,+ "modified": payment_txn_preauth.modified_at,+ "charge_status": payment_txn_preauth.charge_status,+ "total": quantize_price(+ payment_txn_preauth.total, payment_txn_preauth.currency+ ),+ "captured_amount": quantize_price(+ payment_txn_preauth.captured_amount, payment_txn_preauth.currency+ ),+ "currency": payment_txn_preauth.currency,+ },+ **get_site_context(),+ }++ mocked_notify.has_calls(+ [+ call(+ NotifyEventType.ORDER_CONFIRMED,+ expected_confirmed_payload,+ channel_slug=order_unconfirmed.channel.slug,+ ),+ call(+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,+ expected_payment_payload,+ channel_slug=order_unconfirmed.channel.slug,+ ),+ ])@@ -429,3 +577,104 @@ def test_order_confirm_skip_address_validation(assert order.shipping_address.postal_code == invalid_postal_codeassert order.billing_address.postal_code == invalid_postal_codeassert order.status == OrderStatus.UNFULFILLED+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@patch("saleor.payment.gateway.capture")+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_confirm_triggers_webhooks(+ capture_mock,+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ order_unconfirmed,+ permission_group_manage_orders,+ payment_txn_preauth,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_CONFIRMED,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_PAID,+ ]+ )++ payment_txn_preauth.order = order_unconfirmed+ payment_txn_preauth.captured_amount = order_unconfirmed.total.gross.amount+ payment_txn_preauth.total = order_unconfirmed.total.gross.amount+ payment_txn_preauth.save(update_fields=["order", "captured_amount", "total"])++ order_unconfirmed.total_charged = order_unconfirmed.total.gross+ order_unconfirmed.save(update_fields=["total_charged_amount"])+ updates_amounts_for_order(order_unconfirmed)++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ assert not OrderEvent.objects.exists()++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(+ ORDER_CONFIRM_MUTATION,+ {"id": graphene.Node.to_global_id("Order", order_unconfirmed.id)},+ )++ # then+ assert not get_graphql_content(response)["data"]["orderConfirm"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_confirmed_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CONFIRMED,+ )+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_fully_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_PAID,+ )+ order_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_PAID,+ )+ order_deliveries = [+ order_confirmed_delivery,+ order_updated_delivery,+ order_fully_paid_delivery,+ order_paid_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ assert not mocked_send_webhook_request_sync.called+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.pyindex 6b261b9b92..3861b74265 100644--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py@@ -1,18 +1,21 @@-from unittest.mock import ANY, patch+from unittest.mock import ANY, call, patchimport grapheneimport pytest+from django.test import override_settingsfrom .....core.exceptions import InsufficientStock, InsufficientStockData+from .....core.models import EventDeliveryfrom .....giftcard import GiftCardEventsfrom .....giftcard.models import GiftCard, GiftCardEventfrom .....order import FulfillmentStatus, OrderStatus+from .....order.actions import call_order_event, order_fulfilledfrom .....order.error_codes import OrderErrorCodefrom .....order.models import Fulfillment, FulfillmentLinefrom .....product.models import ProductVariantfrom .....tests.utils import flush_post_commit_hooksfrom .....warehouse.models import Allocation, Stock-from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentORDER_FULFILL_MUTATION = """@@ -38,9 +41,11 @@ ORDER_FULFILL_MUTATION = """"""+@patch("saleor.order.actions.order_fulfilled", wraps=order_fulfilled)@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_order_fulfill_with_out_of_stock_webhook(product_variant_out_of_stock_webhooks,+ wrapped_order_fulfilled,staff_api_client,order_with_lines,permission_group_manage_orders,@@ -70,6 +75,7 @@ def test_order_fulfill_with_out_of_stock_webhook(stock = order_line2.variant.stocks.filter(warehouse=warehouse).first()product_variant_out_of_stock_webhooks.assert_called_once_with(stock)+ assert wrapped_order_fulfilled.called@pytest.mark.parametrize("fulfillment_auto_approve", [True, False])@@ -1545,3 +1551,111 @@ def test_order_fulfill_tracking_number_updated_event_triggered(== WebhookEventAsyncType.FULFILLMENT_TRACKING_NUMBER_UPDATED)assert mocked_fulfillment_created[0][1] == WebhookEventAsyncType.FULFILLMENT_CREATED+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_fulfill_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ order_with_lines,+ permission_group_manage_orders,+ warehouse,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [WebhookEventAsyncType.ORDER_UPDATED, WebhookEventAsyncType.ORDER_FULFILLED]+ )+ order = order_with_lines++ query = ORDER_FULFILL_MUTATION+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line1, order_line2 = order.lines.all()+ order_line1_id = graphene.Node.to_global_id("OrderLine", order_line1.id)+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line2_id,+ "stocks": [+ {"quantity": order_line2.quantity, "warehouse": warehouse_id}+ ],+ },+ {+ "orderLineId": order_line1_id,+ "stocks": [+ {"quantity": order_line1.quantity, "warehouse": warehouse_id}+ ],+ },+ ],+ },+ }+ # when+ with django_capture_on_commit_callbacks(execute=False) as callbacks:+ response = staff_api_client.post_graphql(query, variables)++ with django_capture_on_commit_callbacks(execute=True):+ for callback in callbacks:+ callback()++ # then+ assert not get_graphql_content(response)["data"]["orderFulfill"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_fulfilled_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULFILLED,+ )+ order_deliveries = [+ order_updated_delivery,+ order_fulfilled_delivery,+ ]++ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not tax_delivery+ assert not filter_shipping_delivery++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_line_delete.py b/saleor/graphql/order/tests/mutations/test_order_line_delete.pyindex 6e3004dc5b..3323898f88 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_delete.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_delete.py@@ -1,14 +1,18 @@-from unittest.mock import patch+from unittest.mock import call, patchimport grapheneimport pytestfrom django.db.models import Sum+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEventfrom .....warehouse.models import Stock+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ..utils import assert_proper_webhook_called_once@@ -300,3 +304,84 @@ def test_order_line_delete_non_removable_gift(assert len(errors) == 1assert errors[0]["field"] == "id"assert errors[0]["code"] == OrderErrorCode.NON_REMOVABLE_GIFT_LINE.name+++ ("status", "webhook_event"),+ [+ (OrderStatus.DRAFT, WebhookEventAsyncType.DRAFT_ORDER_UPDATED),+ (OrderStatus.UNCONFIRMED, WebhookEventAsyncType.ORDER_UPDATED),+ ],+)+@patch(+ "saleor.graphql.order.mutations.utils.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_line_delete_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ draft_order,+ permission_group_manage_orders,+ staff_api_client,+ settings,+ django_capture_on_commit_callbacks,+ status,+ webhook_event,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ permission_group_manage_orders.user_set.add(staff_api_client.user)++ query = ORDER_LINE_DELETE_MUTATION+ order = draft_order+ order.status = status+ order.save(update_fields=["status"])++ line = order.lines.first()++ line_id = graphene.Node.to_global_id("OrderLine", line.id)+ variables = {"id": line_id}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderLineDelete"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.pyindex 4367a4c1fc..14f7302567 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py@@ -1,17 +1,21 @@from decimal import Decimal-from unittest.mock import patch+from unittest.mock import call, patchimport grapheneimport pytest+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....discount import DiscountType, RewardValueTypefrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEventfrom .....product.models import ProductVariantfrom .....tests.utils import flush_post_commit_hooksfrom .....warehouse.models import Allocation, Stock+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ..utils import assert_proper_webhook_called_once@@ -574,3 +578,86 @@ def test_order_line_update_gift_promotion(assert discount.amount_value == gift_priceassert discount.type == DiscountType.ORDER_PROMOTIONassert discount.reason == f"Promotion: {promotion_id}"+++ ("status", "webhook_event"),+ [+ (OrderStatus.DRAFT, WebhookEventAsyncType.DRAFT_ORDER_UPDATED),+ (OrderStatus.UNCONFIRMED, WebhookEventAsyncType.ORDER_UPDATED),+ ],+)+@patch(+ "saleor.graphql.order.mutations.utils.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_line_update_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ permission_group_manage_orders,+ staff_api_client,+ settings,+ django_capture_on_commit_callbacks,+ status,+ webhook_event,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ query = ORDER_LINE_UPDATE_MUTATION+ order = order_with_lines+ order.should_refresh_prices = True+ order.status = status+ order.save(update_fields=["status", "should_refresh_prices"])+ first_line, second_line = order.lines.all()+ new_quantity = 5++ first_line_id = graphene.Node.to_global_id("OrderLine", first_line.id)++ permission_group_manage_orders.user_set.add(staff_api_client.user)++ variables = {"lineId": first_line_id, "quantity": new_quantity}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderLineUpdate"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.pyindex 763cdb64ea..be94b3c880 100644--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py@@ -1,19 +1,23 @@from datetime import datetimefrom decimal import Decimal-from unittest.mock import patch+from unittest.mock import call, patchimport grapheneimport pytestimport pytzfrom django.db.models import Sum+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....discount import DiscountType, RewardValueTypefrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEvent, OrderLinefrom .....product.models import ProductVariantfrom .....warehouse.models import Allocation, Stock+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ..utils import assert_proper_webhook_called_once@@ -1238,3 +1242,85 @@ def test_order_lines_create_no_shipping_address(assert not data["errors"]assert data["orderLines"][0]["productSku"] == variant.skuassert data["orderLines"][0]["quantity"] == quantity+++ ("status", "webhook_event"),+ [+ (OrderStatus.DRAFT, WebhookEventAsyncType.DRAFT_ORDER_UPDATED),+ (OrderStatus.UNCONFIRMED, WebhookEventAsyncType.ORDER_UPDATED),+ ],+)+@patch(+ "saleor.graphql.order.mutations.utils.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_lines_create_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ permission_group_manage_orders,+ staff_api_client,+ settings,+ django_capture_on_commit_callbacks,+ status,+ webhook_event,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ query = ORDER_LINES_CREATE_MUTATION+ order = order_with_lines+ order.status = status+ order.save(update_fields=["status"])+ line = order.lines.first()+ variant = line.variant+ quantity = 2+ order_id = graphene.Node.to_global_id("Order", order.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}++ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderLinesCreate"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_note_add.py b/saleor/graphql/order/tests/mutations/test_order_note_add.pyindex 18188a4865..3caa1c8eb3 100644--- a/saleor/graphql/order/tests/mutations/test_order_note_add.py+++ b/saleor/graphql/order/tests/mutations/test_order_note_add.py@@ -1,12 +1,16 @@-from unittest.mock import patch+from unittest.mock import call, patchimport grapheneimport pytest+from django.test import override_settingsfrom .....account.models import CustomerEvent+from .....core.models import EventDeliveryfrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderNoteAddErrorCode+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentORDER_NOTE_ADD_MUTATION = """@@ -170,3 +174,82 @@ def test_order_note_add_fail_on_missing_permission(staff_api_client, order):# thenassert_no_permission(response)+++ ("status", "webhook_event"),+ [+ (OrderStatus.DRAFT, WebhookEventAsyncType.DRAFT_ORDER_UPDATED),+ (OrderStatus.UNCONFIRMED, WebhookEventAsyncType.ORDER_UPDATED),+ ],+)+@patch(+ "saleor.graphql.order.mutations.utils.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_note_add_user_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ status,+ webhook_event,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = order_with_lines+ order.should_refresh_prices = True+ order.status = status+ order.save(update_fields=["status", "should_refresh_prices"])++ order_id = graphene.Node.to_global_id("Order", order.id)+ message = "new note"+ variables = {"id": order_id, "message": message}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(ORDER_NOTE_ADD_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderNoteAdd"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_note_update.py b/saleor/graphql/order/tests/mutations/test_order_note_update.pyindex e7d7f49302..721bb1ce40 100644--- a/saleor/graphql/order/tests/mutations/test_order_note_update.py+++ b/saleor/graphql/order/tests/mutations/test_order_note_update.py@@ -1,12 +1,16 @@-from unittest.mock import patch+from unittest.mock import call, patchimport grapheneimport pytest+from django.test import override_settingsfrom .....account.models import CustomerEvent+from .....core.models import EventDeliveryfrom .....order import OrderEvents, OrderStatus+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderNoteUpdateErrorCodefrom .....order.models import OrderEvent+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentORDER_NOTE_UPDATE_MUTATION = """@@ -202,3 +206,94 @@ def test_order_note_remove_fail_on_missing_permission(staff_api_client, order):# thenassert_no_permission(response)+++ ("status", "webhook_event"),+ [+ (OrderStatus.DRAFT, WebhookEventAsyncType.DRAFT_ORDER_UPDATED),+ (OrderStatus.UNCONFIRMED, WebhookEventAsyncType.ORDER_UPDATED),+ ],+)+@patch(+ "saleor.graphql.order.mutations.utils.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_note_update_user_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ staff_user,+ settings,+ django_capture_on_commit_callbacks,+ status,+ webhook_event,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ order = order_with_lines+ order.should_refresh_prices = True+ order.status = status+ order.save(update_fields=["status", "should_refresh_prices"])++ parameters = {"message": "a note"}+ note = OrderEvent.objects.create(+ order=order,+ type=OrderEvents.NOTE_ADDED,+ user=staff_user,+ parameters=parameters,+ )+ note_id = graphene.Node.to_global_id("OrderEvent", note.pk)++ message = "new note"+ variables = {"id": note_id, "message": message}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(+ ORDER_NOTE_UPDATE_MUTATION,+ variables,+ permissions=[permission_manage_orders],+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderNoteUpdate"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_update.py b/saleor/graphql/order/tests/mutations/test_order_update.pyindex dca2b87b13..be446cbaec 100644--- a/saleor/graphql/order/tests/mutations/test_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_order_update.py@@ -1,10 +1,14 @@-from unittest.mock import patch+from unittest.mock import call, patchimport graphene+from django.test import override_settings+from .....core.models import EventDeliveryfrom .....order import OrderStatus+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCodefrom .....product.models import ProductVariant+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentORDER_UPDATE_MUTATION = """@@ -510,3 +514,75 @@ def test_order_update_invalid_address_skip_validation(assert order.shipping_address.validation_skipped is Trueassert order.billing_address.postal_code == invalid_postal_codeassert order.billing_address.validation_skipped is True+++@patch(+ "saleor.graphql.order.mutations.order_update.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_update_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ graphql_address_data,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.ORDER_UPDATED)++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save()+ order_id = graphene.Node.to_global_id("Order", order.id)++ variables = {+ "id": order_id,+ "address": graphql_address_data,+ }++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(ORDER_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderUpdate"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py b/saleor/graphql/order/tests/mutations/test_order_update_shipping.pyindex 086364cab9..2ef1da1663 100644--- a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py+++ b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py@@ -1,12 +1,17 @@from decimal import Decimal+from unittest.mock import call, patchimport grapheneimport pytest+from django.test import override_settingsfrom prices import TaxedMoney+from .....core.models import EventDeliveryfrom .....core.taxes import zero_money, zero_taxed_moneyfrom .....order import OrderStatus+from .....order.actions import call_order_eventfrom .....order.error_codes import OrderErrorCode+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentORDER_UPDATE_SHIPPING_QUERY = """@@ -533,3 +538,84 @@ def test_order_shipping_update_mutation_properly_recalculate_total(content = get_graphql_content(response)data = content["data"]["orderUpdateShipping"]assert data["order"]["shippingMethod"] is None+++@patch(+ "saleor.graphql.order.mutations.order_update_shipping.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_update_shipping_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ shipping_method,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.ORDER_UPDATED)++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = order_with_lines+ order.base_shipping_price = zero_money(order.currency)+ order.status = OrderStatus.UNCONFIRMED+ order.save()++ query = ORDER_UPDATE_SHIPPING_QUERY+ order_id = graphene.Node.to_global_id("Order", order.id)+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)+ variables = {"order": order_id, "shippingMethod": method_id}++ # when+ with django_capture_on_commit_callbacks(execute=True):+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["orderUpdateShipping"]["errors"]++ # confirm that event delivery was generated for each webhook.+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_deliveries = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).order_by("pk")+ assert len(filter_shipping_deliveries) == 2++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ # FIXME: This is the issue with current way of caching filter shipping+ # webhooks. Mutation calls the webhook to validates the shipping methods.+ # WebhookPlugin makes a cache based on the order payload. Then when+ # tax-webhook exists, we can get different price values, which will+ # change the data used to build the cache key. This should be solved+ # after providing similar way of handling sync webhooks as we have for+ # tax webhooks.+ call(filter_shipping_deliveries[0], timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ call(tax_delivery),+ call(filter_shipping_deliveries[1], timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex afe99afaf9..12c7ca5b99 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -3,9 +3,10 @@ from collections import defaultdictfrom collections.abc import Iterablefrom copy import deepcopyfrom decimal import Decimal-from typing import TYPE_CHECKING, Optional, TypedDict+from typing import TYPE_CHECKING, Callable, Optional, TypedDictfrom uuid import UUID+from django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.db import transaction@@ -13,7 +14,11 @@ from ..account.models import Userfrom ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockDatafrom ..core.tracing import traced_atomic_transactionfrom ..core.transactions import transaction_with_commit_on_errors-from ..core.utils.events import call_event+from ..core.utils.events import (+ call_event,+ call_event_including_protected_events,+ webhook_async_event_requires_sync_webhooks_to_trigger,+)from ..giftcard import GiftCardLineDatafrom ..payment import (ChargeStatus,@@ -26,6 +31,7 @@ from ..payment import (from ..payment.interface import RefundDatafrom ..payment.models import Payment, Transaction, TransactionItemfrom ..payment.utils import create_payment, create_transaction_for_order+from ..shipping.models import ShippingMethodChannelListingfrom ..warehouse.management import (deallocate_stock,deallocate_stock_for_order,@@ -33,7 +39,10 @@ from ..warehouse.management import (get_order_lines_with_track_inventory,)from ..warehouse.models import Stock+from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ..webhook.utils import get_webhooks_for_multiple_eventsfrom . import (+ ORDER_EDITABLE_STATUS,FulfillmentLineData,FulfillmentStatus,OrderChargeStatus,@@ -42,6 +51,7 @@ from . import (events,utils,)+from .calculations import fetch_order_prices_if_expiredfrom .events import (draft_order_created_from_replace_event,fulfillment_refunded_event,@@ -59,6 +69,7 @@ from .notifications import (send_payment_confirmation,)from .utils import (+ get_valid_shipping_methods_for_order,order_line_needs_automatic_fulfillment,restock_fulfillment_lines,update_order_authorize_data,@@ -72,6 +83,7 @@ if TYPE_CHECKING:from ..plugins.manager import PluginsManagerfrom ..site.models import SiteSettingsfrom ..warehouse.models import Warehouse+ from ..webhook.models import Webhookfrom .fetch import OrderInfologger = logging.getLogger(__name__)@@ -87,6 +99,98 @@ class OrderFulfillmentLineInfo(TypedDict):quantity: int+WEBHOOK_EVENTS_FOR_ORDER_FULFILLED = {+ WebhookEventAsyncType.ORDER_FULFILLED,+ WebhookEventAsyncType.ORDER_UPDATED,+ *WebhookEventSyncType.ORDER_EVENTS,+}++WEBHOOK_EVENTS_FOR_ORDER_REFUNDED = {+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ *WebhookEventSyncType.ORDER_EVENTS,+}+WEBHOOK_EVENTS_FOR_ORDER_CANCELED = {+ WebhookEventAsyncType.ORDER_CANCELLED,+ WebhookEventAsyncType.ORDER_UPDATED,+ *WebhookEventSyncType.ORDER_EVENTS,+}+WEBHOOK_EVENTS_FOR_FULLY_PAID = {+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ *WebhookEventSyncType.ORDER_EVENTS,+}+WEBHOOK_EVENTS_FOR_ORDER_AUTHORIZED = {+ WebhookEventAsyncType.ORDER_UPDATED,+ *WebhookEventSyncType.ORDER_EVENTS,+}++WEBHOOK_EVENTS_FOR_ORDER_CHARGED = {+ WebhookEventAsyncType.ORDER_PAID,+}.union(WEBHOOK_EVENTS_FOR_FULLY_PAID)++WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED = {+ WebhookEventAsyncType.ORDER_CONFIRMED,+ *WebhookEventSyncType.ORDER_EVENTS,+}+++WEBHOOK_EVENTS_FOR_ORDER_CREATED = {+ WebhookEventAsyncType.ORDER_CREATED,+}.union(WEBHOOK_EVENTS_FOR_ORDER_CHARGED).union(WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED)+++def call_order_event(+ manager: "PluginsManager",+ event_func: Callable,+ event_name: str,+ order: "Order",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,+ **event_kwargs,+):+ if order.status not in ORDER_EDITABLE_STATUS:+ call_event_including_protected_events(event_func, order, **event_kwargs)+ return+ if event_name == WebhookEventAsyncType.DRAFT_ORDER_DELETED:+ call_event_including_protected_events(event_func, order, **event_kwargs)+ return++ if webhook_event_map is None:+ webhook_event_map = get_webhooks_for_multiple_events(+ [event_name, *WebhookEventSyncType.ORDER_EVENTS]+ )+ if not webhook_async_event_requires_sync_webhooks_to_trigger(+ event_name, webhook_event_map, WebhookEventSyncType.ORDER_EVENTS+ ):+ call_event_including_protected_events(event_func, order, **event_kwargs)+ return++ if (+ webhook_event_map.get(WebhookEventSyncType.ORDER_CALCULATE_TAXES)+ and order.should_refresh_prices+ ):+ fetch_order_prices_if_expired(+ order,+ manager,+ database_connection_name=database_connection_name,+ )+ if webhook_event_map.get(WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS):+ shipping_listings = ShippingMethodChannelListing.objects.filter(+ channel_id=order.channel_id+ )+ get_valid_shipping_methods_for_order(+ order,+ shipping_listings,+ manager,+ database_connection_name=database_connection_name,+ )++ call_event_including_protected_events(event_func, order, **event_kwargs)+ return++def order_created(order_info: "OrderInfo",user: Optional[User],@@ -97,7 +201,18 @@ def order_created():order = order_info.orderevents.order_created_event(order=order, user=user, app=app, from_draft=from_draft)- call_event(manager.order_created, order)++ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CREATED+ )++ call_order_event(+ manager,+ manager.order_created,+ WebhookEventAsyncType.ORDER_CREATED,+ order,+ webhook_event_map=webhook_event_map,+ )payment = order_info.paymentif payment and order.is_pre_authorized():order_authorized(@@ -107,6 +222,7 @@ def order_created(amount=payment.total,payment=payment,manager=manager,+ webhook_event_map=webhook_event_map,)if order.charge_status in [OrderChargeStatus.FULL, OrderChargeStatus.OVERCHARGED]:order_charged(@@ -118,11 +234,12 @@ def order_created(manager=manager,site_settings=site_settings,gateway=payment.gateway if payment else None,+ webhook_event_map=webhook_event_map,)channel = order_info.channelif channel.automatically_confirm_all_new_orders:- order_confirmed(order, user, app, manager)+ order_confirmed(order, user, app, manager, webhook_event_map=webhook_event_map)def order_confirmed(@@ -131,13 +248,20 @@ def order_confirmed(app: Optional["App"],manager: "PluginsManager",send_confirmation_email: bool = False,+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,):"""Order confirmed.Trigger event, plugin hooks and optionally confirmation email."""events.order_confirmed_event(order=order, user=user, app=app)- call_event(manager.order_confirmed, order)+ call_order_event(+ manager,+ manager.order_confirmed,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ order,+ webhook_event_map=webhook_event_map,+ )if send_confirmation_email:send_order_confirmed(order, user, app, manager)@@ -145,6 +269,7 @@ def order_confirmed(def handle_fully_paid_order(manager: "PluginsManager",order_info: "OrderInfo",+ webhook_event_map: dict[str, set["Webhook"]],user: Optional[User] = None,app: Optional["App"] = None,site_settings: Optional["SiteSettings"] = None,@@ -168,11 +293,23 @@ def handle_fully_paid_order(order, order_lines, site_settings, user, app, manager)- call_event(manager.order_fully_paid, order)if not order.is_draft() and order.channel.automatically_confirm_all_new_orders:update_order_status(order)- call_event(manager.order_updated, order)+ call_order_event(+ manager,+ manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ webhook_event_map=webhook_event_map,+ )+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )def cancel_order(@@ -180,8 +317,7 @@ def cancel_order(user: Optional[User],app: Optional["App"],manager: "PluginsManager",- webhooks_cancelled=None,- webhooks_updated=None,+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,):"""Cancel order.@@ -193,9 +329,28 @@ def cancel_order(deallocate_stock_for_order(order, manager)order.status = OrderStatus.CANCELEDorder.save(update_fields=["status", "updated_at"])-- call_event(manager.order_cancelled, order, webhooks=webhooks_cancelled)- call_event(manager.order_updated, order, webhooks=webhooks_updated)+ if not webhook_event_map:+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED+ )+ call_order_event(+ manager,+ manager.order_cancelled,+ WebhookEventAsyncType.ORDER_CANCELLED,+ order,+ webhook_event_map=webhook_event_map,+ webhooks=webhook_event_map.get(+ WebhookEventAsyncType.ORDER_CANCELLED, set()+ ),+ )+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ webhooks=webhook_event_map.get(WebhookEventAsyncType.ORDER_UPDATED, set()),+ )call_event(send_order_canceled_confirmation, order, user, app, manager)@@ -208,6 +363,7 @@ def order_refunded(payment: Optional["Payment"],manager: "PluginsManager",trigger_order_updated: bool = True,+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,):if payment:call_event(@@ -228,10 +384,26 @@ def order_refunded(order.currency,manager,)+ if webhook_event_map is None:+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_REFUNDED+ )- call_event(manager.order_refunded, order)+ call_order_event(+ manager,+ manager.order_refunded,+ WebhookEventAsyncType.ORDER_REFUNDED,+ order,+ webhook_event_map=webhook_event_map,+ )if trigger_order_updated:- call_event(manager.order_updated, order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )total_refunded = Decimal(0)last_payment = payment if payment else order.get_last_payment()@@ -252,7 +424,13 @@ def order_refunded()if total_refunded >= order.total.gross.amount:- call_event(manager.order_fully_refunded, order)+ call_order_event(+ manager,+ manager.order_fully_refunded,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ order,+ webhook_event_map=webhook_event_map,+ )def order_voided(@@ -263,7 +441,9 @@ def order_voided(manager: "PluginsManager",):events.payment_voided_event(order=order, user=user, app=app, payment=payment)- call_event(manager.order_updated, order)+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )def order_returned(@@ -285,9 +465,14 @@ def order_fulfilled(gift_card_lines_info: list[GiftCardLineData],site_settings: "SiteSettings",notify_customer=True,+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,):from ..giftcard.utils import gift_cards_create+ if webhook_event_map is None:+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_FULFILLED+ )order = fulfillments[0].order# transaction ensures webhooks are triggered only when order status and fulfillment# events are successfully created@@ -304,12 +489,24 @@ def order_fulfilled(events.fulfillment_fulfilled_items_event(order=order, user=user, app=app, fulfillment_lines=fulfillment_lines)- call_event(manager.order_updated, order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )for fulfillment in fulfillments:call_event(manager.fulfillment_created, fulfillment, notify_customer)if order.status == OrderStatus.FULFILLED:- call_event(manager.order_fulfilled, order)+ call_order_event(+ manager,+ manager.order_fulfilled,+ WebhookEventAsyncType.ORDER_FULFILLED,+ order,+ webhook_event_map=webhook_event_map,+ )for fulfillment in fulfillments:call_event(manager.fulfillment_approved, fulfillment)@@ -326,15 +523,14 @@ def order_awaits_fulfillment_approval(app: Optional["App"],fulfillment_lines: list[FulfillmentLine],manager: "PluginsManager",- _gift_card_lines: list["GiftCardLineData"],- _site_settings: "SiteSettings",- _notify_customer=True,):order = fulfillments[0].orderevents.fulfillment_awaits_approval_event(order=order, user=user, app=app, fulfillment_lines=fulfillment_lines)- call_event(manager.order_updated, order)+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )def order_authorized(@@ -344,11 +540,18 @@ def order_authorized(amount: "Decimal",payment: "Payment",manager: "PluginsManager",+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,):events.payment_authorized_event(order=order, user=user, app=app, amount=amount, payment=payment)- call_event(manager.order_updated, order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )def order_charged(@@ -360,17 +563,43 @@ def order_charged(manager: "PluginsManager",site_settings: Optional["SiteSettings"] = None,gateway: Optional[str] = None,+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,):order = order_info.orderif payment and amount is not None:events.payment_captured_event(order=order, user=user, app=app, amount=amount, payment=payment)- call_event(manager.order_paid, order)+ if webhook_event_map is None:+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CHARGED+ )++ call_order_event(+ manager,+ manager.order_paid,+ WebhookEventAsyncType.ORDER_PAID,+ order,+ webhook_event_map=webhook_event_map,+ )if order.charge_status in [OrderChargeStatus.FULL, OrderChargeStatus.OVERCHARGED]:- handle_fully_paid_order(manager, order_info, user, app, site_settings, gateway)+ handle_fully_paid_order(+ manager,+ order_info,+ user=user,+ app=app,+ site_settings=site_settings,+ gateway=gateway,+ webhook_event_map=webhook_event_map,+ )else:- call_event(manager.order_updated, order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )def order_transaction_updated(@@ -385,11 +614,37 @@ def order_transaction_updated(site_settings: Optional["SiteSettings"] = None,):order_updated = False+ order_charged_to_call = False+ order_refunded_to_call = False+ webhook_events = set()if transaction_item.authorized_value != previous_authorized_value:+ webhook_events = {+ WebhookEventAsyncType.ORDER_UPDATED,+ *WebhookEventSyncType.ORDER_EVENTS,+ }order_updated = True+if transaction_item.charged_value > previous_charged_value:# order_updated False as order_charged triggers order_updatedorder_updated = False+ order_charged_to_call = True+ webhook_events = webhook_events.union(WEBHOOK_EVENTS_FOR_ORDER_CHARGED)++ elif transaction_item.charged_value != previous_charged_value:+ order_updated = True+ webhook_events.add(WebhookEventAsyncType.ORDER_UPDATED)+ webhook_events = webhook_events.union(WebhookEventSyncType.ORDER_EVENTS)++ if transaction_item.refunded_value > previous_refunded_value:+ # order_updated False as order_refunded triggers order_updated+ order_updated = False+ order_refunded_to_call = True+ webhook_events = webhook_events.union(WEBHOOK_EVENTS_FOR_ORDER_REFUNDED)++ webhook_event_map = (+ get_webhooks_for_multiple_events(webhook_events) if webhook_events else None+ )+ if order_charged_to_call:order_charged(order_info,user,@@ -398,13 +653,9 @@ def order_transaction_updated(payment=order_info.payment,site_settings=site_settings,manager=manager,+ webhook_event_map=webhook_event_map,)- elif transaction_item.charged_value != previous_charged_value:- order_updated = True-- if transaction_item.refunded_value > previous_refunded_value:- # order_updated False as order_refunded triggers order_updated- order_updated = False+ if order_refunded_to_call:order_refunded(order=order_info.order,user=user,@@ -412,10 +663,16 @@ def order_transaction_updated(amount=transaction_item.refunded_value - previous_refunded_value,payment=None,manager=manager,+ webhook_event_map=webhook_event_map,)-if order_updated:- call_event(manager.order_updated, order_info.order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order_info.order,+ webhook_event_map=webhook_event_map,+ )def fulfillment_tracking_updated(@@ -433,7 +690,12 @@ def fulfillment_tracking_updated(fulfillment=fulfillment,)call_event(manager.tracking_number_updated, fulfillment)- call_event(manager.order_updated, fulfillment.order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ fulfillment.order,+ )def cancel_fulfillment(@@ -465,7 +727,12 @@ def cancel_fulfillment(fulfillment.save(update_fields=["status"])update_order_status(fulfillment.order)call_event(manager.fulfillment_canceled, fulfillment)- call_event(manager.order_updated, fulfillment.order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ fulfillment.order,+ )return fulfillment@@ -494,7 +761,12 @@ def cancel_waiting_fulfillment(fulfillment.delete()update_order_status(fulfillment.order)call_event(manager.fulfillment_canceled, fulfillment)- call_event(manager.order_updated, fulfillment.order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ fulfillment.order,+ )def approve_fulfillment(@@ -571,10 +843,25 @@ def approve_fulfillment(order.refresh_from_db()update_order_status(order)- call_event(manager.order_updated, order)+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_FULFILLED+ )+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )call_event(manager.fulfillment_approved, fulfillment, notify_customer)if order.status == OrderStatus.FULFILLED:- call_event(manager.order_fulfilled, order)+ call_order_event(+ manager,+ manager.order_fulfilled,+ WebhookEventAsyncType.ORDER_FULFILLED,+ order,+ webhook_event_map=webhook_event_map,+ )if gift_card_lines_info:gift_cards_create(@@ -617,8 +904,15 @@ def mark_order_as_paid_with_transaction(app=app,transaction_reference=external_reference,)- call_event(manager.order_fully_paid, order)- call_event(manager.order_updated, order)+ call_order_event(+ manager,+ manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ )+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )def mark_order_as_paid_with_payment(@@ -666,15 +960,29 @@ def mark_order_as_paid_with_payment(transaction_reference=external_reference,)- call_event(manager.order_fully_paid, order)- call_event(manager.order_updated, order)-update_order_charge_data(order,)update_order_authorize_data(order,)+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_FULLY_PAID+ )+ call_order_event(+ manager,+ manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ webhook_event_map=webhook_event_map,+ )+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )def clean_mark_order_as_paid(order: "Order"):@@ -979,22 +1287,29 @@ def create_fulfillments(FulfillmentLine.objects.bulk_create(fulfillment_lines)order.refresh_from_db()- post_creation_func = (- order_fulfilled if approved else order_awaits_fulfillment_approval- )- transaction.on_commit(- lambda: post_creation_func(- fulfillments,- user,- app,- fulfillment_lines,- manager,- gift_card_lines_info,- site_settings,- notify_customer,+ if approved:+ transaction.on_commit(+ lambda: order_fulfilled(+ fulfillments,+ user,+ app,+ fulfillment_lines,+ manager,+ gift_card_lines_info,+ site_settings,+ notify_customer,+ )+ )+ else:+ transaction.on_commit(+ lambda: order_awaits_fulfillment_approval(+ fulfillments,+ user,+ app,+ fulfillment_lines,+ manager,+ ))- )-return fulfillments@@ -1219,7 +1534,9 @@ def create_refund_fulfillment(FulfillmentStatus.WAITING_FOR_APPROVAL,],).delete()- call_event(manager.order_updated, order)+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )return refunded_fulfillment@@ -1583,7 +1900,9 @@ def create_fulfillments_for_returned_products(],).delete()- call_event(manager.order_updated, order)+ call_order_event(+ manager, manager.order_updated, WebhookEventAsyncType.ORDER_UPDATED, order+ )return return_fulfillment, replace_fulfillment, new_orderdiff --git a/saleor/order/tasks.py b/saleor/order/tasks.pyindex fc96a80908..bfe77b03fd 100644--- a/saleor/order/tasks.py+++ b/saleor/order/tasks.py@@ -10,14 +10,14 @@ from ..celeryconf import appfrom ..channel.models import Channelfrom ..core.db.connection import allow_writerfrom ..core.tracing import traced_atomic_transaction-from ..core.utils.events import call_eventfrom ..discount.models import Voucher, VoucherCode, VoucherCustomerfrom ..payment.models import Payment, TransactionItemfrom ..plugins.manager import get_plugins_managerfrom ..warehouse.management import deallocate_stock_for_orders-from ..webhook.event_types import WebhookEventAsyncType-from ..webhook.utils import get_webhooks_for_event+from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ..webhook.utils import get_webhooks_for_multiple_eventsfrom . import OrderEvents, OrderStatus+from .actions import call_order_eventfrom .models import Order, OrderEventfrom .utils import invalidate_order_prices@@ -46,8 +46,20 @@ def recalculate_orders_task(order_ids: list[int]):@allow_writer()def send_order_updated(order_ids):manager = get_plugins_manager(allow_replica=True)+ webhook_event_map = get_webhooks_for_multiple_events(+ [+ WebhookEventAsyncType.ORDER_UPDATED,+ *WebhookEventSyncType.ORDER_EVENTS,+ ]+ )for order in Order.objects.filter(id__in=order_ids):- manager.order_updated(order)+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )def _bulk_release_voucher_usage(order_ids):@@ -92,11 +104,28 @@ def _call_expired_order_events(order_ids, manager):.filter(id__in=order_ids).select_related("channel"))- webhooks_order_expired = get_webhooks_for_event(WebhookEventAsyncType.ORDER_EXPIRED)- webhooks_order_updated = get_webhooks_for_event(WebhookEventAsyncType.ORDER_UPDATED)+ webhook_event_map = get_webhooks_for_multiple_events(+ [+ WebhookEventAsyncType.ORDER_EXPIRED,+ WebhookEventAsyncType.ORDER_UPDATED,+ # *WebhookEventSyncType.ORDER_EVENTS,+ ]+ )for order in orders:- call_event(manager.order_expired, order, webhooks=webhooks_order_expired)- call_event(manager.order_updated, order, webhooks=webhooks_order_updated)+ call_order_event(+ manager,+ manager.order_expired,+ WebhookEventAsyncType.ORDER_EXPIRED,+ order,+ webhook_event_map=webhook_event_map,+ )+ call_order_event(+ manager,+ manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )def _order_expired_events(order_ids):diff --git a/saleor/order/tests/test_actions.py b/saleor/order/tests/test_actions.pyindex b70b087764..a967baf208 100644--- a/saleor/order/tests/test_actions.py+++ b/saleor/order/tests/test_actions.py@@ -2,15 +2,16 @@ from unittest.mock import patchimport pytest+from ...webhook.utils import get_webhooks_for_multiple_eventsfrom .. import OrderStatus-from ..actions import order_created+from ..actions import WEBHOOK_EVENTS_FOR_ORDER_CREATED, order_confirmed, order_createdfrom ..fetch import OrderInfoparametrize_order_statuses = [(status,) for status, _ in OrderStatus.CHOICES]@pytest.mark.parametrize("order_status", parametrize_order_statuses)-@patch("saleor.order.actions.order_confirmed")+@patch("saleor.order.actions.order_confirmed", wraps=order_confirmed)def test_order_created_order_confirmed_with_turned_flag_on(mock_order_confirmed, order_status, order, customer_user, plugins_manager):@@ -27,12 +28,16 @@ def test_order_created_order_confirmed_with_turned_flag_on(lines_data=[],)+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CREATED+ )+# whenorder_created(order_info, user=customer_user, app=None, manager=plugins_manager)# thenmock_order_confirmed.assert_called_once_with(- order, customer_user, None, plugins_manager+ order, customer_user, None, plugins_manager, webhook_event_map=webhook_event_map)diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex 459358e771..18a8315084 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -1,10 +1,12 @@from decimal import Decimal-from unittest.mock import patch+from unittest.mock import call, patchimport pytest+from django.test import override_settingsfrom prices import Money, TaxedMoneyfrom ...channel import MarkAsPaidStrategy+from ...core.models import EventDeliveryfrom ...giftcard import GiftCardEventsfrom ...giftcard.models import GiftCard, GiftCardEventfrom ...order.fetch import OrderLineInfo, fetch_order_info@@ -15,6 +17,8 @@ from ...product.models import DigitalContentfrom ...product.tests.utils import create_imagefrom ...tests.utils import flush_post_commit_hooksfrom ...warehouse.models import Allocation, Stock+from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ...webhook.utils import get_webhooks_for_multiple_eventsfrom .. import (FulfillmentStatus,OrderAuthorizeStatus,@@ -23,7 +27,14 @@ from .. import (OrderStatus,)from ..actions import (+ WEBHOOK_EVENTS_FOR_FULLY_PAID,+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED,+ WEBHOOK_EVENTS_FOR_ORDER_CHARGED,+ WEBHOOK_EVENTS_FOR_ORDER_CREATED,+ WEBHOOK_EVENTS_FOR_ORDER_FULFILLED,+ WEBHOOK_EVENTS_FOR_ORDER_REFUNDED,automatically_fulfill_digital_lines,+ call_order_event,cancel_fulfillment,cancel_order,clean_mark_order_as_paid,@@ -31,9 +42,17 @@ from ..actions import (handle_fully_paid_order,mark_order_as_paid_with_payment,mark_order_as_paid_with_transaction,+ order_authorized,+ order_awaits_fulfillment_approval,+ order_charged,+ order_confirmed,+ order_created,+ order_fulfilled,order_refunded,order_transaction_updated,+ order_voided,)+from ..fetch import OrderInfofrom ..models import Fulfillment, OrderLinefrom ..notifications import (send_fulfillment_confirmation_to_customer,@@ -96,6 +115,7 @@ def test_handle_fully_paid_order_digital_lines(send_fulfillment_confirmation_to_customer,order_with_digital_line,):+ # givenorder = order_with_digital_lineorder.payments.add(Payment.objects.create())redirect_url = "http://localhost.pl"@@ -105,8 +125,12 @@ def test_handle_fully_paid_order_digital_lines(order_info = fetch_order_info(order)manager = get_plugins_manager(allow_replica=False)- handle_fully_paid_order(manager, order_info)+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)++ # when+ handle_fully_paid_order(manager, order_info, webhook_event_map=webhook_event_map)+ # thenfulfillment = order.fulfillments.first()event_order_paid = order.events.get()@@ -124,13 +148,18 @@ def test_handle_fully_paid_order_digital_lines(@patch("saleor.order.actions.send_payment_confirmation")def test_handle_fully_paid_order(mock_send_payment_confirmation, order):+ # givenmanager = get_plugins_manager(allow_replica=False)order.payments.add(Payment.objects.create())order_info = fetch_order_info(order)- handle_fully_paid_order(manager, order_info)+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)++ # when+ handle_fully_paid_order(manager, order_info, webhook_event_map=webhook_event_map)+ # thenevent_order_paid = order.events.get()assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID@@ -139,12 +168,17 @@ def test_handle_fully_paid_order(mock_send_payment_confirmation, order):@patch("saleor.order.notifications.send_payment_confirmation")def test_handle_fully_paid_order_no_email(mock_send_payment_confirmation, order):+ # givenorder.user = Noneorder.user_email = ""manager = get_plugins_manager(allow_replica=False)order_info = fetch_order_info(order)- handle_fully_paid_order(manager, order_info)+ # when+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)++ # then+ handle_fully_paid_order(manager, order_info, webhook_event_map=webhook_event_map)event = order.events.get()assert event.type == OrderEvents.ORDER_FULLY_PAIDassert not mock_send_payment_confirmation.called@@ -158,8 +192,15 @@ def test_handle_fully_paid_order_with_gateway(mock_send_payment_confirmation, ororder.payments.add(Payment.objects.create())order_info = fetch_order_info(order)+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)+# when- handle_fully_paid_order(manager, order_info, gateway="mirumee.payments.dummy")+ handle_fully_paid_order(+ manager,+ order_info,+ gateway="mirumee.payments.dummy",+ webhook_event_map=webhook_event_map,+ )# thenevent_order_paid = order.events.get()@@ -178,6 +219,7 @@ def test_handle_fully_paid_order_gift_cards_created(order_with_lines,non_shippable_gift_card_product,shippable_gift_card_product,+ django_capture_on_commit_callbacks,):"""Test that digital gift cards are issued when automatic fulfillment is enabled."""# given@@ -214,16 +256,25 @@ def test_handle_fully_paid_order_gift_cards_created(order.payments.add(Payment.objects.create())order_info = fetch_order_info(order)+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)+# when- handle_fully_paid_order(manager, order_info)+ with django_capture_on_commit_callbacks(execute=False) as callbacks:+ handle_fully_paid_order(+ manager, order_info, webhook_event_map=webhook_event_map+ )++ # second on_commit_callbacks as callbacks from first iteration triggers other+ # on_commit callbacks+ with django_capture_on_commit_callbacks(execute=True):+ for callback in callbacks:+ callback()# then- flush_post_commit_hooks()assert order.events.filter(type=OrderEvents.ORDER_FULLY_PAID)mock_send_payment_confirmation.assert_called_once_with(order_info, manager)- flush_post_commit_hooks()gift_card = GiftCard.objects.get()assert gift_card.initial_balance == non_shippable_gift_card_line.unit_price_grossassert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)@@ -249,6 +300,7 @@ def test_handle_fully_paid_order_gift_cards_not_created(order_with_lines,non_shippable_gift_card_product,shippable_gift_card_product,+ django_capture_on_commit_callbacks,):"""Ensure digital gift cards are not issued when automatic fulfillment is disabled."""# given@@ -285,16 +337,25 @@ def test_handle_fully_paid_order_gift_cards_not_created(order.payments.add(Payment.objects.create())order_info = fetch_order_info(order)+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)+# when- handle_fully_paid_order(manager, order_info)+ with django_capture_on_commit_callbacks(execute=False) as callbacks:+ handle_fully_paid_order(+ manager, order_info, webhook_event_map=webhook_event_map+ )++ # second on_commit_callbacks as callbacks from first iteration triggers other+ # on_commit callbacks+ with django_capture_on_commit_callbacks(execute=True):+ for callback in callbacks:+ callback()# then- flush_post_commit_hooks()assert order.events.filter(type=OrderEvents.ORDER_FULLY_PAID)mock_send_payment_confirmation.assert_called_once_with(order_info, manager)- flush_post_commit_hooks()assert not GiftCard.objects.exists()send_notification_mock.assert_not_called@@ -315,7 +376,9 @@ def test_handle_fully_paid_order_for_draft_order(order_info = fetch_order_info(draft_order)# when- handle_fully_paid_order(manager, order_info)+ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)++ handle_fully_paid_order(manager, order_info, webhook_event_map=webhook_event_map)# thenevent_order_paid = draft_order.events.get()@@ -325,6 +388,119 @@ def test_handle_fully_paid_order_for_draft_order(mock_send_payment_confirmation.assert_called_once_with(order_info, manager)+@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_handle_fully_paid_order_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ customer_user,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ ]+ )+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.charge_status = OrderChargeStatus.FULL+ order.save(update_fields=["status", "should_refresh_prices", "charge_status"])++ order.channel.automatically_confirm_all_new_orders = False+ order.channel.save(update_fields=["automatically_confirm_all_new_orders"])++ order_info = OrderInfo(+ order=order,+ customer_email=order.get_customer_email(),+ channel=order.channel,+ payment=order.get_last_payment(),+ lines_data=[],+ )++ webhook_event_map = get_webhooks_for_multiple_events(WEBHOOK_EVENTS_FOR_FULLY_PAID)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ handle_fully_paid_order(plugins_manager, order_info, webhook_event_map)++ # then+ # confirm that event delivery was generated for each webhook.+ order_fully_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_PAID,+ )+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)++ order_deliveries = [order_updated_delivery, order_fully_paid_delivery]+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ ],+ any_order=True,+ )++def test_mark_as_paid_with_payment(admin_user, draft_order):manager = get_plugins_manager(allow_replica=False)mark_order_as_paid_with_payment(draft_order, admin_user, None, manager)@@ -458,6 +634,7 @@ def test_cancel_fulfillment_variant_witout_inventory_tracking(def test_cancel_order(send_order_canceled_confirmation_mock,fulfilled_order_with_all_cancelled_fulfillments,+ django_capture_on_commit_callbacks,):# givenorder = fulfilled_order_with_all_cancelled_fulfillments@@ -468,7 +645,8 @@ def test_cancel_order().exists()# when- cancel_order(order, None, None, manager)+ with django_capture_on_commit_callbacks(execute=True):+ cancel_order(order, None, None, manager)# thenorder_event = order.events.last()@@ -479,12 +657,122 @@ def test_cancel_order(order_line__order=order, quantity_allocated__gt=0).exists()- flush_post_commit_hooks()send_order_canceled_confirmation_mock.assert_called_once_with(order, None, None, manager)+@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_cancel_order_dont_trigger_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_CANCELLED,+ ]+ )++ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CANCELED+ )++ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.charge_status = OrderChargeStatus.FULL+ order.save(update_fields=["status", "should_refresh_prices", "charge_status"])++ # when+ with django_capture_on_commit_callbacks(execute=True):+ cancel_order(order, None, None, plugins_manager)++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_cancelled_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CANCELLED,+ )+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not tax_delivery+ assert not filter_shipping_delivery++ order_deliveries = [+ order_cancelled_delivery,+ order_updated_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ assert not mocked_send_webhook_request_sync.called++ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ webhooks=webhook_event_map.get(+ WebhookEventAsyncType.ORDER_UPDATED, set()+ ),+ ),+ call(+ plugins_manager,+ plugins_manager.order_cancelled,+ WebhookEventAsyncType.ORDER_CANCELLED,+ order,+ webhook_event_map=webhook_event_map,+ webhooks=webhook_event_map.get(+ WebhookEventAsyncType.ORDER_CANCELLED, set()+ ),+ ),+ ],+ any_order=True,+ )++@patch("saleor.plugins.manager.PluginsManager.order_refunded")@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")@patch("saleor.order.actions.send_order_refunded_confirmation")@@ -551,128 +839,745 @@ def test_order_refunded_by_app(order_refunded_mock.assert_called_once_with(order)-def test_fulfill_order_lines(order_with_lines):- order = order_with_lines- line = order.lines.first()- quantity_fulfilled_before = line.quantity_fulfilled- variant = line.variant- stock = Stock.objects.get(product_variant=variant)- stock_quantity_after = stock.quantity - line.quantity-- fulfill_order_lines(+@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_refunded_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ app,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks([- OrderLineInfo(- line=line,- quantity=line.quantity,- variant=variant,- warehouse_pk=stock.warehouse.pk,- )- ],- get_plugins_manager(allow_replica=False),+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ ])- stock.refresh_from_db()- assert stock.quantity == stock_quantity_after- assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])+ payment = Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ order=order,+ charge_status=ChargeStatus.FULLY_REFUNDED,+ )+ payment.transactions.create(+ kind=TransactionKind.REFUND,+ is_success=True,+ amount=order.total.gross.amount,+ gateway_response={},+ )+ amount = order.total.gross.amount+ plugins_manager = get_plugins_manager(allow_replica=False)-def test_fulfill_order_lines_multiple_lines(order_with_lines):- order = order_with_lines- lines = order.lines.all()+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_REFUNDED+ )- assert lines.count() > 1+ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_refunded(order, None, app, amount, payment, plugins_manager)- quantity_fulfilled_before_1 = lines[0].quantity_fulfilled- variant_1 = lines[0].variant- stock_1 = Stock.objects.get(product_variant=variant_1)- stock_quantity_after_1 = stock_1.quantity - lines[0].quantity+ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_refunded_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_REFUNDED,+ )+ order_fully_refunded_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )+ order_deliveries = [+ order_updated_delivery,+ order_fully_refunded_delivery,+ order_refunded_delivery,+ ]- quantity_fulfilled_before_2 = lines[1].quantity_fulfilled- variant_2 = lines[1].variant- stock_2 = Stock.objects.get(product_variant=variant_2)- stock_quantity_after_2 = stock_2.quantity - lines[1].quantity+ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )- fulfill_order_lines(+ wrapped_call_order_event.assert_has_calls([- OrderLineInfo(- line=lines[0],- quantity=lines[0].quantity,- variant=variant_1,- warehouse_pk=stock_1.warehouse.pk,+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,),- OrderLineInfo(- line=lines[1],- quantity=lines[1].quantity,- variant=variant_2,- warehouse_pk=stock_2.warehouse.pk,+ call(+ plugins_manager,+ plugins_manager.order_refunded,+ WebhookEventAsyncType.ORDER_REFUNDED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_fully_refunded,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ order,+ webhook_event_map=webhook_event_map,),],- get_plugins_manager(allow_replica=False),+ any_order=True,)- stock_1.refresh_from_db()- assert stock_1.quantity == stock_quantity_after_1- assert (- lines[0].quantity_fulfilled == quantity_fulfilled_before_1 + lines[0].quantity++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_voided_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ app,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ WebhookEventAsyncType.ORDER_UPDATED,)- stock_2.refresh_from_db()- assert stock_2.quantity == stock_quantity_after_2- assert (- lines[1].quantity_fulfilled == quantity_fulfilled_before_2 + lines[1].quantity+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ payment = Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ order=order,+ charge_status=ChargeStatus.FULLY_REFUNDED,)+ plugins_manager = get_plugins_manager(allow_replica=False)-def test_fulfill_order_lines_with_variant_deleted(order_with_lines):- line = order_with_lines.lines.first()- line.variant.delete()+ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_voided(order, None, app, payment, plugins_manager)- line.refresh_from_db()+ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )- fulfill_order_lines(- [OrderLineInfo(line=line, quantity=line.quantity)],- get_plugins_manager(allow_replica=False),+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,)+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ wrapped_call_order_event.assert_called_once_with(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ )-def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):- order = order_with_lines- line = order.lines.first()- quantity_fulfilled_before = line.quantity_fulfilled- variant = line.variant- variant.track_inventory = False- variant.save()- stock = Stock.objects.get(product_variant=variant)- # stock should not change- stock_quantity_after = stock.quantity+@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_fulfilled_dont_trigger_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ fulfilled_order,+ settings,+ site_settings,+ django_capture_on_commit_callbacks,+ app,+):+ # given+ fulfillment = fulfilled_order.fulfillments.first()+ fulfillment_lines = list(fulfillment.lines.all())+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [WebhookEventAsyncType.ORDER_UPDATED, WebhookEventAsyncType.ORDER_FULFILLED]+ )+ plugins_manager = get_plugins_manager(allow_replica=False)- fulfill_order_lines(+ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_FULFILLED+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_fulfilled(+ [fulfillment],+ None,+ app,+ fulfillment_lines,+ plugins_manager,+ [],+ site_settings,+ )++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_fulfilled_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULFILLED,+ )+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not tax_delivery+ assert not filter_shipping_delivery++ order_deliveries = [+ order_updated_delivery,+ order_fulfilled_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls([- OrderLineInfo(- line=line,- quantity=line.quantity,- variant=variant,- warehouse_pk=stock.warehouse.pk,+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},)+ for delivery in order_deliveries],- get_plugins_manager(allow_replica=False),+ any_order=True,)+ assert not mocked_send_webhook_request_sync.called- stock.refresh_from_db()- assert stock.quantity == stock_quantity_after- assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity+ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ fulfilled_order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_fulfilled,+ WebhookEventAsyncType.ORDER_FULFILLED,+ fulfilled_order,+ webhook_event_map=webhook_event_map,+ ),+ ],+ any_order=True,+ )-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer")-@patch("saleor.order.utils.get_default_digital_content_settings")-@patch("saleor.plugins.manager.PluginsManager.fulfillment_created")-def test_fulfill_digital_lines(- mock_fulfillment_created,- mock_digital_settings,- mock_email_fulfillment,- order_with_lines,- media_root,+@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_awaits_fulfillment_approval_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ fulfilled_order,+ settings,+ site_settings,+ django_capture_on_commit_callbacks,+ app,+):+ # given+ fulfillment = fulfilled_order.fulfillments.first()+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL+ fulfillment.save()+ fulfillment_lines = list(fulfillment.lines.all())++ order = fulfilled_order+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_UPDATED,+ ]+ )+ plugins_manager = get_plugins_manager(allow_replica=False)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_awaits_fulfillment_approval(+ [fulfillment],+ None,+ app,+ fulfillment_lines,+ plugins_manager,+ )++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ wrapped_call_order_event.assert_called_once_with(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ fulfilled_order,+ )+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_authorized_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ app,+):+ # given++ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_UPDATED,+ ]+ )+ payment = Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ order=order,+ charge_status=ChargeStatus.FULLY_REFUNDED,+ )++ plugins_manager = get_plugins_manager(allow_replica=False)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_authorized(+ order, None, app, order.total.gross.amount, payment, plugins_manager+ )++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ wrapped_call_order_event.assert_called_once_with(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=None,+ )+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_charged_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ app,+):+ # given++ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.charge_status = OrderChargeStatus.FULL+ order.save(update_fields=["status", "should_refresh_prices", "charge_status"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_UPDATED,+ ]+ )++ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CHARGED+ )++ plugins_manager = get_plugins_manager(allow_replica=False)+ order_info = fetch_order_info(order)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_charged(+ order_info, None, app, order.total.gross.amount, None, plugins_manager+ )++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_fully_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_PAID,+ )+ order_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_PAID,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ order_deliveries = [+ order_updated_delivery,+ order_fully_paid_delivery,+ order_paid_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )++ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_paid,+ WebhookEventAsyncType.ORDER_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ ],+ any_order=True,+ )+++def test_fulfill_order_lines(order_with_lines):+ order = order_with_lines+ line = order.lines.first()+ quantity_fulfilled_before = line.quantity_fulfilled+ variant = line.variant+ stock = Stock.objects.get(product_variant=variant)+ stock_quantity_after = stock.quantity - line.quantity++ fulfill_order_lines(+ [+ OrderLineInfo(+ line=line,+ quantity=line.quantity,+ variant=variant,+ warehouse_pk=stock.warehouse.pk,+ )+ ],+ get_plugins_manager(allow_replica=False),+ )++ stock.refresh_from_db()+ assert stock.quantity == stock_quantity_after+ assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity+++def test_fulfill_order_lines_multiple_lines(order_with_lines):+ order = order_with_lines+ lines = order.lines.all()++ assert lines.count() > 1++ quantity_fulfilled_before_1 = lines[0].quantity_fulfilled+ variant_1 = lines[0].variant+ stock_1 = Stock.objects.get(product_variant=variant_1)+ stock_quantity_after_1 = stock_1.quantity - lines[0].quantity++ quantity_fulfilled_before_2 = lines[1].quantity_fulfilled+ variant_2 = lines[1].variant+ stock_2 = Stock.objects.get(product_variant=variant_2)+ stock_quantity_after_2 = stock_2.quantity - lines[1].quantity++ fulfill_order_lines(+ [+ OrderLineInfo(+ line=lines[0],+ quantity=lines[0].quantity,+ variant=variant_1,+ warehouse_pk=stock_1.warehouse.pk,+ ),+ OrderLineInfo(+ line=lines[1],+ quantity=lines[1].quantity,+ variant=variant_2,+ warehouse_pk=stock_2.warehouse.pk,+ ),+ ],+ get_plugins_manager(allow_replica=False),+ )++ stock_1.refresh_from_db()+ assert stock_1.quantity == stock_quantity_after_1+ assert (+ lines[0].quantity_fulfilled == quantity_fulfilled_before_1 + lines[0].quantity+ )++ stock_2.refresh_from_db()+ assert stock_2.quantity == stock_quantity_after_2+ assert (+ lines[1].quantity_fulfilled == quantity_fulfilled_before_2 + lines[1].quantity+ )+++def test_fulfill_order_lines_with_variant_deleted(order_with_lines):+ line = order_with_lines.lines.first()+ line.variant.delete()++ line.refresh_from_db()++ fulfill_order_lines(+ [OrderLineInfo(line=line, quantity=line.quantity)],+ get_plugins_manager(allow_replica=False),+ )+++def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):+ order = order_with_lines+ line = order.lines.first()+ quantity_fulfilled_before = line.quantity_fulfilled+ variant = line.variant+ variant.track_inventory = False+ variant.save()+ stock = Stock.objects.get(product_variant=variant)++ # stock should not change+ stock_quantity_after = stock.quantity++ fulfill_order_lines(+ [+ OrderLineInfo(+ line=line,+ quantity=line.quantity,+ variant=variant,+ warehouse_pk=stock.warehouse.pk,+ )+ ],+ get_plugins_manager(allow_replica=False),+ )++ stock.refresh_from_db()+ assert stock.quantity == stock_quantity_after+ assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity+++@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer")+@patch("saleor.order.utils.get_default_digital_content_settings")+@patch("saleor.plugins.manager.PluginsManager.fulfillment_created")+def test_fulfill_digital_lines(+ mock_fulfillment_created,+ mock_digital_settings,+ mock_email_fulfillment,+ order_with_lines,+ media_root,):mock_digital_settings.return_value = {"automatic_fulfillment": True}line = order_with_lines.lines.all()[0]@@ -739,59 +1644,437 @@ def test_fulfill_digital_lines_no_allocation(variant.track_inventory = Falsevariant.save()- line.is_shipping_required = False- line.allocations.all().delete()- line.save()+ line.is_shipping_required = False+ line.allocations.all().delete()+ line.save()++ order_with_lines.refresh_from_db()+ order_info = fetch_order_info(order_with_lines)+ manager = get_plugins_manager(allow_replica=False)++ # when+ automatically_fulfill_digital_lines(order_info, manager)++ # then+ line.refresh_from_db()+ fulfillment = Fulfillment.objects.get(order=order_with_lines)+ fulfillment_lines = fulfillment.lines.all()++ assert fulfillment_lines.count() == 1+ assert line.digital_content_url+ assert mock_email_fulfillment.called+ mock_fulfillment_created.assert_called_once_with(fulfillment)+++@patch("saleor.plugins.manager.PluginsManager.order_updated")+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")+def test_order_transaction_updated_order_fully_paid(+ order_fully_paid, order_updated, order_with_lines, transaction_item_generator+):+ # given+ order_info = fetch_order_info(order_with_lines)+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk, charged_value=order_with_lines.total.gross.amount+ )+ manager = get_plugins_manager(allow_replica=False)+ updates_amounts_for_order(+ order_with_lines,+ )++ # when+ order_transaction_updated(+ order_info=order_info,+ transaction_item=transaction_item,+ manager=manager,+ user=None,+ app=None,+ previous_authorized_value=Decimal(0),+ previous_charged_value=Decimal(0),+ previous_refunded_value=Decimal(0),+ )++ # then+ flush_post_commit_hooks()+ order_fully_paid.assert_called_once_with(order_with_lines)+ order_updated.assert_called_once_with(order_with_lines)+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_transaction_updated_for_charged_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ transaction_item_generator,+ django_capture_on_commit_callbacks,+ app,+ settings,+):+ # given+ plugins_manager = get_plugins_manager(allow_replica=False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_UPDATED,+ ]+ )+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CHARGED+ )++ order_info = fetch_order_info(order_with_lines)+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk,+ charged_value=order_with_lines.total.gross.amount,+ )++ updates_amounts_for_order(+ order_with_lines,+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_transaction_updated(+ order_info=order_info,+ transaction_item=transaction_item,+ manager=plugins_manager,+ user=None,+ app=None,+ previous_authorized_value=Decimal(0),+ previous_charged_value=Decimal(0),+ previous_refunded_value=Decimal(0),+ )++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_fully_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_PAID,+ )+ order_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_PAID,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )+ order_deliveries = [+ order_updated_delivery,+ order_fully_paid_delivery,+ order_paid_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )++ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_paid,+ WebhookEventAsyncType.ORDER_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ ],+ any_order=True,+ )+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_transaction_updated_for_authorized_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ transaction_item_generator,+ django_capture_on_commit_callbacks,+ app,+ settings,+):+ # given+ plugins_manager = get_plugins_manager(allow_replica=False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ WebhookEventAsyncType.ORDER_UPDATED,+ )+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ webhook_event_map = get_webhooks_for_multiple_events(+ [WebhookEventAsyncType.ORDER_UPDATED, *WebhookEventSyncType.ORDER_EVENTS]+ )- order_with_lines.refresh_from_db()order_info = fetch_order_info(order_with_lines)- manager = get_plugins_manager(allow_replica=False)+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk,+ authorized_value=order_with_lines.total.gross.amount,+ )++ updates_amounts_for_order(+ order_with_lines,+ )# when- automatically_fulfill_digital_lines(order_info, manager)+ with django_capture_on_commit_callbacks(execute=True):+ order_transaction_updated(+ order_info=order_info,+ transaction_item=transaction_item,+ manager=plugins_manager,+ user=None,+ app=None,+ previous_authorized_value=Decimal(0),+ previous_charged_value=Decimal(0),+ previous_refunded_value=Decimal(0),+ )# then- line.refresh_from_db()- fulfillment = Fulfillment.objects.get(order=order_with_lines)- fulfillment_lines = fulfillment.lines.all()+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )- assert fulfillment_lines.count() == 1- assert line.digital_content_url- assert mock_email_fulfillment.called- mock_fulfillment_created.assert_called_once_with(fulfillment)+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )-@patch("saleor.plugins.manager.PluginsManager.order_updated")-@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")-def test_order_transaction_updated_order_fully_paid(- order_fully_paid, order_updated, order_with_lines, transaction_item_generator+ wrapped_call_order_event.assert_called_once_with(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ )+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_transaction_updated_for_refunded_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ transaction_item_generator,+ django_capture_on_commit_callbacks,+ app,+ settings,):# given+ plugins_manager = get_plugins_manager(allow_replica=False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ ]+ )+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_REFUNDED+ )+order_info = fetch_order_info(order_with_lines)transaction_item = transaction_item_generator(- order_id=order_with_lines.pk, charged_value=order_with_lines.total.gross.amount+ order_id=order_with_lines.pk,+ refunded_value=order_with_lines.total.gross.amount,)- manager = get_plugins_manager(allow_replica=False)+updates_amounts_for_order(order_with_lines,)# when- order_transaction_updated(- order_info=order_info,- transaction_item=transaction_item,- manager=manager,- user=None,- app=None,- previous_authorized_value=Decimal(0),- previous_charged_value=Decimal(0),- previous_refunded_value=Decimal(0),- )+ with django_capture_on_commit_callbacks(execute=True):+ order_transaction_updated(+ order_info=order_info,+ transaction_item=transaction_item,+ manager=plugins_manager,+ user=None,+ app=None,+ previous_authorized_value=Decimal(0),+ previous_charged_value=Decimal(0),+ previous_refunded_value=Decimal(0),+ )# then- flush_post_commit_hooks()- order_fully_paid.assert_called_once_with(order_with_lines)- order_updated.assert_called_once_with(order_with_lines)+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )+ order_refunded_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_REFUNDED,+ )+ order_fully_refunded_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )+ order_deliveries = [+ order_updated_delivery,+ order_fully_refunded_delivery,+ order_refunded_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )++ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_refunded,+ WebhookEventAsyncType.ORDER_REFUNDED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_fully_refunded,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ ],+ any_order=True,+ )@patch("saleor.plugins.manager.PluginsManager.order_updated")@@ -1157,3 +2440,677 @@ def test_order_transaction_updated_order_fully_refunded_with_transaction_and_payflush_post_commit_hooks()order_refunded.assert_called_once_with(order_with_lines)order_fully_refunded.assert_called_once_with(order_with_lines)+++ "webhook_event",+ [+ WebhookEventAsyncType.ORDER_CREATED,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_CANCELLED,+ WebhookEventAsyncType.ORDER_EXPIRED,+ WebhookEventAsyncType.ORDER_FULFILLED,+ WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ ],+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_triggers_sync_webhook(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ webhook_event,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ getattr(plugins_manager, webhook_event),+ webhook_event,+ order,+ )++ # then+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+++ "webhook_event",+ [+ WebhookEventAsyncType.ORDER_CREATED,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_CANCELLED,+ WebhookEventAsyncType.ORDER_EXPIRED,+ WebhookEventAsyncType.ORDER_FULFILLED,+ WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ ],+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_missing_filter_shipping_method_webhook(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ webhook_event,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ shipping_filter_webhook.is_active = False+ shipping_filter_webhook.save(update_fields=["is_active"])++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ getattr(plugins_manager, webhook_event),+ webhook_event,+ order,+ )++ # then+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not filter_shipping_delivery++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_called_once_with(tax_delivery)+++ "webhook_event",+ [+ WebhookEventAsyncType.ORDER_CREATED,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_CANCELLED,+ WebhookEventAsyncType.ORDER_EXPIRED,+ WebhookEventAsyncType.ORDER_FULFILLED,+ WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,+ ],+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_skips_tax_webhook_when_prices_are_valid(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ webhook_event,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(+ update_fields=[+ "status",+ ]+ )++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ getattr(plugins_manager, webhook_event),+ webhook_event,+ order,+ )++ # then+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )+ assert not tax_delivery+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_called_once_with(+ filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT+ )+++ "webhook_event",+ [+ WebhookEventAsyncType.ORDER_CREATED,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_REFUNDED,+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_CANCELLED,+ WebhookEventAsyncType.ORDER_EXPIRED,+ WebhookEventAsyncType.ORDER_FULFILLED,+ WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,+ ],+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_skips_sync_webhooks_when_order_not_editable(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+ webhook_event,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.UNFULFILLED+ order.save(+ update_fields=[+ "status",+ ]+ )++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(webhook_event)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ getattr(plugins_manager, webhook_event),+ webhook_event,+ order,+ )++ # then+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not filter_shipping_delivery+ assert not tax_delivery+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ assert not mocked_send_webhook_request_sync.called+++@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_skips_sync_webhooks_when_draft_order_deleted(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order.save(update_fields=["status"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ order_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.DRAFT_ORDER_DELETED)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ plugins_manager.draft_order_deleted,+ WebhookEventAsyncType.DRAFT_ORDER_DELETED,+ order,+ )++ # then+ order_delivery = EventDelivery.objects.get(webhook_id=order_webhook.id)+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not filter_shipping_delivery+ assert not tax_delivery+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ assert not mocked_send_webhook_request_sync.called+++@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_skips_when_async_webhooks_missing(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ checkout_webhook,+ ) = setup_order_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ plugins_manager.order_created,+ WebhookEventAsyncType.ORDER_CREATED,+ order,+ )++ # then+ tax_delivery = EventDelivery.objects.filter(webhook_id=tax_webhook.id).first()+ filter_shipping_delivery = EventDelivery.objects.filter(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ ).first()+ assert not filter_shipping_delivery+ assert not tax_delivery+ assert not mocked_send_webhook_request_async.called+ assert not mocked_send_webhook_request_sync.called+++@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_call_order_event_for_order_event_skips_when_sync_webhooks_missing(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ order_with_lines,+ settings,+ webhook,+ permission_manage_orders,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ webhook.app.permissions.add(permission_manage_orders)++ mocked_send_webhook_request_sync.return_value = []++ # when+ with django_capture_on_commit_callbacks(execute=True):+ call_order_event(+ plugins_manager,+ plugins_manager.order_created,+ WebhookEventAsyncType.ORDER_CREATED,+ order,+ )++ # then+ order_delivery = EventDelivery.objects.get(webhook_id=webhook.id)+ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ assert not mocked_send_webhook_request_sync.called+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_created_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ customer_user,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_CREATED,+ WebhookEventAsyncType.ORDER_PAID,+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ ]+ )+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.charge_status = OrderChargeStatus.FULL+ order.save(update_fields=["status", "should_refresh_prices", "charge_status"])++ order.channel.automatically_confirm_all_new_orders = True+ order.channel.save(update_fields=["automatically_confirm_all_new_orders"])+ order_info = OrderInfo(+ order=order,+ customer_email=order.get_customer_email(),+ channel=order.channel,+ payment=order.get_last_payment(),+ lines_data=[],+ )++ webhook_event_map = get_webhooks_for_multiple_events(+ WEBHOOK_EVENTS_FOR_ORDER_CREATED+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_created(order_info, user=customer_user, app=None, manager=plugins_manager)++ # then+ # confirm that event delivery was generated for each webhook.+ order_confirmed_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CONFIRMED,+ )+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CREATED,+ )+ order_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_PAID,+ )+ order_fully_paid_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_FULLY_PAID,+ )+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )+ order_deliveries = [+ order_confirmed_delivery,+ order_updated_delivery,+ order_paid_delivery,+ order_fully_paid_delivery,+ ]++ mocked_send_webhook_request_async.assert_has_calls(+ [+ call(+ kwargs={"event_delivery_id": delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ for delivery in order_deliveries+ ],+ any_order=True,+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ wrapped_call_order_event.assert_has_calls(+ [+ call(+ plugins_manager,+ plugins_manager.order_created,+ WebhookEventAsyncType.ORDER_CREATED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_confirmed,+ WebhookEventAsyncType.ORDER_CONFIRMED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_paid,+ WebhookEventAsyncType.ORDER_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_fully_paid,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ order,+ webhook_event_map=webhook_event_map,+ ),+ call(+ plugins_manager,+ plugins_manager.order_updated,+ WebhookEventAsyncType.ORDER_UPDATED,+ order,+ webhook_event_map=webhook_event_map,+ ),+ ],+ any_order=True,+ )+++@patch(+ "saleor.order.actions.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_order_confirmed_triggers_webhooks(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ customer_user,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ plugins_manager = get_plugins_manager(False)+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_CONFIRMED,+ ]+ )++ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(update_fields=["status", "should_refresh_prices"])++ # when+ with django_capture_on_commit_callbacks(execute=True):+ order_confirmed(order, user=customer_user, app=None, manager=plugins_manager)++ # then+ # confirm that event delivery was generated for each webhook.+ order_confirmed_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_CONFIRMED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_confirmed_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/order/tests/test_tasks.py b/saleor/order/tests/test_tasks.pyindex dc2bd1e779..8bb3451dc7 100644--- a/saleor/order/tests/test_tasks.py+++ b/saleor/order/tests/test_tasks.py@@ -1,20 +1,25 @@import loggingfrom datetime import timedeltafrom unittest import mock-from unittest.mock import patch+from unittest.mock import call, patchimport pytest+from django.test import override_settingsfrom django.utils import timezonefrom freezegun import freeze_time+from ...core.models import EventDeliveryfrom ...discount.models import VoucherCustomerfrom ...warehouse.models import Allocation+from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom .. import OrderEvents, OrderStatus+from ..actions import call_order_eventfrom ..models import Order, OrderEvent, get_order_numberfrom ..tasks import (_bulk_release_voucher_usage,delete_expired_orders_task,expire_orders_task,+ send_order_updated,)@@ -683,3 +688,76 @@ def test_bulk_release_voucher_usage_voucher_usage_mismatch(code.refresh_from_db()assert code.used == 0assert code.code in caplog.text+++@patch(+ "saleor.order.tasks.call_order_event",+ wraps=call_order_event,+)+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_send_order_updated(+ mocked_send_webhook_request_async,+ mocked_send_webhook_request_sync,+ wrapped_call_order_event,+ setup_order_webhooks,+ order_with_lines,+ settings,+ django_capture_on_commit_callbacks,+):+ # given+ mocked_send_webhook_request_sync.return_value = []+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_order_webhook,+ ) = setup_order_webhooks(+ [+ WebhookEventAsyncType.ORDER_UPDATED,+ WebhookEventAsyncType.ORDER_FULLY_PAID,+ ]+ )+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.should_refresh_prices = True+ order.save(+ update_fields=[+ "status",+ "should_refresh_prices",+ ]+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ send_order_updated([order.pk])++ # then+ # confirm that event delivery was generated for each webhook.+ order_updated_delivery = EventDelivery.objects.get(+ webhook_id=additional_order_webhook.id,+ event_type=WebhookEventAsyncType.ORDER_UPDATED,+ )++ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)+ filter_shipping_delivery = EventDelivery.objects.get(+ webhook_id=shipping_filter_webhook.id,+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ )++ mocked_send_webhook_request_async.assert_called_once_with(+ kwargs={"event_delivery_id": order_updated_delivery.id},+ queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ mocked_send_webhook_request_sync.assert_has_calls(+ [+ call(tax_delivery),+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),+ ]+ )+ assert wrapped_call_order_event.calleddiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f457a6e827..c5ada61dac 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -8,7 +8,7 @@ from datetime import timedeltafrom decimal import Decimalfrom functools import partialfrom io import BytesIO-from typing import Callable, Optional+from typing import Callable, Optional, Unionfrom unittest.mock import MagicMockimport graphene@@ -9555,3 +9555,188 @@ def setup_checkout_webhooks()return _setup+++def setup_order_webhooks(+ permission_handle_taxes,+ permission_manage_shipping,+ permission_manage_orders,+):+ subscription_async_webhooks = """+ fragment OrderFragment on Order {+ shippingPrice {+ gross {+ amount+ }+ }+ total {+ gross {+ amount+ }+ }+ }++ subscription {+ event {+ ... on OrderCreated {+ order {+ ...OrderFragment+ }+ }+ ... on OrderUpdated {+ order {+ ...OrderFragment+ }+ }+ ... on OrderPaid {+ order {+ ...OrderFragment+ }+ }+ ... on OrderExpired {+ order {+ ...OrderFragment+ }+ }+ ... on OrderRefunded {+ order {+ ...OrderFragment+ }+ }+ ... on OrderConfirmed {+ order {+ ...OrderFragment+ }+ }+ ... on OrderFullyPaid {+ order {+ ...OrderFragment+ }+ }+ ... on OrderFulfilled {+ order {+ ...OrderFragment+ }+ }+ ... on OrderCancelled {+ order {+ ...OrderFragment+ }+ }+ ... on OrderBulkCreated {+ orders {+ ...OrderFragment+ }+ }+ ... on OrderFullyRefunded {+ order {+ ...OrderFragment+ }+ }+ ... on OrderMetadataUpdated {+ order {+ ...OrderFragment+ }+ }+ ... on DraftOrderCreated {+ order {+ ...OrderFragment+ }+ }+ ... on DraftOrderUpdated {+ order {+ ...OrderFragment+ }+ }+ ... on DraftOrderDeleted {+ order {+ ...OrderFragment+ }+ }+ }+ }+ """++ def _setup(additional_order_event: Union[str, list[str]]):+ tax_app, shipping_app, additional_app = App.objects.bulk_create(+ [+ App(+ name="Sample tax app",+ is_active=True,+ identifier="saleor.app.tax",+ ),+ App(+ name="Sample shipping app",+ is_active=True,+ identifier="saleor.app.shipping",+ ),+ App(+ name="Sample async webhook app",+ is_active=True,+ identifier="saleor.app.additional",+ ),+ ]+ )+ tax_app.permissions.add(permission_handle_taxes)+ shipping_app.permissions.set(+ [permission_manage_shipping, permission_manage_orders]+ )+ additional_app.permissions.add(permission_manage_orders)+ (+ tax_webhook,+ shipping_filter_webhook,+ additional_webhook,+ ) = Webhook.objects.bulk_create(+ [+ Webhook(+ name="Tax webhook",+ app=tax_app,+ target_url="http://127.0.0.1/test",+ subscription_query="subscription{ event{ ...on CalculateTaxes{ __typename } } }",+ ),+ Webhook(+ name="Shipping webhook",+ app=shipping_app,+ target_url="http://127.0.0.1/test",+ subscription_query="subscription { event { ... on OrderFilterShippingMethods { __typename } } }",+ ),+ Webhook(+ name="Checkout additional webhook",+ app=additional_app,+ target_url="http://127.0.0.1/test",+ subscription_query=subscription_async_webhooks,+ ),+ ]+ )+ if isinstance(additional_order_event, str):+ additional_order_event = [+ additional_order_event,+ ]+ additional_events = [+ WebhookEvent(+ event_type=event,+ webhook_id=additional_webhook.id,+ )+ for event in additional_order_event+ ]+ WebhookEvent.objects.bulk_create(+ [+ WebhookEvent(+ event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,+ webhook_id=tax_webhook.id,+ ),+ WebhookEvent(+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ webhook_id=shipping_filter_webhook.id,+ ),+ ]+ + additional_events+ )+ return (+ tax_webhook,+ shipping_filter_webhook,+ additional_webhook,+ )++ return _setupdiff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex c3a4f177b1..6622679c25 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -936,6 +936,7 @@ class WebhookEventSyncType:CHECKOUT_FILTER_SHIPPING_METHODS,CHECKOUT_CALCULATE_TAXES,]+ ORDER_EVENTS = [ORDER_CALCULATE_TAXES, ORDER_FILTER_SHIPPING_METHODS]# Events that are used only in the mutation logic can be excluded from the# circular query check.diff --git a/saleor/webhook/tests/test_utils.py b/saleor/webhook/tests/test_utils.pyindex c6ed395843..9dc0fbe9e7 100644--- a/saleor/webhook/tests/test_utils.py+++ b/saleor/webhook/tests/test_utils.py@@ -197,7 +197,9 @@ def test_get_webhooks_for_multiple_events()# then- assert webhook_map == {+ assert dict(webhook_map) == {+ WebhookEventAsyncType.ANY: set(),+ WebhookEventAsyncType.ORDER_CREATED: set(),WebhookEventAsyncType.CHECKOUT_CREATED: {checkout_created_webhook},WebhookEventAsyncType.ATTRIBUTE_CREATED: {attribute_created_webhook,diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.pyindex 02e80cc4fd..45d09cad2a 100644--- a/saleor/webhook/transport/shipping.py+++ b/saleor/webhook/transport/shipping.py@@ -18,9 +18,7 @@ from ...settings import WEBHOOK_SYNC_TIMEOUTfrom ...shipping.interface import ShippingMethodDatafrom ...webhook.utils import get_webhooks_for_eventfrom ..const import APP_ID_PREFIX, CACHE_EXCLUDED_SHIPPING_TIME-from .synchronous.transport import (- trigger_webhook_sync_if_not_cached,-)+from .synchronous.transport import trigger_webhook_sync_if_not_cachedlogger = logging.getLogger(__name__)@@ -110,6 +108,7 @@ def get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:# drop fields that change between requests but are not relevant for cache keysource_object.pop("last_change", None)source_object.pop("meta", None)+ source_object.pop("shipping_method", None)return payload_dictdiff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.pyindex bb78610f63..247bd04aaa 100644--- a/saleor/webhook/utils.py+++ b/saleor/webhook/utils.py@@ -1,4 +1,5 @@from collections import defaultdict+from collections.abc import Iterablefrom typing import TYPE_CHECKING, Optionalfrom django.conf import settings@@ -81,58 +82,63 @@ def get_webhooks_for_event(def get_webhooks_for_multiple_events(- event_types: list[str],- webhooks: Optional["QuerySet[Webhook]"] = None,- apps_ids: Optional["list[int]"] = None,- apps_identifier: Optional[list[str]] = None,+ event_types: Iterable[str],) -> dict[str, set[Webhook]]:- if webhooks is None:- # For this QS replica usage is applied later, as this QS could be also passed- # as parameter.- webhooks = Webhook.objects.all()+ set_event_types = set(event_types)+ if set_event_types.intersection(WebhookEventAsyncType.ALL):+ set_event_types.add(WebhookEventAsyncType.ANY)++ webhook_id_to_event_type = (+ WebhookEvent.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(event_type__in=set_event_types)+ .values_list("webhook_id", "event_type")+ )+ webhook_id_to_event_types_map = defaultdict(set)+ for webhook_id, event_type in webhook_id_to_event_type:+ webhook_id_to_event_types_map[webhook_id].add(event_type)- filter_expresion = Q()- for event_type in set(event_types):- filter_expresion |= Q(- get_filter_for_single_webhook_event(- event_type=event_type,- apps_ids=apps_ids,- apps_identifier=apps_identifier,- )- )- webhooks = list(- webhooks.using(settings.DATABASE_CONNECTION_REPLICA_NAME)- .filter(filter_expresion)- .select_related("app")- .prefetch_related("app__permissions__content_type")+ webhooks = Webhook.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(+ id__in={webhook_id for webhook_id, _ in webhook_id_to_event_type},+ is_active=True,)- webhook_events = WebhookEvent.objects.filter(- webhook_id__in={webhook.id for webhook in webhooks}- ).values_list("webhook_id", "event_type")- webhook_events_map = defaultdict(set)- for webhook_id, event_type in webhook_events:- webhook_events_map[webhook_id].add(event_type)- webhook_app = {webhook.app_id: webhook.app for webhook in webhooks}+ app_ids = {webhook.app_id for webhook in webhooks}++ apps = (+ App.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(id__in=app_ids, is_active=True, removed_at__isnull=True)+ .prefetch_related("permissions__content_type")+ .in_bulk()+ )+app_perm_map = {}- for app in webhook_app.values():- app_permissions = app.permissions.all()+ for app in apps.values():+ app_perms = app.permissions.all()app_permission_codenames = [- permission.codename for permission in app_permissions+ (permission.content_type.app_label, permission.codename)+ for permission in app_perms]app_perm_map[app.id] = app_permission_codenames-- event_map = defaultdict(set)+ active_event_map = defaultdict(set)for webhook in webhooks:- app_permission_codenames = app_perm_map.get(webhook.app_id, [])- events: set[str] = webhook_events_map.get(webhook.id, set())- for event_type in events:+ if webhook.app_id not in apps:+ continue+ app = apps[webhook.app_id]+ webhook.app = app+ app_permissions = app_perm_map.get(webhook.app_id, [])+ events = webhook_id_to_event_types_map.get(webhook.id, set())+ for event in events:required_permission = WebhookEventAsyncType.PERMISSIONS.get(- event_type, WebhookEventSyncType.PERMISSIONS.get(event_type)+ event, WebhookEventSyncType.PERMISSIONS.get(event))if not required_permission:- event_map[event_type].add(webhook)- continue- _, codename = required_permission.value.split(".")- if codename in app_permission_codenames:- event_map[event_type].add(webhook)- return event_map+ active_event_map[event].add(webhook)+ else:+ app_label, codename = required_permission.value.split(".")+ if (app_label, codename) in app_permissions:+ active_event_map[event].add(webhook)+ # always add events that don't have any active webhooks. This is needed for+ # future validation when calling events.+ for event in set_event_types:+ if event not in active_event_map:+ active_event_map[event] = set()+ return active_event_map