Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix empty sync webhooks for checkout type (#16393)

Maciej Korycinskidbc210162a62
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 5c39045c89..1f1924cef2 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -1,15 +1,129 @@
+from collections.abc import Iterable
+from datetime import timedelta
from decimal import Decimal
-from typing import cast
+from typing import TYPE_CHECKING, Callable, Optional, cast
-from ..core.utils.events import call_event
+from django.utils import timezone
+
+from ..core.utils.events import call_event_including_protected_events
from ..payment.models import TransactionItem
-from ..plugins.manager import PluginsManager
+from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ..webhook.utils import get_webhooks_for_multiple_events
from . import CheckoutChargeStatus
from .calculations import fetch_checkout_data
-from .fetch import fetch_checkout_info, fetch_checkout_lines
+from .fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
from .models import Checkout
from .payment_utils import update_refundable_for_checkout
+if TYPE_CHECKING:
+ from ..account.models import Address
+ from ..plugins.manager import PluginsManager
+ 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,
+ event_name: str,
+ checkout: "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
+ ):
+ call_event_including_protected_events(event_func, checkout)
+ return
+
+ lines_info, _ = fetch_checkout_lines(
+ checkout,
+ )
+ checkout_info = fetch_checkout_info(
+ checkout,
+ lines_info,
+ manager,
+ )
+ call_checkout_event_for_checkout_info(
+ manager=manager,
+ event_func=event_func,
+ event_name=event_name,
+ checkout_info=checkout_info,
+ lines=lines_info,
+ webhook_event_map=webhook_event_map,
+ )
+ return
+
+
+def call_checkout_event_for_checkout_info(
+ manager: "PluginsManager",
+ event_func: Callable,
+ event_name: str,
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"] = None,
+ webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,
+):
+ checkout = checkout_info.checkout
+ if webhook_event_map is None:
+ webhook_event_map = get_webhooks_for_multiple_events(
+ [event_name, *WebhookEventSyncType.CHECKOUT_EVENTS]
+ )
+
+ # 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
+ ):
+ call_event_including_protected_events(event_func, checkout)
+ return None
+
+ _ = checkout_info.all_shipping_methods
+
+ # + timedelta(seconds=10) to confirm that triggered webhooks will still have a
+ # valid prices. Triggered only when we have active sync tax webhook
+ if (
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in webhook_event_map
+ and checkout.price_expiration < timezone.now() + timedelta(seconds=10)
+ ):
+ fetch_checkout_data(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address
+ or checkout_info.shipping_address
+ or checkout_info.billing_address,
+ force_update=True,
+ )
+
+ call_event_including_protected_events(event_func, checkout)
+ return None
+
def update_last_transaction_modified_at_for_checkout(
checkout: Checkout, transaction: TransactionItem
@@ -55,4 +169,10 @@ def transaction_amounts_for_checkout_updated(
update_refundable_for_checkout(checkout.pk)
if not previous_charge_status_is_fully_paid and current_status_is_fully_paid:
- call_event(manager.checkout_fully_paid, checkout_info.checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_fully_paid,
+ event_name=WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
index 7d77ffe36f..d6129b4ad4 100644
--- a/saleor/checkout/tests/test_actions.py
+++ b/saleor/checkout/tests/test_actions.py
@@ -1,14 +1,23 @@
import datetime
from decimal import Decimal
-from unittest.mock import patch
+from unittest.mock import call, patch
import pytest
import pytz
+from django.test import override_settings
+from django.utils import timezone
from freezegun import freeze_time
+from ...core.models import EventDelivery
+from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
+from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from .. import CheckoutAuthorizeStatus, CheckoutChargeStatus
-from ..actions import transaction_amounts_for_checkout_updated
+from ..actions import (
+ call_checkout_event_for_checkout,
+ call_checkout_event_for_checkout_info,
+ transaction_amounts_for_checkout_updated,
+)
from ..calculations import fetch_checkout_data
from ..fetch import fetch_checkout_info, fetch_checkout_lines
@@ -287,3 +296,561 @@ def test_get_checkout_refundable_with_multiple_active_transactions(
# then
checkout.refresh_from_db()
assert checkout.automatically_refundable is True
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_triggers_sync_webhook_when_needed(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_created_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ # when
+ with freeze_time("2023-06-01 12:00:01"):
+ call_checkout_event_for_checkout(
+ plugins_manager,
+ plugins_manager.checkout_created,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout_with_items,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_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.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_skips_tax_webhook_when_not_expired(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now() + datetime.timedelta(hours=1)
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_created_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ # when
+ call_checkout_event_for_checkout(
+ plugins_manager,
+ plugins_manager.checkout_created,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout_with_items,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_created_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.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ assert not tax_delivery
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ ]
+ )
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_skip_sync_webhooks_when_async_missing(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+
+ # setup sync webhooks with async that is not going to be called
+ setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ # when
+ with freeze_time("2023-06-01 12:00:01"):
+ call_checkout_event_for_checkout(
+ plugins_manager,
+ plugins_manager.checkout_updated,
+ WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_with_items,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_only_async_when_sync_missing(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ permission_manage_checkouts,
+ settings,
+ webhook,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ webhook.events.create(event_type=WebhookEventAsyncType.CHECKOUT_CREATED)
+ webhook.app.permissions.add(permission_manage_checkouts)
+
+ # when
+ with freeze_time("2023-06-01 12:00:01"):
+ call_checkout_event_for_checkout(
+ plugins_manager,
+ plugins_manager.checkout_created,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout_with_items,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(webhook_id=webhook.id)
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ assert not mocked_send_webhook_request_sync.called
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_info_triggers_sync_webhook_when_needed(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_created_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ lines_info, _ = fetch_checkout_lines(
+ checkout_with_items,
+ )
+ checkout_info = fetch_checkout_info(
+ checkout_with_items,
+ lines_info,
+ plugins_manager,
+ )
+
+ # when
+ with freeze_time("2023-06-01 12:00:01"):
+ call_checkout_event_for_checkout_info(
+ plugins_manager,
+ plugins_manager.checkout_created,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout_info,
+ lines_info,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_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.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_info_skips_tax_webhook_when_not_expired(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now() + datetime.timedelta(hours=1)
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_created_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ lines_info, _ = fetch_checkout_lines(
+ checkout_with_items,
+ )
+ checkout_info = fetch_checkout_info(
+ checkout_with_items,
+ lines_info,
+ plugins_manager,
+ )
+
+ # when
+ call_checkout_event_for_checkout_info(
+ plugins_manager,
+ plugins_manager.checkout_created,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout_info,
+ lines_info,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_created_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.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ assert not tax_delivery
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ ]
+ )
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_info_only_async_when_sync_missing(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ permission_manage_checkouts,
+ settings,
+ webhook,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ webhook.events.create(event_type=WebhookEventAsyncType.CHECKOUT_CREATED)
+ webhook.app.permissions.add(permission_manage_checkouts)
+
+ lines_info, _ = fetch_checkout_lines(
+ checkout_with_items,
+ )
+ checkout_info = fetch_checkout_info(
+ checkout_with_items,
+ lines_info,
+ plugins_manager,
+ )
+
+ # when
+ with freeze_time("2023-06-01 12:00:01"):
+ call_checkout_event_for_checkout_info(
+ plugins_manager,
+ plugins_manager.checkout_created,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout_info,
+ lines_info,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(webhook_id=webhook.id)
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ assert not mocked_send_webhook_request_sync.called
+
+
+@freeze_time("2023-05-31 12:00:01")
+@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_checkout_event_for_checkout_info_skip_sync_webhooks_when_async_missing(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ checkout_with_items,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+
+ # setup sync webhooks with async that is not going to be called
+ setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ lines_info, _ = fetch_checkout_lines(
+ checkout_with_items,
+ )
+ checkout_info = fetch_checkout_info(
+ checkout_with_items,
+ lines_info,
+ plugins_manager,
+ )
+
+ # when
+ with freeze_time("2023-06-01 12:00:01"):
+ call_checkout_event_for_checkout_info(
+ plugins_manager,
+ plugins_manager.checkout_updated,
+ WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info,
+ lines_info,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
+
+
+@freeze_time("2023-05-31 12:00:01")
+@patch(
+ "saleor.checkout.actions.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ checkout_with_items,
+ transaction_item_generator,
+):
+ # given
+ plugins_manager = get_plugins_manager(allow_replica=False)
+ checkout_with_items.price_expiration = timezone.now() - datetime.timedelta(hours=10)
+ checkout_with_items.save(update_fields=["price_expiration"])
+
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_fully_paid_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+
+ # then
+ flush_post_commit_hooks()
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_fully_paid_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_fully_paid_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_fully_paid_delivery.id},
+ queue=settings.CHECKOUT_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(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/core/utils/events.py b/saleor/core/utils/events.py
index c992a4548f..b9e82d8ad5 100644
--- a/saleor/core/utils/events.py
+++ b/saleor/core/utils/events.py
@@ -1,13 +1,32 @@
from django.db import transaction
+from ...checkout.fetch import CheckoutInfo
+from ...checkout.models import Checkout
-def call_event(func_obj, *func_args, **func_kwargs):
- """Call webhook event with given args.
- Ensures that in atomic transaction event is called on_commit.
+def call_event_including_protected_events(func_obj, *func_args, **func_kwargs):
+ """Call event without additional validation.
+
+ This function triggers the event without any additional validation. It should be
+ used when all additional actions are already handled. Additional actions like
+ triggering all existing sync webhooks before calling async webhooks.
"""
connection = transaction.get_connection()
if connection.in_atomic_block:
transaction.on_commit(lambda: func_obj(*func_args, **func_kwargs))
else:
func_obj(*func_args, **func_kwargs)
+
+
+def call_event(func_obj, *func_args, **func_kwargs):
+ """Call webhook event with given args.
+
+ Ensures that in atomic transaction event is called on_commit.
+ """
+ is_checkout_instance = any(
+ [isinstance(arg, (Checkout, CheckoutInfo)) for arg in func_args]
+ )
+
+ if is_checkout_instance:
+ 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.py
new file mode 100644
index 0000000000..580dec8487
--- /dev/null
+++ b/saleor/core/utils/tests/test_events.py
@@ -0,0 +1,15 @@
+import pytest
+
+from ..events import call_event
+
+
+def test_call_event_cannot_be_used_with_checkout_info_object(
+ checkout_info, plugins_manager
+):
+ with pytest.raises(NotImplementedError):
+ call_event(plugins_manager.checkout_updated, checkout_info)
+
+
+def test_call_event_cannot_be_used_with_checkout_object(checkout, plugins_manager):
+ with pytest.raises(NotImplementedError):
+ call_event(plugins_manager.checkout_updated, checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
index 2300db2835..7621c418d9 100644
--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
fetch_checkout_info,
@@ -120,6 +121,12 @@ class CheckoutAddPromoCode(BaseMutation):
recalculate_discount=False,
save=True,
)
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager=manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutAddPromoCode(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
index 032e1bc783..d9cdefa678 100644
--- a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
@@ -1,11 +1,9 @@
import graphene
from ....checkout import AddressType
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ....checkout.utils import (
- change_billing_address_in_checkout,
- invalidate_checkout,
-)
+from ....checkout.utils import change_billing_address_in_checkout, invalidate_checkout
from ....core.tracing import traced_atomic_transaction
from ....webhook.event_types import WebhookEventAsyncType
from ...account.types import AddressInput
@@ -110,6 +108,11 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
+ invalidate_prices_updated_fields
)
- cls.call_event(manager.checkout_updated, checkout)
-
+ call_checkout_event_for_checkout_info(
+ manager=manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutBillingAddressUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index fc3026d7f3..59644474b9 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -4,6 +4,7 @@ import graphene
from django.conf import settings
from ....checkout import AddressType, models
+from ....checkout.actions import call_checkout_event_for_checkout
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.utils import add_variants_to_checkout
from ....core.tracing import traced_atomic_transaction
@@ -404,8 +405,14 @@ class CheckoutCreate(ModelMutation, I18nMixin):
if channel:
input["channel"] = channel
response = super().perform_mutation(_root, info, input=input)
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.checkout_created, response.checkout)
+ checkout = response.checkout
apply_gift_reward_if_applicable_on_checkout_creation(response.checkout)
+ manager = get_plugin_manager_promise(info.context).get()
+ call_checkout_event_for_checkout(
+ manager,
+ event_func=manager.checkout_created,
+ event_name=WebhookEventAsyncType.CHECKOUT_CREATED,
+ checkout=checkout,
+ )
response.created = True
return response
diff --git a/saleor/graphql/checkout/mutations/checkout_customer_attach.py b/saleor/graphql/checkout/mutations/checkout_customer_attach.py
index e2d8a7e84d..843d9b5e6f 100644
--- a/saleor/graphql/checkout/mutations/checkout_customer_attach.py
+++ b/saleor/graphql/checkout/mutations/checkout_customer_attach.py
@@ -1,6 +1,7 @@
import graphene
from django.forms import ValidationError
+from ....checkout.actions import call_checkout_event_for_checkout
from ....checkout.error_codes import CheckoutErrorCode
from ....core.exceptions import PermissionDenied
from ....permission.auth_filters import AuthorizationFilters
@@ -116,5 +117,12 @@ class CheckoutCustomerAttach(BaseMutation):
checkout.email = customer.email
checkout.save(update_fields=["email", "user", "last_change"])
manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.checkout_updated, checkout)
+
+ call_checkout_event_for_checkout(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout=checkout,
+ )
+
return CheckoutCustomerAttach(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_customer_detach.py b/saleor/graphql/checkout/mutations/checkout_customer_detach.py
index 445ca02155..4c1b58b8a7 100644
--- a/saleor/graphql/checkout/mutations/checkout_customer_detach.py
+++ b/saleor/graphql/checkout/mutations/checkout_customer_detach.py
@@ -1,5 +1,8 @@
import graphene
+from ....checkout.actions import (
+ call_checkout_event_for_checkout,
+)
from ....core.exceptions import PermissionDenied
from ....permission.auth_filters import AuthorizationFilters
from ....permission.enums import AccountPermissions
@@ -68,5 +71,11 @@ class CheckoutCustomerDetach(BaseMutation):
checkout.user = None
checkout.save(update_fields=["user", "last_change"])
manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.checkout_updated, checkout)
+
+ call_checkout_event_for_checkout(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout=checkout,
+ )
return CheckoutCustomerDetach(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_customer_note_update.py b/saleor/graphql/checkout/mutations/checkout_customer_note_update.py
index b41da463a5..4035064719 100644
--- a/saleor/graphql/checkout/mutations/checkout_customer_note_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_customer_note_update.py
@@ -1,5 +1,6 @@
import graphene
+from ....checkout.actions import call_checkout_event_for_checkout
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_321
@@ -53,5 +54,10 @@ class CheckoutCustomerNoteUpdate(BaseMutation):
cls.clean_instance(info, checkout)
checkout.save(update_fields=["note", "last_change"])
manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout=checkout,
+ )
return CheckoutCustomerNoteUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index 42a207487c..02ff68a544 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -4,6 +4,7 @@ from typing import Optional
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
CheckoutInfo,
@@ -269,7 +270,13 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
update_fields=checkout_fields_to_update + invalidate_prices_updated_fields
)
get_or_create_checkout_metadata(checkout).save()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
@staticmethod
def _resolve_delivery_method_type(id_) -> Optional[str]:
diff --git a/saleor/graphql/checkout/mutations/checkout_email_update.py b/saleor/graphql/checkout/mutations/checkout_email_update.py
index 778d0887fc..49d222336a 100644
--- a/saleor/graphql/checkout/mutations/checkout_email_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_email_update.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.actions import call_checkout_event_for_checkout
from ....checkout.error_codes import CheckoutErrorCode
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
@@ -79,5 +80,10 @@ class CheckoutEmailUpdate(BaseMutation):
cls.clean_instance(info, checkout)
checkout.save(update_fields=["email", "last_change"])
manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout=checkout,
+ )
return CheckoutEmailUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_language_code_update.py b/saleor/graphql/checkout/mutations/checkout_language_code_update.py
index 44ebd9e264..07614b8167 100644
--- a/saleor/graphql/checkout/mutations/checkout_language_code_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_language_code_update.py
@@ -1,5 +1,6 @@
import graphene
+from saleor.checkout.actions import call_checkout_event_for_checkout
from saleor.webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
@@ -66,5 +67,10 @@ class CheckoutLanguageCodeUpdate(BaseMutation):
checkout.language_code = language_code
checkout.save(update_fields=["language_code", "last_change"])
manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout=checkout,
+ )
return CheckoutLanguageCodeUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_line_delete.py b/saleor/graphql/checkout/mutations/checkout_line_delete.py
index a832757a86..40fc469afa 100644
--- a/saleor/graphql/checkout/mutations/checkout_line_delete.py
+++ b/saleor/graphql/checkout/mutations/checkout_line_delete.py
@@ -1,5 +1,6 @@
import graphene
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import invalidate_checkout
@@ -81,6 +82,12 @@ class CheckoutLineDelete(BaseMutation):
checkout_info = fetch_checkout_info(checkout, lines, manager)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
invalidate_checkout(checkout_info, lines, manager, save=True)
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutLineDelete(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index 9baadc1404..26883b84ce 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -1,5 +1,6 @@
import graphene
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
fetch_checkout_info,
@@ -215,7 +216,13 @@ class CheckoutLinesAdd(BaseMutation):
update_checkout_external_shipping_method_if_invalid(checkout_info, lines)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
invalidate_checkout(checkout_info, lines, manager, save=True)
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutLinesAdd(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_delete.py b/saleor/graphql/checkout/mutations/checkout_lines_delete.py
index db1eebcb9b..d93fab0394 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_delete.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_delete.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import invalidate_checkout
@@ -100,6 +101,12 @@ class CheckoutLinesDelete(BaseMutation):
checkout_info = fetch_checkout_info(checkout, lines, manager)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
invalidate_checkout(checkout_info, lines, manager, save=True)
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutLinesDelete(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
index c3c6bf595f..f90202865d 100644
--- a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError
from graphql.error import GraphQLError
from ....checkout import models
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import (
@@ -108,7 +109,13 @@ class CheckoutRemovePromoCode(BaseMutation):
recalculate_discount=True,
save=True,
)
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutRemovePromoCode(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
index 028035eb84..7a140b9448 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
@@ -5,6 +5,7 @@ import graphene
from django.core.exceptions import ValidationError
from ....checkout import AddressType, models
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
CheckoutLineInfo,
@@ -215,6 +216,12 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixi
+ invalidate_prices_updated_fields
)
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutShippingAddressUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index 965145855c..6a04f4db7c 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -3,6 +3,7 @@ from typing import Optional
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.actions import call_checkout_event_for_checkout_info
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import (
@@ -223,7 +224,13 @@ class CheckoutShippingMethodUpdate(BaseMutation):
)
get_checkout_metadata(checkout).save()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutShippingMethodUpdate(checkout=checkout)
@classmethod
@@ -258,7 +265,13 @@ class CheckoutShippingMethodUpdate(BaseMutation):
+ invalidate_prices_updated_fields
)
get_checkout_metadata(checkout).save()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutShippingMethodUpdate(checkout=checkout)
@@ -277,5 +290,11 @@ class CheckoutShippingMethodUpdate(BaseMutation):
)
get_checkout_metadata(checkout).save()
- cls.call_event(manager.checkout_updated, checkout)
+ call_checkout_event_for_checkout_info(
+ manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines,
+ )
return CheckoutShippingMethodUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 30dbfeb613..37db790a68 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -417,7 +417,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(71):
+ with django_assert_num_queries(72):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -435,7 +435,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(71):
+ with django_assert_num_queries(72):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -566,7 +566,7 @@ def test_create_checkout_with_order_promotion(
}
# when
- with django_assert_num_queries(76):
+ with django_assert_num_queries(77):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -821,7 +821,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(92):
+ with django_assert_num_queries(93):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -835,7 +835,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(92):
+ with django_assert_num_queries(93):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -1080,7 +1080,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(91):
+ with django_assert_num_queries(92):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1093,7 +1093,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(91):
+ with django_assert_num_queries(92):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1143,7 +1143,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
}
# when
- with django_assert_num_queries(83):
+ with django_assert_num_queries(84):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1228,7 +1228,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
}
# when
- with django_assert_num_queries(83):
+ with django_assert_num_queries(84):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1263,7 +1263,7 @@ def test_add_checkout_lines_order_discount_applies(
}
# when
- with django_assert_num_queries(86):
+ with django_assert_num_queries(87):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1297,7 +1297,7 @@ def test_add_checkout_lines_gift_discount_applies(
}
# when
- with django_assert_num_queries(112):
+ with django_assert_num_queries(113):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
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.py
index 5499c84f36..497ea79b48 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
@@ -1,20 +1,25 @@
from datetime import date, timedelta
from decimal import Decimal
from unittest import mock
+from unittest.mock import call, patch
import graphene
import pytest
+from django.test import override_settings
from django.utils import timezone
from prices import Money
from .....checkout import base_calculations, calculations
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import add_variant_to_checkout, set_external_shipping_id
+from .....core.models import EventDelivery
from .....discount import VoucherType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductVariantChannelListing
from .....warehouse.models import Stock
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -1498,3 +1503,74 @@ def test_with_active_problems_flow(
# then
assert not content["data"]["checkoutAddPromoCode"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_add_promo_code.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_add_voucher_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_item,
+ voucher,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "promoCode": voucher.code,
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_ADD_PROMO_CODE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutAddPromoCode"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index ec8f9bea45..09a971a131 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
@@ -1,8 +1,13 @@
from unittest import mock
+from unittest.mock import call, patch
import pytest
+from django.test import override_settings
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.utils import invalidate_checkout
+from .....core.models import EventDelivery
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -638,3 +643,79 @@ def test_checkout_billing_address_skip_validation_by_app(
checkout.refresh_from_db()
assert checkout.billing_address.postal_code == invalid_postal_code
assert checkout.billing_address.validation_skipped is True
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_billing_address_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_billing_address_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+ graphql_address_data,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item
+
+ query = MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE
+ billing_address = graphql_address_data
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "billingAddress": billing_address,
+ }
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutBillingAddressUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index bd69403210..82f67cb2d1 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -1,6 +1,7 @@
import datetime
import warnings
from unittest import mock
+from unittest.mock import call, patch
import graphene
import pytest
@@ -10,12 +11,15 @@ from django.utils import timezone
from .....channel.utils import DEPRECATION_WARNING_MESSAGE
from .....checkout import AddressType
+from .....checkout.actions import call_checkout_event_for_checkout
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_lines
from .....checkout.models import Checkout
from .....checkout.utils import calculate_checkout_quantity
+from .....core.models import EventDelivery
from .....product.models import ProductChannelListing
from .....warehouse.models import Reservation, Stock
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....tests.utils import assert_no_permission, get_graphql_content
MUTATION_CHECKOUT_CREATE = """
@@ -2641,3 +2645,90 @@ def test_checkout_create_skip_validation_billing_address_by_app(
new_checkout = Checkout.objects.first()
assert new_checkout.billing_address.postal_code == invalid_postal_code
assert new_checkout.billing_address.validation_skipped is True
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_create.call_checkout_event_for_checkout",
+ wraps=call_checkout_event_for_checkout,
+)
+@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_checkout_create_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ api_client,
+ stock,
+ graphql_address_data,
+ channel_USD,
+ setup_checkout_webhooks,
+ settings,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = None
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_created_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ billing_metadata = [{"key": "billing", "value": "billing_value"}]
+ shipping_metadata = [{"key": "shipping", "value": "shipping_value"}]
+ shipping_address_data = graphql_address_data.copy()
+ billing_address_data = graphql_address_data.copy()
+ shipping_address_data["metadata"] = shipping_metadata
+ billing_address_data["metadata"] = billing_metadata
+
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address_data,
+ "billingAddress": billing_address_data,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutCreate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_create_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_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.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_create_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
index 7311fa04d2..db8946de81 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
@@ -1,7 +1,13 @@
+from unittest.mock import call, patch
+
import graphene
+from django.test import override_settings
from .....account.models import User
+from .....checkout.actions import call_checkout_event_for_checkout
from .....checkout.error_codes import CheckoutErrorCode
+from .....core.models import EventDelivery
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -227,3 +233,80 @@ def test_with_active_problems_flow(user_api_client, checkout_with_problems):
# then
assert not content["data"]["checkoutCustomerAttach"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_customer_attach.call_checkout_event_for_checkout",
+ wraps=call_checkout_event_for_checkout,
+)
+@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_checkout_customer_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+ customer_user2,
+ permission_impersonate_user,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item
+ checkout.email = "[email protected]"
+ checkout.save()
+
+ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH
+ customer_id = graphene.Node.to_global_id("User", customer_user2.pk)
+ variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}
+
+ # when
+ response = user_api_client.post_graphql(
+ query, variables, permissions=[permission_impersonate_user]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutCustomerAttach"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
index 54747e7bfc..5635ed3e06 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
@@ -1,4 +1,11 @@
+from unittest.mock import call, patch
+
+from django.test import override_settings
+
from .....account.models import User
+from .....checkout.actions import call_checkout_event_for_checkout
+from .....core.models import EventDelivery
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -105,3 +112,77 @@ def test_with_active_problems_flow(user_api_client, checkout_with_problems):
# then
assert not content["data"]["checkoutCustomerDetach"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_customer_detach.call_checkout_event_for_checkout",
+ wraps=call_checkout_event_for_checkout,
+)
+@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_checkout_customer_detach_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+ customer_user,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item
+ checkout.user = customer_user
+ checkout.save(update_fields=["user"])
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutCustomerDetach"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index 5edb04a9b2..d351a0dc15 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
@@ -1,3 +1,11 @@
+from unittest.mock import call, patch
+
+from django.test import override_settings
+
+from saleor.checkout.actions import call_checkout_event_for_checkout
+from saleor.core.models import EventDelivery
+from saleor.webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -66,3 +74,77 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):
# then
content = get_graphql_content(response)
assert not content["data"]["checkoutCustomerNoteUpdate"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_customer_note_update.call_checkout_event_for_checkout",
+ wraps=call_checkout_event_for_checkout,
+)
+@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_checkout_customer_note_update_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ customer_note = "New customer note value"
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "customerNote": customer_note,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ CHECKOUT_CUSTOMER_NOTE_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCustomerNoteUpdate"]
+ assert not data["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index 26573695f4..6fe2fb2ff5 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
@@ -1,18 +1,22 @@
from unittest import mock
-from unittest.mock import patch
+from unittest.mock import call, patch
import graphene
import pytest
+from django.test import override_settings
from .....account.models import Address
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout
+from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....shipping import models as shipping_models
from .....shipping.utils import convert_to_shipping_method_data
from .....warehouse import WarehouseClickAndCollectOption
from .....warehouse.models import Stock
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -1002,3 +1006,257 @@ def test_checkout_delivery_method_update_from_cc_to_all_warehouses_disabled_cc(
assert len(errors) == 1
assert errors[0]["field"] == "deliveryMethodId"
assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_delivery_method_update_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ shipping_method,
+ checkout_with_item,
+ address,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ # when
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutDeliveryMethodUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_delivery_method_update_cc_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_item_for_cc,
+ warehouses_for_cc,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ warehouse_cc_all = warehouses_for_cc[1]
+ test_address_name = "Jimmy"
+ warehouse_cc_all_address = warehouse_cc_all.address
+ warehouse_cc_all_address.first_name = test_address_name
+ warehouse_cc_all_address.save(update_fields=["first_name"])
+ checkout = checkout_with_item_for_cc
+
+ Stock.objects.create(
+ warehouse=warehouse_cc_all,
+ product_variant=checkout.lines.first().variant,
+ quantity=1,
+ )
+
+ # when
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+ method_id = graphene.Node.to_global_id("Warehouse", warehouse_cc_all.id)
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutDeliveryMethodUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method"
+)
+def test_checkout_delivery_method_update_external_shipping_triggers_sync_webhooks(
+ mock_clean_delivery,
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_item_for_cc,
+):
+ # given
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item_for_cc
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+ mock_clean_delivery.return_value = True
+
+ response_method_id = "abcd"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": "Provider - Economy",
+ "amount": "10",
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_send_webhook_request_sync.side_effect = [
+ mock_json_response,
+ [],
+ [],
+ ]
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_webhook.app.identifier}:{response_method_id}"
+ )
+
+ # when
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutDeliveryMethodUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
index 58f1dad8ec..b8fdb9a8d6 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
@@ -1,4 +1,11 @@
+from unittest.mock import call, patch
+
+from django.test import override_settings
+
+from .....checkout.actions import call_checkout_event_for_checkout
from .....checkout.error_codes import CheckoutErrorCode
+from .....core.models import EventDelivery
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -78,3 +85,75 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):
# then
assert not content["data"]["checkoutEmailUpdate"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_email_update.call_checkout_event_for_checkout",
+ wraps=call_checkout_event_for_checkout,
+)
+@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_checkout_email_update_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item
+ checkout.email = None
+ checkout.save(update_fields=["email"])
+
+ email = "[email protected]"
+ variables = {"id": to_global_id_or_none(checkout), "email": email}
+
+ # when
+ response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutEmailUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index c02660be27..03c1268fa4 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
@@ -1,3 +1,10 @@
+from unittest.mock import call, patch
+
+from django.test import override_settings
+
+from .....checkout.actions import call_checkout_event_for_checkout
+from .....core.models import EventDelivery
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -61,3 +68,74 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):
# then
assert not content["data"]["checkoutLanguageCodeUpdate"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_language_code_update.call_checkout_event_for_checkout",
+ wraps=call_checkout_event_for_checkout,
+)
+@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_checkout_update_language_code_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_gift_card,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ language_code = "PL"
+ checkout = checkout_with_gift_card
+ variables = {"id": to_global_id_or_none(checkout), "languageCode": language_code}
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutLanguageCodeUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
index 20d742edcd..cdc177e1bc 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
@@ -1,8 +1,11 @@
from unittest import mock
+from unittest.mock import call, patch
import graphene
+from django.test import override_settings
from .....checkout import base_calculations
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import (
@@ -11,8 +14,10 @@ from .....checkout.utils import (
calculate_checkout_quantity,
invalidate_checkout,
)
+from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....warehouse.models import Reservation
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
from ...mutations.utils import update_checkout_shipping_method_if_invalid
@@ -198,3 +203,86 @@ def test_checkout_line_delete_non_removable_gift(user_api_client, checkout_line)
assert len(errors) == 1
assert errors[0]["field"] == "lineId"
assert errors[0]["code"] == CheckoutErrorCode.NON_REMOVABLE_GIFT_LINE.name
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_line_delete.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_line_delete_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_items,
+ product_with_single_variant,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ variant = product_with_single_variant.variants.first()
+
+ checkout_info = fetch_checkout_info(
+ checkout_with_items, [], get_plugins_manager(allow_replica=False)
+ )
+ add_variant_to_checkout(checkout_info, variant, 1)
+
+ line = checkout_info.checkout.lines.last()
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "lineId": to_global_id_or_none(line),
+ }
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_LINE_DELETE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutLineDelete"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 9bce930875..9ebf8b44f5 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -1,13 +1,16 @@
import datetime
from decimal import Decimal
from unittest import mock
+from unittest.mock import call, patch
import graphene
import pytest
import pytz
+from django.test import override_settings
from django.utils import timezone
from prices import Money
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
@@ -17,6 +20,7 @@ from .....checkout.utils import (
invalidate_checkout,
recalculate_checkout_discount,
)
+from .....core.models import EventDelivery
from .....discount import RewardType, RewardValueType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
@@ -24,6 +28,7 @@ from .....shipping.interface import ShippingMethodData
from .....warehouse import WarehouseClickAndCollectOption
from .....warehouse.models import Reservation, Stock
from .....warehouse.tests.utils import get_available_quantity_for_stock
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ...mutations.utils import update_checkout_shipping_method_if_invalid
@@ -1748,3 +1753,87 @@ def test_with_active_problems_flow(
# then
assert not content["data"]["checkoutLinesAdd"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_lines_add_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+ stock,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ variant = stock.product_variant
+
+ checkout = checkout_with_item
+
+ lines, _ = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 3
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {
+ "variantId": variant_id,
+ "quantity": 1,
+ }
+ ],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutLinesAdd"]["errors"]
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
index 19d94f3097..d23fd4832f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
@@ -1,12 +1,17 @@
from unittest import mock
+from unittest.mock import call, patch
import graphene
+from django.test import override_settings
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import CheckoutLine
from .....checkout.utils import invalidate_checkout
+from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
from ...mutations.utils import update_checkout_shipping_method_if_invalid
@@ -195,3 +200,79 @@ def test_checkout_lines_delete_not_associated_with_checkout(
assert errors[0]["field"] == "lineId"
assert errors[0]["code"] == CheckoutErrorCode.INVALID.name
assert errors[0]["lines"] == [line_id]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_delete.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_lines_delete_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_items,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ line = checkout_with_items.lines.first()
+ first_line_id = to_global_id_or_none(line)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "linesIds": [first_line_id],
+ }
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_DELETE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutLinesDelete"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 5104aa1b28..50bde58189 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -1,11 +1,14 @@
import datetime
from decimal import Decimal
from unittest import mock
+from unittest.mock import call, patch
import graphene
import pytest
+from django.test import override_settings
from django.utils import timezone
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
@@ -14,10 +17,12 @@ from .....checkout.utils import (
calculate_checkout_quantity,
invalidate_checkout,
)
+from .....core.models import EventDelivery
from .....discount import RewardValueType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing
from .....warehouse.models import Reservation, Stock
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ...mutations.utils import update_checkout_shipping_method_if_invalid
@@ -1355,3 +1360,84 @@ def test_checkout_lines_update_quantity_gift(user_api_client, checkout_with_item
assert errors[0]["field"] == "lineId"
assert errors[0]["code"] == CheckoutErrorCode.NON_EDITABLE_GIFT_LINE.name
assert errors[0]["lines"] == [line_id]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_lines_update_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_items,
+ product_with_single_variant,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ variant = product_with_single_variant.variants.first()
+
+ checkout_info = fetch_checkout_info(
+ checkout_with_items, [], get_plugins_manager(allow_replica=False)
+ )
+ add_variant_to_checkout(checkout_info, variant, 1)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "lines": [{"variantId": to_global_id_or_none(variant), "quantity": 3}],
+ }
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutLinesUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index 595bec7495..6f471d45af 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
@@ -1,17 +1,21 @@
from datetime import timedelta
from decimal import Decimal
-from unittest.mock import patch
+from unittest.mock import call, patch
import graphene
+from django.test import override_settings
from django.utils import timezone
from prices import Money
from .....checkout import base_calculations
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....core.models import EventDelivery
from .....discount import RewardValueType
from .....discount.models import Voucher, VoucherChannelListing, VoucherCode
from .....plugins.manager import get_plugins_manager
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -701,3 +705,72 @@ def test_with_active_problems_flow(
# then
assert not content["data"]["checkoutRemovePromoCode"]["errors"]
checkout_updated_webhook_mock.assert_called_once_with(checkout_with_problems)
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_remove_promo_code.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_remove_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout_with_voucher,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_voucher),
+ "promoCode": checkout_with_voucher.voucher_code,
+ }
+
+ # when
+ content = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ # then
+ assert not content["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index 7b78c2a98d..8bbc22942f 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
@@ -1,10 +1,12 @@
import datetime
from unittest import mock
+from unittest.mock import call, patch
import pytest
from django.test import override_settings
from django.utils import timezone
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
@@ -13,9 +15,11 @@ from .....checkout.utils import (
add_voucher_to_checkout,
invalidate_checkout,
)
+from .....core.models import EventDelivery
from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....warehouse.models import Reservation, Stock
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ...mutations.utils import update_checkout_shipping_method_if_invalid
@@ -1071,3 +1075,79 @@ def test_checkout_shipping_address_skip_validation_by_app(
checkout.refresh_from_db()
assert checkout.shipping_address.postal_code == invalid_postal_code
assert checkout.shipping_address.validation_skipped is True
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_address_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_shipping_address_update_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ user_api_client,
+ checkout_with_item,
+ graphql_address_data,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout = checkout_with_item
+ assert checkout.shipping_address is None
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "shippingAddress": graphql_address_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutShippingAddressUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
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.py
index 4e129b0942..820449564a 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
@@ -1,20 +1,21 @@
from unittest import mock
-from unittest.mock import patch
+from unittest.mock import call, patch
import graphene
import pytest
+from django.test import override_settings
from .....account.models import Address
+from .....checkout.actions import call_checkout_event_for_checkout_info
from .....checkout.error_codes import CheckoutErrorCode
-from .....checkout.fetch import (
- fetch_checkout_info,
- fetch_checkout_lines,
-)
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout
+from .....core.models import EventDelivery
from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....shipping import models as shipping_models
from .....shipping.utils import convert_to_shipping_method_data
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -475,3 +476,247 @@ def test_with_active_problems_flow(
# then
assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_shipping_method_update_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ address,
+ api_client,
+ checkout_with_items,
+ shipping_method,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout_with_items.shipping_address = address
+ checkout_with_items.save(update_fields=["shipping_address"])
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingMethodId": method_id,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_shipping_method_update_external_shipping_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ address,
+ staff_api_client,
+ checkout_with_item,
+):
+ # given
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ response_method_id = "abcd"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": "Provider - Economy",
+ "amount": "10",
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_send_webhook_request_sync.side_effect = [
+ mock_json_response,
+ [],
+ [],
+ ]
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_webhook.app.identifier}:{response_method_id}"
+ )
+
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_checkout_shipping_method_update_to_none_triggers_sync_webhooks(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ address,
+ api_client,
+ checkout_with_items,
+ shipping_method,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout_with_items.shipping_address = address
+ checkout_with_items.save(update_fields=["shipping_address"])
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingMethodId": None,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 13557f7952..d7b89e90a8 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -3,14 +3,7 @@ import secrets
from collections.abc import Collection, Iterable
from enum import Enum
from itertools import chain
-from typing import (
- Any,
- Optional,
- TypeVar,
- Union,
- cast,
- overload,
-)
+from typing import Any, Optional, TypeVar, Union, cast, overload
from uuid import UUID
import graphene
diff --git a/saleor/graphql/meta/extra_methods.py b/saleor/graphql/meta/extra_methods.py
index 2e31109ba9..94aa4ee862 100644
--- a/saleor/graphql/meta/extra_methods.py
+++ b/saleor/graphql/meta/extra_methods.py
@@ -1,12 +1,58 @@
+from ...checkout.actions import (
+ call_checkout_event_for_checkout_info,
+ checkout_event_requires_sync_webhooks_to_trigger,
+)
+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...product.models import Product, ProductVariant
+from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ...webhook.utils import get_webhooks_for_multiple_events
from ..core import ResolveInfo
from ..plugins.dataloaders import get_plugin_manager_promise
def extra_checkout_actions(instance, info: ResolveInfo, **data):
manager = get_plugin_manager_promise(info.context).get()
- manager.checkout_updated(instance)
- manager.checkout_metadata_updated(instance)
+ webhook_event_map = get_webhooks_for_multiple_events(
+ [
+ WebhookEventAsyncType.CHECKOUT_UPDATED,
+ WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED,
+ *WebhookEventSyncType.CHECKOUT_EVENTS,
+ ]
+ )
+ # 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
+ ):
+ lines_info, _ = fetch_checkout_lines(
+ instance,
+ )
+ checkout_info = fetch_checkout_info(
+ instance,
+ lines_info,
+ manager,
+ )
+ call_checkout_event_for_checkout_info(
+ manager=manager,
+ event_func=manager.checkout_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines_info,
+ webhook_event_map=webhook_event_map,
+ )
+ call_checkout_event_for_checkout_info(
+ manager=manager,
+ event_func=manager.checkout_metadata_updated,
+ event_name=WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines_info,
+ webhook_event_map=webhook_event_map,
+ )
+ else:
+ manager.checkout_updated(instance)
+ manager.checkout_metadata_updated(instance)
def extra_channel_actions(instance, info: ResolveInfo, **data):
diff --git a/saleor/graphql/meta/tests/mutations/test_checkout.py b/saleor/graphql/meta/tests/mutations/test_checkout.py
index c717e6dee4..276c64324e 100644
--- a/saleor/graphql/meta/tests/mutations/test_checkout.py
+++ b/saleor/graphql/meta/tests/mutations/test_checkout.py
@@ -1,7 +1,14 @@
-from unittest.mock import patch
+from datetime import timedelta
+from unittest.mock import call, patch
import graphene
+from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
+from .....checkout.actions import call_checkout_event_for_checkout_info
+from .....core.models import EventDelivery
+from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE
from .test_delete_metadata import (
execute_clear_public_metadata_for_item,
@@ -353,3 +360,145 @@ def test_update_public_metadata_for_checkout_line(api_client, checkout_line):
checkout_line_id,
value="NewMetaValue",
)
+
+
+@freeze_time("2023-05-31 12:00:01")
+@patch(
+ "saleor.graphql.meta.extra_methods.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_add_metadata_for_checkout_triggers_sync_webhooks_with_checkout_updated(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ checkout.price_expiration = timezone.now() - timedelta(hours=10)
+ checkout.save(update_fields=["price_expiration"])
+ # when
+ response = execute_update_public_metadata_for_item(
+ api_client, None, checkout_id, "Checkout"
+ )
+
+ # then
+ assert response["data"]["updateMetadata"]["errors"] == []
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_update_delivery.id},
+ queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
+
+
+@freeze_time("2023-05-31 12:00:01")
+@patch(
+ "saleor.graphql.meta.extra_methods.call_checkout_event_for_checkout_info",
+ wraps=call_checkout_event_for_checkout_info,
+)
+@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_add_metadata_for_checkout_triggers_sync_webhooks_with_updated_metadata(
+ mocked_send_webhook_request_async,
+ mocked_send_webhook_request_sync,
+ wrapped_call_checkout_event_for_checkout,
+ setup_checkout_webhooks,
+ settings,
+ api_client,
+ checkout,
+):
+ # given
+ mocked_send_webhook_request_sync.return_value = []
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_metadata_updated_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED)
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ checkout.price_expiration = timezone.now() - timedelta(hours=10)
+ checkout.save(update_fields=["price_expiration"])
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ api_client, None, checkout_id, "Checkout"
+ )
+
+ # then
+ assert response["data"]["updateMetadata"]["errors"] == []
+
+ # confirm that event delivery was generated for each webhook.
+ checkout_metadata_updated_delivery = EventDelivery.objects.get(
+ webhook_id=checkout_metadata_updated_webhook.id
+ )
+ tax_delivery = EventDelivery.objects.get(webhook_id=tax_webhook.id)
+ shipping_methods_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_webhook.id,
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ filter_shipping_delivery = EventDelivery.objects.get(
+ webhook_id=shipping_filter_webhook.id,
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ )
+
+ mocked_send_webhook_request_async.assert_called_once_with(
+ kwargs={"event_delivery_id": checkout_metadata_updated_delivery.id},
+ queue=None,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+ )
+ mocked_send_webhook_request_sync.assert_has_calls(
+ [
+ call(shipping_methods_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(filter_shipping_delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT),
+ call(tax_delivery),
+ ]
+ )
+ assert wrapped_call_checkout_event_for_checkout.called
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 13022e7300..96f2496c32 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -4,14 +4,7 @@ from collections import defaultdict
from collections.abc import Iterable
from decimal import Decimal
from functools import partial
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Final,
- Optional,
- Union,
-)
+from typing import TYPE_CHECKING, Any, Callable, Final, Optional, Union
import graphene
from django.conf import settings
@@ -56,7 +49,7 @@ from ...payment.utils import (
)
from ...settings import WEBHOOK_SYNC_TIMEOUT
from ...thumbnail.models import Thumbnail
-from ...webhook.const import CACHE_EXCLUDED_SHIPPING_KEY, WEBHOOK_CACHE_DEFAULT_TIMEOUT
+from ...webhook.const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.payloads import (
generate_checkout_payload,
@@ -3190,14 +3183,13 @@ class WebhookPlugin(BasePlugin):
order,
available_shipping_methods,
)
- cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order.id)
return get_excluded_shipping_data(
event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
previous_value=previous_value,
payload_fun=payload_fun,
- cache_key=cache_key,
subscribable_object=order,
allow_replica=self.allow_replica,
+ requestor=self.requestor,
)
def excluded_shipping_methods_for_checkout(
@@ -3211,12 +3203,10 @@ class WebhookPlugin(BasePlugin):
checkout,
available_shipping_methods,
)
- cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout.token)
return get_excluded_shipping_data(
event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
previous_value=previous_value,
payload_fun=payload_function,
- cache_key=cache_key,
subscribable_object=checkout,
allow_replica=self.allow_replica,
)
diff --git a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
index 164eca4481..e9a4e399c3 100644
--- a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
+++ b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
@@ -3,11 +3,9 @@ from unittest import mock
import graphene
-from saleor.webhook.const import (
- CACHE_EXCLUDED_SHIPPING_KEY,
- CACHE_EXCLUDED_SHIPPING_TIME,
-)
-
+from ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIME
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.transport.utils import generate_cache_key_for_webhook
from ...base_plugin import ExcludedShippingMethod
@@ -81,11 +79,12 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(
shipping_app_factory,
):
# given
- shipping_app_factory()
+ shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
webhook_reason = "Order contains dangerous products."
other_reason = "Shipping is not applicable for this order."
- mocked_webhook.return_value = {
+ webhook_response = {
"excluded_methods": [
{
"id": graphene.Node.to_global_id("ShippingMethod", "1"),
@@ -93,7 +92,11 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(
}
]
}
- payload = json.dumps({"order": {"id": 1, "some_field": "12"}})
+
+ mocked_webhook.return_value = webhook_response
+
+ payload_dict = {"order": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
mocked_cache_get.return_value = None
@@ -114,14 +117,17 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(
# then
assert mocked_webhook.called
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order_with_lines.id)
-
- expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+ expected_cache_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
mocked_cache_set.assert_called_once_with(
expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
@@ -142,11 +148,11 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_dif
shipping_app_factory,
):
# given
- shipping_app_factory()
+ shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
webhook_reason = "Order contains dangerous products."
other_reason = "Shipping is not applicable for this order."
-
- mocked_webhook.return_value = {
+ webhook_response = {
"excluded_methods": [
{
"id": graphene.Node.to_global_id("ShippingMethod", "1"),
@@ -154,13 +160,13 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_dif
}
]
}
- payload = json.dumps({"order": {"id": 1, "some_field": "12"}})
+ mocked_webhook.return_value = webhook_response
+
+ payload_dict = {"order": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
- mocked_cache_get.return_value = (
- {"order": "different-payload"},
- [{"id": "1", "reason": webhook_reason}],
- )
+ mocked_cache_get.return_value = None
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
@@ -178,14 +184,18 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_dif
# then
assert mocked_webhook.called
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order_with_lines.id)
-
- expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+ expected_cache_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
mocked_cache_set.assert_called_once_with(
expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
@@ -263,11 +273,13 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(
shipping_app_factory,
):
# given
- shipping_app_factory()
+ shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
+
webhook_reason = "Order contains dangerous products."
other_reason = "Shipping is not applicable for this order."
- mocked_webhook.return_value = {
+ webhook_response = {
"excluded_methods": [
{
"id": graphene.Node.to_global_id("ShippingMethod", "1"),
@@ -275,8 +287,10 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(
}
]
}
+ mocked_webhook.return_value = webhook_response
- payload = json.dumps({"checkout": {"id": 1, "some_field": "12"}})
+ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
mocked_cache_get.return_value = None
@@ -298,14 +312,17 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(
# then
assert mocked_webhook.called
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
-
- expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+ expected_cache_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
mocked_cache_set.assert_called_once_with(
expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
@@ -327,11 +344,13 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_dif
shipping_app_factory,
):
# given
- shipping_app_factory()
+ shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
+
webhook_reason = "Order contains dangerous products."
other_reason = "Shipping is not applicable for this order."
- mocked_webhook.return_value = {
+ webhook_response = {
"excluded_methods": [
{
"id": graphene.Node.to_global_id("ShippingMethod", "1"),
@@ -340,13 +359,13 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_dif
]
}
- payload = json.dumps({"checkout": {"id": 1, "some_field": "12"}})
+ mocked_webhook.return_value = webhook_response
+
+ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
- mocked_cache_get.return_value = (
- {"checkout": "different_payload"},
- [{"id": "1", "reason": webhook_reason}],
- )
+ mocked_cache_get.return_value = None
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
@@ -363,12 +382,16 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_dif
# then
assert mocked_webhook.called
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
-
- expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+ expected_cache_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
+ mocked_cache_get.assert_called_once_with(expected_cache_key)
mocked_cache_set.assert_called_once_with(
expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index d11aa0a3e5..4588ebe685 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -1,12 +1,13 @@
import json
from unittest import mock
+from unittest.mock import call
import graphene
import pytest
from ....core.models import EventDelivery
from ....graphql.tests.utils import get_graphql_content
-from ....webhook.const import CACHE_EXCLUDED_SHIPPING_KEY, CACHE_EXCLUDED_SHIPPING_TIME
+from ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIME
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
from ....webhook.payloads import (
@@ -20,6 +21,7 @@ from ....webhook.transport.shipping import (
to_shipping_app_id,
)
from ....webhook.transport.synchronous.transport import trigger_webhook_sync
+from ....webhook.transport.utils import generate_cache_key_for_webhook
from ...base_plugin import ExcludedShippingMethod
ORDER_QUERY_SHIPPING_METHOD = """
@@ -68,7 +70,7 @@ CHECKOUT_QUERY_SHIPPING_METHOD = """
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -84,9 +86,10 @@ def test_excluded_shipping_methods_for_order(
):
# given
shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
webhook_reason = "Order contains dangerous products."
other_reason = "Shipping is not applicable for this order."
- mocked_webhook.return_value = {
+ webhook_response = {
"excluded_methods": [
{
"id": graphene.Node.to_global_id("ShippingMethod", "1"),
@@ -94,7 +97,9 @@ def test_excluded_shipping_methods_for_order(
}
]
}
- payload = mock.MagicMock()
+ mocked_webhook.return_value = webhook_response
+ payload_dict = {"order": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
@@ -115,28 +120,33 @@ def test_excluded_shipping_methods_for_order(
assert em.id == "1"
assert webhook_reason in em.reason
assert other_reason in em.reason
- event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
+
mocked_webhook.assert_called_once_with(
WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
payload,
- shipping_app.webhooks.get(events__event_type=event_type),
+ shipping_webhook,
False,
subscribable_object=order_with_lines,
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
+ expected_cache_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
)
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order_with_lines.id)
-
- expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
mocked_cache_set.assert_called_once_with(
expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -152,34 +162,37 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
):
# given
shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
+
second_shipping_app = shipping_app_factory(app_name="shipping-app2")
+ second_shipping_webhook = second_shipping_app.webhooks.get()
webhook_reason = "Order contains dangerous products."
webhook_second_reason = "Shipping is not applicable for this order."
+ first_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ second_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ }
- mocked_webhook.side_effect = [
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_reason,
- }
- ]
- },
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_second_reason,
- },
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "2"),
- "reason": webhook_second_reason,
- },
- ]
- },
- ]
+ mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]
- payload = mock.MagicMock()
+ payload_dict = {"order": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
@@ -202,36 +215,56 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
mocked_webhook.assert_any_call(
event_type,
payload,
- shipping_app.webhooks.get(events__event_type=event_type),
+ shipping_webhook,
False,
subscribable_object=order_with_lines,
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
)
mocked_webhook.assert_any_call(
event_type,
payload,
- second_shipping_app.webhooks.get(events__event_type=event_type),
+ second_shipping_webhook,
False,
subscribable_object=order_with_lines,
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
+ expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
+ expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(
+ payload_dict,
+ second_shipping_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ second_shipping_app.id,
)
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order_with_lines.id)
- expected_excluded_shipping_method = [
- {"id": "1", "reason": webhook_reason},
- {"id": "1", "reason": webhook_second_reason},
- {"id": "2", "reason": webhook_second_reason},
- ]
+ assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key
- mocked_cache_set.assert_called_once_with(
- expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ mocked_cache_set.assert_has_calls(
+ [
+ call(
+ expected_cache_for_first_webhook_key,
+ first_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ call(
+ expected_cache_for_second_webhook_key,
+ second_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ ]
)
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -247,13 +280,14 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
):
# given
shipping_app = shipping_app_factory()
+ first_webhook = shipping_app.webhooks.get()
event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
# create the second webhook with the same event
second_webhook = Webhook.objects.create(
name="shipping-webhook-1",
app=shipping_app,
- target_url="https://shipping-gateway.com/api/",
+ target_url="https://shipping-gateway.com/apiv2/",
)
second_webhook.events.create(
event_type=event_type,
@@ -263,30 +297,31 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
webhook_reason = "Order contains dangerous products."
webhook_second_reason = "Shipping is not applicable for this order."
- mocked_webhook.side_effect = [
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_reason,
- }
- ]
- },
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_second_reason,
- },
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "2"),
- "reason": webhook_second_reason,
- },
- ]
- },
- ]
+ first_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ second_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ }
+
+ mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]
- payload = mock.MagicMock()
+ payload_dict = {"order": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
@@ -305,30 +340,55 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
assert em.id == "1"
assert webhook_reason in em.reason
assert webhook_second_reason in em.reason
- webhooks = shipping_app.webhooks.filter(events__event_type=event_type)
- assert len(webhooks) > 1
- for webhook in webhooks:
- mocked_webhook.assert_any_call(
- event_type,
- payload,
- webhook,
- False,
- subscribable_object=order_with_lines,
- timeout=settings.WEBHOOK_SYNC_TIMEOUT,
- )
-
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(order_with_lines.id)
- expected_excluded_shipping_method = [
- {"id": "1", "reason": webhook_reason},
- {"id": "1", "reason": webhook_second_reason},
- {"id": "2", "reason": webhook_second_reason},
- ]
+ mocked_webhook.assert_any_call(
+ event_type,
+ payload,
+ first_webhook,
+ False,
+ subscribable_object=order_with_lines,
+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
+ mocked_webhook.assert_any_call(
+ event_type,
+ payload,
+ second_webhook,
+ False,
+ subscribable_object=order_with_lines,
+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
- mocked_cache_set.assert_called_once_with(
- expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(
+ payload_dict,
+ first_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
+ expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(
+ payload_dict,
+ second_webhook.target_url,
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
+ )
+ assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key
+
+ mocked_cache_set.assert_has_calls(
+ [
+ call(
+ expected_cache_for_first_webhook_key,
+ first_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ call(
+ expected_cache_for_second_webhook_key,
+ second_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ ]
)
@@ -530,7 +590,7 @@ def test_trigger_webhook_sync(mock_request, shipping_app):
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -547,10 +607,11 @@ def test_excluded_shipping_methods_for_checkout_webhook(
):
# given
shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
webhook_reason = "Checkout contains dangerous products."
other_reason = "Shipping is not applicable for this checkout."
- mocked_webhook.return_value = {
+ webhook_response = {
"excluded_methods": [
{
"id": graphene.Node.to_global_id("ShippingMethod", "1"),
@@ -558,8 +619,13 @@ def test_excluded_shipping_methods_for_checkout_webhook(
}
]
}
- payload = mock.MagicMock()
+
+ mocked_webhook.return_value = webhook_response
+
+ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
+
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
previous_value = [
@@ -578,24 +644,28 @@ def test_excluded_shipping_methods_for_checkout_webhook(
assert em.id == "1"
assert webhook_reason in em.reason
assert other_reason in em.reason
- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+
mocked_webhook.assert_called_once_with(
- event_type,
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
payload,
- shipping_app.webhooks.get(events__event_type=event_type),
+ shipping_webhook,
False,
subscribable_object=checkout_with_items,
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
+ expected_cache_key = generate_cache_key_for_webhook(
+ payload_dict,
+ shipping_webhook.target_url,
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ shipping_app.id,
)
-
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
-
- expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
mocked_cache_set.assert_called_once_with(
expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
@@ -645,7 +715,7 @@ def test_excluded_shipping_methods_for_checkout(
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -662,34 +732,41 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
):
# given
shipping_app = shipping_app_factory()
+ shipping_webhook = shipping_app.webhooks.get()
+
second_shipping_app = shipping_app_factory()
+ second_shipping_webhook = second_shipping_app.webhooks.get()
+
webhook_reason = "Checkout contains dangerous products."
webhook_second_reason = "Shipping is not applicable for this checkout."
- mocked_webhook.side_effect = [
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_reason,
- }
- ]
- },
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_second_reason,
- },
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "2"),
- "reason": webhook_second_reason,
- },
- ]
- },
- ]
- payload = mock.MagicMock()
+ first_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ second_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ }
+
+ mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]
+
+ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
+
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
previous_value = []
@@ -711,37 +788,54 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
mocked_webhook.assert_any_call(
event_type,
payload,
- shipping_app.webhooks.get(events__event_type=event_type),
+ shipping_webhook,
False,
subscribable_object=checkout_with_items,
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
)
mocked_webhook.assert_any_call(
event_type,
payload,
- second_shipping_app.webhooks.get(events__event_type=event_type),
+ second_shipping_webhook,
False,
subscribable_object=checkout_with_items,
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
)
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
+ expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(
+ payload_dict, shipping_webhook.target_url, event_type, shipping_app.id
+ )
+ expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(
+ payload_dict,
+ second_shipping_webhook.target_url,
+ event_type,
+ second_shipping_app.id,
+ )
- expected_excluded_shipping_method = [
- {"id": "1", "reason": webhook_reason},
- {"id": "1", "reason": webhook_second_reason},
- {"id": "2", "reason": webhook_second_reason},
- ]
+ assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key
- mocked_cache_set.assert_called_once_with(
- expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ mocked_cache_set.assert_has_calls(
+ [
+ call(
+ expected_cache_for_first_webhook_key,
+ first_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ call(
+ expected_cache_for_second_webhook_key,
+ second_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ ]
)
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -758,13 +852,14 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
):
# given
shipping_app = shipping_app_factory()
+ first_webhook = shipping_app.webhooks.get()
event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
# create the second webhook with the same event
second_webhook = Webhook.objects.create(
name="shipping-webhook-1",
app=shipping_app,
- target_url="https://shipping-gateway.com/api/",
+ target_url="https://shipping-gateway.com/apiv2/",
)
second_webhook.events.create(
event_type=event_type,
@@ -774,30 +869,33 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
webhook_reason = "Checkout contains dangerous products."
webhook_second_reason = "Shipping is not applicable for this checkout."
- mocked_webhook.side_effect = [
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_reason,
- }
- ]
- },
- {
- "excluded_methods": [
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "1"),
- "reason": webhook_second_reason,
- },
- {
- "id": graphene.Node.to_global_id("ShippingMethod", "2"),
- "reason": webhook_second_reason,
- },
- ]
- },
- ]
- payload = mock.MagicMock()
+ first_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ second_webhook_response = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ }
+
+ mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]
+
+ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
+ payload = json.dumps(payload_dict)
mocked_payload.return_value = payload
+
plugin = webhook_plugin()
available_shipping_methods = available_shipping_methods_factory(num_methods=2)
previous_value = []
@@ -815,30 +913,49 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
assert em.id == "1"
assert webhook_reason in em.reason
assert webhook_second_reason in em.reason
- webhooks = shipping_app.webhooks.filter(events__event_type=event_type)
- assert len(webhooks) > 1
- for webhook in webhooks:
- mocked_webhook.assert_any_call(
- event_type,
- payload,
- webhook,
- False,
- subscribable_object=checkout_with_items,
- timeout=settings.WEBHOOK_SYNC_TIMEOUT,
- )
- expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
-
- expected_excluded_shipping_method = [
- {"id": "1", "reason": webhook_reason},
- {"id": "1", "reason": webhook_second_reason},
- {"id": "2", "reason": webhook_second_reason},
- ]
+ mocked_webhook.assert_any_call(
+ event_type,
+ payload,
+ first_webhook,
+ False,
+ subscribable_object=checkout_with_items,
+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
+ mocked_webhook.assert_any_call(
+ event_type,
+ payload,
+ second_webhook,
+ False,
+ subscribable_object=checkout_with_items,
+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request=None,
+ requestor=None,
+ )
- mocked_cache_set.assert_called_once_with(
- expected_cache_key,
- (payload, expected_excluded_shipping_method),
- CACHE_EXCLUDED_SHIPPING_TIME,
+ expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(
+ payload_dict, first_webhook.target_url, event_type, shipping_app.id
+ )
+ expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(
+ payload_dict, second_webhook.target_url, event_type, shipping_app.id
+ )
+ assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key
+
+ mocked_cache_set.assert_has_calls(
+ [
+ call(
+ expected_cache_for_first_webhook_key,
+ first_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ call(
+ expected_cache_for_second_webhook_key,
+ second_webhook_response,
+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ ),
+ ]
)
@@ -900,7 +1017,7 @@ def test_generate_excluded_shipping_methods_for_checkout_payload(
@mock.patch("saleor.webhook.transport.shipping.parse_excluded_shipping_methods")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
"saleor.webhook.transport.shipping.get_excluded_shipping_methods_from_response"
)
@@ -922,7 +1039,7 @@ def test_get_excluded_shipping_methods_or_fetch_invalid_response_type(
# when
get_excluded_shipping_methods_or_fetch(
- webhooks, event_type, '{"test":"payload"}', "test", checkout, False
+ webhooks, event_type, '{"test":"payload"}', checkout, False, None
)
# then
mocked_get_excluded.asssert_not_called()
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index b897876953..f457a6e827 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -104,9 +104,7 @@ from ..order.models import (
OrderLine,
)
from ..order.search import prepare_order_search_vector_value
-from ..order.utils import (
- get_voucher_discount_assigned_to_order,
-)
+from ..order.utils import get_voucher_discount_assigned_to_order
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
from ..payment.interface import AddressData, GatewayConfig, GatewayResponse, PaymentData
@@ -9422,3 +9420,138 @@ def setup_mock_for_cache():
cache_mock.delete = mocked_delete_cache
return _mocked_cache
+
+
+def setup_checkout_webhooks(
+ permission_handle_taxes,
+ permission_manage_shipping,
+ permission_manage_checkouts,
+):
+ subscription_async_webhooks = """
+ fragment CheckoutFragment on Checkout {
+ shippingPrice {
+ gross {
+ amount
+ }
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ }
+
+ subscription {
+ event {
+ ... on CheckoutCreated {
+ checkout {
+ ...CheckoutFragment
+ }
+ }
+ ... on CheckoutUpdated {
+ checkout {
+ ...CheckoutFragment
+ }
+ }
+ ... on CheckoutFullyPaid {
+ checkout {
+ ...CheckoutFragment
+ }
+ }
+ ... on CheckoutMetadataUpdated {
+ checkout {
+ ...CheckoutFragment
+ }
+ }
+ }
+ }
+ """
+
+ def _setup(additional_checkout_event):
+ 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_checkouts]
+ )
+ additional_app.permissions.add(permission_manage_checkouts)
+ (
+ tax_webhook,
+ shipping_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 ShippingListMethodsForCheckout { __typename } } }",
+ ),
+ Webhook(
+ name="Shipping webhook",
+ app=shipping_app,
+ target_url="http://127.0.0.1/test",
+ subscription_query="subscription { event { ... on CheckoutFilterShippingMethods { __typename } } }",
+ ),
+ Webhook(
+ name="Checkout additional webhook",
+ app=additional_app,
+ target_url="http://127.0.0.1/test",
+ subscription_query=subscription_async_webhooks,
+ ),
+ ]
+ )
+
+ WebhookEvent.objects.bulk_create(
+ [
+ WebhookEvent(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ webhook_id=tax_webhook.id,
+ ),
+ WebhookEvent(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ webhook_id=shipping_filter_webhook.id,
+ ),
+ WebhookEvent(
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ webhook_id=shipping_webhook.id,
+ ),
+ WebhookEvent(
+ event_type=additional_checkout_event,
+ webhook_id=additional_webhook.id,
+ ),
+ ]
+ )
+ return (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ additional_webhook,
+ )
+
+ return _setup
diff --git a/saleor/webhook/const.py b/saleor/webhook/const.py
index dbabdd0496..429f02b038 100644
--- a/saleor/webhook/const.py
+++ b/saleor/webhook/const.py
@@ -1,4 +1,3 @@
-CACHE_EXCLUDED_SHIPPING_KEY = "webhook_exclude_shipping_id_"
CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3
WEBHOOK_CACHE_DEFAULT_TIMEOUT: int = 5 * 60 # 5 minutes
APP_ID_PREFIX = "app"
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index d801ae32c1..c3a4f177b1 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -931,6 +931,11 @@ class WebhookEventSyncType:
PAYMENT_REFUND,
PAYMENT_VOID,
]
+ CHECKOUT_EVENTS = [
+ SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ CHECKOUT_FILTER_SHIPPING_METHODS,
+ CHECKOUT_CALCULATE_TAXES,
+ ]
# 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.py
index 26d8fbc5f3..c6ed395843 100644
--- a/saleor/webhook/tests/test_utils.py
+++ b/saleor/webhook/tests/test_utils.py
@@ -9,7 +9,7 @@ from ..observability.exceptions import (
TruncationError,
)
from ..observability.payload_schema import ObservabilityEventTypes
-from ..utils import get_webhooks_for_event
+from ..utils import get_webhooks_for_event, get_webhooks_for_multiple_events
@pytest.fixture
@@ -141,3 +141,71 @@ def test_truncation_error_extra_fields(
"payload_size": payload_size,
**kwargs,
}
+
+
+def test_get_webhooks_for_multiple_events(
+ async_app_factory, async_type, setup_checkout_webhooks, app, external_app
+):
+ # given
+ (
+ tax_webhook,
+ shipping_webhook,
+ shipping_filter_webhook,
+ checkout_created_webhook,
+ ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_CREATED)
+
+ attribute_created_webhook = app.webhooks.create(
+ name="Attribute webhook",
+ target_url="http://127.0.0.1/test",
+ )
+ attribute_created_webhook.events.create(
+ event_type=WebhookEventAsyncType.ATTRIBUTE_CREATED
+ )
+ second_attribute_created_webhook = app.webhooks.create(
+ name="Second attribute webhook",
+ target_url="http://127.0.0.1/test",
+ )
+ second_attribute_created_webhook.events.create(
+ event_type=WebhookEventAsyncType.ATTRIBUTE_CREATED
+ )
+
+ disabled_webhook = app.webhooks.create(
+ name="Attribute webhook", target_url="http://127.0.0.1/test", is_active=False
+ )
+ disabled_webhook.events.create(event_type=WebhookEventAsyncType.ATTRIBUTE_CREATED)
+
+ not_active_app = external_app
+ not_active_app.is_active = False
+ not_active_app.save()
+
+ not_active_webhook = not_active_app.webhooks.create(
+ name="Attribute webhook",
+ target_url="http://127.0.0.1/test",
+ )
+ not_active_webhook.events.create(event_type=WebhookEventAsyncType.ATTRIBUTE_CREATED)
+
+ # when
+ webhook_map = get_webhooks_for_multiple_events(
+ [
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ WebhookEventAsyncType.ATTRIBUTE_CREATED,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ WebhookEventAsyncType.ORDER_CREATED,
+ ]
+ )
+
+ # then
+ assert webhook_map == {
+ WebhookEventAsyncType.CHECKOUT_CREATED: {checkout_created_webhook},
+ WebhookEventAsyncType.ATTRIBUTE_CREATED: {
+ attribute_created_webhook,
+ second_attribute_created_webhook,
+ },
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES: {tax_webhook},
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT: {shipping_webhook},
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS: {
+ shipping_filter_webhook
+ },
+ }
diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.py
index 273ec48c2f..02e80cc4fd 100644
--- a/saleor/webhook/transport/shipping.py
+++ b/saleor/webhook/transport/shipping.py
@@ -4,8 +4,6 @@ import logging
from collections import defaultdict
from typing import Any, Callable, Optional, Union
-from django.conf import settings
-from django.core.cache import cache
from django.db.models import QuerySet
from graphql import GraphQLError
from prices import Money
@@ -15,11 +13,14 @@ from ...checkout.models import Checkout
from ...graphql.core.utils import from_global_id_or_error
from ...graphql.shipping.types import ShippingMethod
from ...order.models import Order
-from ...plugins.base_plugin import ExcludedShippingMethod
+from ...plugins.base_plugin import ExcludedShippingMethod, RequestorOrLazyObject
+from ...settings import WEBHOOK_SYNC_TIMEOUT
from ...shipping.interface import ShippingMethodData
from ...webhook.utils import get_webhooks_for_event
from ..const import APP_ID_PREFIX, CACHE_EXCLUDED_SHIPPING_TIME
-from .synchronous.transport import trigger_webhook_sync
+from .synchronous.transport import (
+ trigger_webhook_sync_if_not_cached,
+)
logger = logging.getLogger(__name__)
@@ -102,58 +103,48 @@ def validate_shipping_method_data(shipping_method_data):
return all(key in shipping_method_data for key in keys)
-def _compare_order_payloads(payload: str, cached_payload: str) -> bool:
- """Compare two strings of order payloads ignoring meta."""
- EXCLUDED_KEY = "meta"
- try:
- order_payload = json.loads(payload)["order"]
- cached_order_payload = json.loads(cached_payload)["order"]
- except: # noqa
- return False
- return {k: v for k, v in order_payload.items() if k != EXCLUDED_KEY} == {
- k: v for k, v in cached_order_payload.items() if k != EXCLUDED_KEY
- }
+def get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:
+ payload_dict = json.loads(payload)
+ source_object = payload_dict.get("checkout", payload_dict.get("order", {}))
+
+ # drop fields that change between requests but are not relevant for cache key
+ source_object.pop("last_change", None)
+ source_object.pop("meta", None)
+ return payload_dict
def get_excluded_shipping_methods_or_fetch(
webhooks: QuerySet,
event_type: str,
payload: str,
- cache_key: str,
subscribable_object: Optional[Union["Order", "Checkout"]],
allow_replica: bool,
+ requestor: Optional[RequestorOrLazyObject],
) -> dict[str, list[ExcludedShippingMethod]]:
"""Return data of all excluded shipping methods.
The data will be fetched from the cache. If missing it will fetch it from all
defined webhooks by calling a request to each of them one by one.
"""
- cached_data = cache.get(cache_key)
- if cached_data:
- cached_payload, excluded_shipping_methods = cached_data
- if (payload == cached_payload) or _compare_order_payloads(
- payload, cached_payload
- ):
- return parse_excluded_shipping_methods(excluded_shipping_methods)
-
+ cache_data = get_cache_data_for_exclude_shipping_methods(payload)
excluded_methods = []
# Gather responses from webhooks
for webhook in webhooks:
- if not webhook:
- continue
- response_data = trigger_webhook_sync(
- event_type,
- payload,
- webhook,
- allow_replica,
+ response_data = trigger_webhook_sync_if_not_cached(
+ event_type=event_type,
+ payload=payload,
+ webhook=webhook,
+ cache_data=cache_data,
+ allow_replica=allow_replica,
subscribable_object=subscribable_object,
- timeout=settings.WEBHOOK_SYNC_TIMEOUT,
+ request_timeout=WEBHOOK_SYNC_TIMEOUT,
+ cache_timeout=CACHE_EXCLUDED_SHIPPING_TIME,
+ requestor=requestor,
)
if response_data and isinstance(response_data, dict):
excluded_methods.extend(
get_excluded_shipping_methods_from_response(response_data)
)
- cache.set(cache_key, (payload, excluded_methods), CACHE_EXCLUDED_SHIPPING_TIME)
return parse_excluded_shipping_methods(excluded_methods)
@@ -161,9 +152,9 @@ def get_excluded_shipping_data(
event_type: str,
previous_value: list[ExcludedShippingMethod],
payload_fun: Callable[[], str],
- cache_key: str,
subscribable_object: Optional[Union["Order", "Checkout"]],
allow_replica: bool,
+ requestor: Optional[RequestorOrLazyObject] = None,
) -> list[ExcludedShippingMethod]:
"""Exclude not allowed shipping methods by sync webhook.
@@ -183,7 +174,7 @@ def get_excluded_shipping_data(
payload = payload_fun()
excluded_methods_map = get_excluded_shipping_methods_or_fetch(
- webhooks, event_type, payload, cache_key, subscribable_object, allow_replica
+ webhooks, event_type, payload, subscribable_object, allow_replica, requestor
)
# Gather responses for previous plugins
@@ -242,4 +233,8 @@ def get_cache_data_for_shipping_list_methods_for_checkout(payload: str) -> dict:
# drop fields that change between requests but are not relevant for cache key
key_data[0].pop("last_change")
key_data[0].pop("meta")
+ # Drop the external_app_shipping_id from the cache key as it should not have an
+ # impact on cache invalidation
+ if "external_app_shipping_id" in key_data[0].get("private_metadata", {}):
+ del key_data[0]["private_metadata"]["external_app_shipping_id"]
return key_data
diff --git a/saleor/webhook/transport/tests/test_shipping.py b/saleor/webhook/transport/tests/test_shipping.py
new file mode 100644
index 0000000000..0be285e0ea
--- /dev/null
+++ b/saleor/webhook/transport/tests/test_shipping.py
@@ -0,0 +1,44 @@
+from ....checkout.utils import get_or_create_checkout_metadata
+from ...payloads import (
+ generate_checkout_payload,
+ generate_excluded_shipping_methods_for_checkout_payload,
+)
+from ..shipping import (
+ get_cache_data_for_exclude_shipping_methods,
+ get_cache_data_for_shipping_list_methods_for_checkout,
+)
+
+
+def test_get_cache_data_for_shipping_list_methods_for_checkout(checkout_with_items):
+ # given
+ metadata = get_or_create_checkout_metadata(checkout_with_items)
+ metadata.store_value_in_private_metadata({"external_app_shipping_id": "something"})
+ metadata.save()
+ payload_str = generate_checkout_payload(checkout_with_items)
+ assert "last_change" in payload_str
+ assert "meta" in payload_str
+ assert "external_app_shipping_id" in payload_str
+
+ # when
+ cache_data = get_cache_data_for_shipping_list_methods_for_checkout(payload_str)
+
+ # then
+ assert "last_change" not in cache_data[0]
+ assert "meta" not in cache_data[0]
+ assert "external_app_shipping_id" not in cache_data[0]["private_metadata"]
+
+
+def test_get_cache_data_for_exclude_shipping_methods(checkout_with_items):
+ # given
+ payload_str = generate_excluded_shipping_methods_for_checkout_payload(
+ checkout_with_items, []
+ )
+ assert "last_change" in payload_str
+ assert "meta" in payload_str
+
+ # when
+ cache_data = get_cache_data_for_exclude_shipping_methods(payload_str)
+
+ # then
+ assert "last_change" not in cache_data
+ assert "meta" not in cache_data
diff --git a/saleor/webhook/transport/tests/test_utils.py b/saleor/webhook/transport/tests/test_utils.py
index afd11099fd..375675b1ed 100644
--- a/saleor/webhook/transport/tests/test_utils.py
+++ b/saleor/webhook/transport/tests/test_utils.py
@@ -1,6 +1,6 @@
import datetime
import json
-from unittest.mock import MagicMock, call, patch
+from unittest.mock import MagicMock, patch
import pytest
from celery import Task
@@ -10,7 +10,6 @@ from celery.utils.threads import LocalStack
from ....core import EventDeliveryStatus
from ....core.models import EventDeliveryAttempt
from ...event_types import WebhookEventAsyncType
-from ..shipping import get_cache_data_for_shipping_list_methods_for_checkout
from ..utils import WebhookResponse, handle_webhook_retry, send_webhook_using_aws_sqs
@@ -188,19 +187,3 @@ def test_send_webhook_using_aws_sqs_with_fifo_queue(mocked_boto3_client):
# then
_, send_message_kwargs = mocked_boto3_client.send_message.call_args
assert send_message_kwargs["MessageGroupId"] == domain
-
-
-@patch("saleor.webhook.transport.shipping.json.loads")
-def test_get_cache_data_for_shipping_list_methods_for_checkout(mock_loads):
- # when
- result = get_cache_data_for_shipping_list_methods_for_checkout("test payload")
-
- # then
- assert result is mock_loads.return_value
- assert mock_loads.mock_calls == [
- call("test payload"),
- call().__getitem__(0),
- call().__getitem__().pop("last_change"),
- call().__getitem__(0),
- call().__getitem__().pop("meta"),
- ]
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index 6ceae01e2f..bb78610f63 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -1,3 +1,4 @@
+from collections import defaultdict
from typing import TYPE_CHECKING, Optional
from django.conf import settings
@@ -12,13 +13,11 @@ if TYPE_CHECKING:
from django.db.models import QuerySet
-def get_webhooks_for_event(
+def get_filter_for_single_webhook_event(
event_type: str,
- webhooks: Optional["QuerySet[Webhook]"] = None,
apps_ids: Optional["list[int]"] = None,
apps_identifier: Optional[list[str]] = None,
-) -> "QuerySet[Webhook]":
- """Get active webhooks from the database for an event."""
+):
permissions = {}
required_permission = WebhookEventAsyncType.PERMISSIONS.get(
event_type, WebhookEventSyncType.PERMISSIONS.get(event_type)
@@ -31,11 +30,6 @@ def get_webhooks_for_event(
# In this function we use the replica database for all queryset reads, as there is
# no risk that any mutation would change the result of these querysets.
- 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()
-
app_kwargs: dict = {"is_active": True, **permissions}
if event_type != WebhookEventAsyncType.APP_DELETED:
app_kwargs["removed_at__isnull"] = True
@@ -54,13 +48,91 @@ def get_webhooks_for_event(
webhook_events = WebhookEvent.objects.using(
settings.DATABASE_CONNECTION_REPLICA_NAME
).filter(event_type__in=event_types)
+ return (
+ Q(is_active=True)
+ & Q(Exists(apps.filter(id=OuterRef("app_id"))))
+ & Q(Exists(webhook_events.filter(webhook_id=OuterRef("id"))))
+ )
+
+
+def get_webhooks_for_event(
+ event_type: str,
+ webhooks: Optional["QuerySet[Webhook]"] = None,
+ apps_ids: Optional["list[int]"] = None,
+ apps_identifier: Optional[list[str]] = None,
+) -> "QuerySet[Webhook]":
+ """Get active webhooks from the database for an event."""
+
+ 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()
+
+ filters = get_filter_for_single_webhook_event(
+ event_type=event_type, apps_ids=apps_ids, apps_identifier=apps_identifier
+ )
+
return (
webhooks.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
- .filter(
- Q(is_active=True)
- & Q(Exists(apps.filter(id=OuterRef("app_id"))))
- & Q(Exists(webhook_events.filter(webhook_id=OuterRef("id"))))
+ .filter(filters)
+ .select_related("app")
+ .prefetch_related("app__permissions__content_type")
+ )
+
+
+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,
+) -> 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()
+
+ 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")
)
+ 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_perm_map = {}
+ for app in webhook_app.values():
+ app_permissions = app.permissions.all()
+ app_permission_codenames = [
+ permission.codename for permission in app_permissions
+ ]
+ app_perm_map[app.id] = app_permission_codenames
+
+ 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:
+ required_permission = WebhookEventAsyncType.PERMISSIONS.get(
+ event_type, WebhookEventSyncType.PERMISSIONS.get(event_type)
+ )
+ 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