Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extrach checkout exclude-shipping webhook from plugin (#18827)
Maciej Korycinskie46cc8120e22
diff --git a/saleor/app/tests/fixtures/app.py b/saleor/app/tests/fixtures/app.pyindex e6240f7984..a3a0f0cf80 100644--- a/saleor/app/tests/fixtures/app.py+++ b/saleor/app/tests/fixtures/app.py@@ -131,6 +131,60 @@ def app_exclude_shipping_for_order(return app+def app_exclude_shipping_for_checkout(+ db,+ permission_manage_orders,+ permission_manage_checkouts,+):+ app = App.objects.create(name="Shipping App", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_orders)+ app.permissions.add(permission_manage_checkouts)++ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ webhook=webhook,+ ),+ ]+ )+ return app+++def second_app_exclude_shipping_for_checkout(+ db,+ permission_manage_orders,+ permission_manage_checkouts,+):+ app = App.objects.create(name="Second Shipping App", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_orders)+ app.permissions.add(permission_manage_checkouts)++ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway2.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ webhook=webhook,+ ),+ ]+ )+ return app++@pytest.fixturedef second_app_exclude_shipping_for_order(db,diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex ddf87afde6..5ebe1bd76b 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -735,11 +735,29 @@ def fetch_shipping_methods_for_checkout(all_methods = list(built_in_shipping_methods_dict.values()) + list(external_shipping_methods_dict.values())- excluded_methods = checkout_info.manager.excluded_shipping_methods_for_checkout(++ # Circular import caused by the current definition of subscription payloads+ # and their usage in webhook/transport layer. Until moving them out from the+ # transport, we will have circular imports.+ from .webhooks.exclude_shipping import excluded_shipping_methods_for_checkout++ allow_replica = not (+ checkout_info.database_connection_name+ == settings.DATABASE_CONNECTION_DEFAULT_NAME+ )++ requestor = (+ checkout_info.manager.requestor_getter()+ if checkout_info.manager.requestor_getter+ else None+ )++ excluded_methods = excluded_shipping_methods_for_checkout(checkout,- checkout_info.channel,- all_methods,- checkout_info.pregenerated_payloads_for_excluded_shipping_method,+ available_shipping_methods=all_methods,+ allow_replica=allow_replica,+ requestor=requestor,+ pregenerated_subscription_payloads=checkout_info.pregenerated_payloads_for_excluded_shipping_method,)initialize_shipping_method_active_status(all_methods, excluded_methods)diff --git a/saleor/checkout/tests/test_fetch.py b/saleor/checkout/tests/test_fetch.pyindex 0371173530..6ef28017b2 100644--- a/saleor/checkout/tests/test_fetch.py+++ b/saleor/checkout/tests/test_fetch.py@@ -6,9 +6,8 @@ from django.utils import timezonefrom freezegun import freeze_timefrom prices import Money-from ...plugins.base_plugin import ExcludedShippingMethodfrom ...product.models import ProductChannelListing, ProductVariantChannelListing-from ...shipping.interface import ShippingMethodData+from ...shipping.interface import ExcludedShippingMethod, ShippingMethodDatafrom ...shipping.models import ShippingMethodfrom ...webhook.transport.shipping_helpers import to_shipping_app_idfrom ..fetch import (@@ -651,7 +650,7 @@ def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_built_in_sh@freeze_time("2024-05-31 12:00:01")@mock.patch(- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout")def test_fetch_shipping_methods_for_checkout_with_excluded_built_in_shipping_method(mocked_exclude_shipping_methods,@@ -1069,7 +1068,7 @@ def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_external_sh@freeze_time("2024-05-31 12:00:01")@mock.patch(- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout")@mock.patch("saleor.plugins.manager.PluginsManager.list_shipping_methods_for_checkout")def test_fetch_shipping_methods_for_checkout_with_excluded_external_shipping_method(@@ -1139,6 +1138,7 @@ def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_ship):# givenshipping_price_amount = Decimal(10)+ shipping_price_amount = Decimal(10)available_shipping_method = ShippingMethodData(id=to_shipping_app_id(app, "external-shipping-method-id"),diff --git a/saleor/checkout/tests/webhooks/__init__.py b/saleor/checkout/tests/webhooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/checkout/tests/webhooks/static_payloads/__init__.py b/saleor/checkout/tests/webhooks/static_payloads/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/checkout/tests/webhooks/static_payloads/test_exclude_shipping.py b/saleor/checkout/tests/webhooks/static_payloads/test_exclude_shipping.pynew file mode 100644index 0000000000..ef872ff92d--- /dev/null+++ b/saleor/checkout/tests/webhooks/static_payloads/test_exclude_shipping.py@@ -0,0 +1,72 @@+import json+from decimal import Decimal++import graphene+from measurement.measures import Weight+from prices import Money++from .....shipping.interface import ShippingMethodData+from ....webhooks.exclude_shipping import (+ _generate_excluded_shipping_methods_for_checkout_payload,+)+++def test_generate_excluded_shipping_methods_for_checkout(checkout):+ shipping_method = ShippingMethodData(+ id="123",+ price=Money(Decimal("10.59"), "USD"),+ name="shipping",+ maximum_order_weight=Weight(kg=10),+ minimum_order_weight=Weight(g=1),+ maximum_delivery_days=10,+ minimum_delivery_days=2,+ )+ response = json.loads(+ _generate_excluded_shipping_methods_for_checkout_payload(+ checkout, [shipping_method]+ )+ )++ assert "checkout" in response+ assert response["shipping_methods"] == [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "123"),+ "price": "10.59",+ "currency": "USD",+ "name": "shipping",+ "maximum_order_weight": "10.0:kg",+ "minimum_order_weight": "1.0:g",+ "maximum_delivery_days": 10,+ "minimum_delivery_days": 2,+ }+ ]+++def test_generate_excluded_shipping_methods_for_checkout_payload(+ checkout_with_items,+):+ # given+ shipping_method = ShippingMethodData(+ id="123",+ price=Money(Decimal("10.59"), "USD"),+ name="shipping",+ maximum_order_weight=Weight(kg=10),+ minimum_order_weight=Weight(g=1),+ maximum_delivery_days=10,+ minimum_delivery_days=2,+ )++ # when+ json_payload = json.loads(+ _generate_excluded_shipping_methods_for_checkout_payload(+ checkout_with_items, available_shipping_methods=[shipping_method]+ )+ )+ # then+ assert len(json_payload["shipping_methods"]) == 1+ assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", shipping_method.id+ )++ assert "checkout" in json_payload+ assert "channel" in json_payload["checkout"]diff --git a/saleor/checkout/tests/webhooks/subscriptions/__init__.py b/saleor/checkout/tests/webhooks/subscriptions/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/checkout/tests/webhooks/subscriptions/test_exclude_shipping.py b/saleor/checkout/tests/webhooks/subscriptions/test_exclude_shipping.pynew file mode 100644index 0000000000..4f8042033f--- /dev/null+++ b/saleor/checkout/tests/webhooks/subscriptions/test_exclude_shipping.py@@ -0,0 +1,276 @@+import json++import graphene+import pytest++from .....shipping.interface import ShippingMethodData+from .....shipping.models import ShippingMethod+from .....shipping.utils import convert_to_shipping_method_data+from .....webhook.event_types import WebhookEventSyncType+from .....webhook.transport.asynchronous.transport import (+ create_deliveries_for_subscriptions,+)++CHECKOUT_FILTER_SHIPPING_METHODS = """+subscription{+ event{+ ...on CheckoutFilterShippingMethods{+ checkout{+ id+ }+ shippingMethods{+ name+ id+ }+ }+ }+}+"""++CHECKOUT_FILTER_SHIPPING_METHODS_CIRCULAR_SHIPPING_METHODS = """+subscription{+ event{+ ...on CheckoutFilterShippingMethods{+ checkout{+ id+ shippingMethods{+ id+ }+ }+ }+ }+}+"""++CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_SHIPPING_METHODS = """+subscription{+ event{+ ...on CheckoutFilterShippingMethods{+ checkout{+ id+ availableShippingMethods{+ id+ }+ }+ }+ }+}+"""++CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_PAYMENT_GATEWAYS = """+subscription{+ event{+ ...on CheckoutFilterShippingMethods{+ checkout{+ id+ availablePaymentGateways{+ id+ }+ }+ }+ }+}+"""+++CHECKOUT_SHIPPING_LIST_AND_FILTER = """+ subscription {+ event {+ ... on CheckoutFilterShippingMethods {+ __typename+ checkout {+ id+ }+ }+ ... on ShippingListMethodsForCheckout {+ __typename+ checkout {+ id+ }+ }+ }+ }+"""+++def subscription_checkout_filter_shipping_methods_webhook(subscription_webhook):+ return subscription_webhook(+ CHECKOUT_FILTER_SHIPPING_METHODS,+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ )+++def subscription_checkout_filter_shipping_method_webhook_with_shipping_methods(+ subscription_webhook,+):+ return subscription_webhook(+ CHECKOUT_FILTER_SHIPPING_METHODS_CIRCULAR_SHIPPING_METHODS,+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ )+++def subscription_checkout_filter_shipping_method_webhook_with_available_ship_methods(+ subscription_webhook,+):+ return subscription_webhook(+ CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_SHIPPING_METHODS,+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ )+++def subscription_checkout_filter_shipping_method_webhook_with_payment_gateways(+ subscription_webhook,+):+ return subscription_webhook(+ CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_PAYMENT_GATEWAYS,+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ )+++def test_checkout_filter_shipping_methods(+ checkout_with_shipping_required,+ subscription_checkout_filter_shipping_methods_webhook,+ address,+ shipping_method,+):+ # given+ checkout = checkout_with_shipping_required+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ webhooks = [subscription_checkout_filter_shipping_methods_webhook]+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ internal_methods: list[ShippingMethodData] = []+ for method in ShippingMethod.objects.all():+ shipping_method_data = convert_to_shipping_method_data(+ method, method.channel_listings.get(channel=checkout.channel)+ )+ internal_methods.append(shipping_method_data)++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, (checkout, internal_methods), webhooks+ )++ # then+ shipping_methods = [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", sm.id),+ "name": sm.name,+ }+ for sm in internal_methods+ ]+ payload = json.loads(deliveries[0].payload.get_payload())++ assert payload["checkout"] == {"id": checkout_id}+ for method in shipping_methods:+ assert method in payload["shippingMethods"]+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_checkout_filter_shipping_methods_no_methods_in_channel(+ checkout,+ subscription_checkout_filter_shipping_methods_webhook,+ address,+ shipping_method,+ shipping_method_channel_PLN,+):+ # given+ webhooks = [subscription_checkout_filter_shipping_methods_webhook]+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, (checkout, []), webhooks+ )++ # then+ expected_payload = {"checkout": {"id": checkout_id}, "shippingMethods": []}+ assert json.loads(deliveries[0].payload.get_payload()) == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_checkout_filter_shipping_methods_with_circular_call_for_shipping_methods(+ checkout_ready_to_complete,+ subscription_checkout_filter_shipping_method_webhook_with_shipping_methods,+):+ # given+ webhooks = [+ subscription_checkout_filter_shipping_method_webhook_with_shipping_methods+ ]+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, (checkout_ready_to_complete, []), webhooks+ )++ # then+ payload = json.loads(deliveries[0].payload.get_payload())++ assert len(payload["errors"]) == 1+ assert (+ payload["errors"][0]["message"]+ == "Resolving this field is not allowed in synchronous events."+ )+ assert payload["checkout"] is None+++def test_checkout_filter_shipping_methods_with_available_shipping_methods_field(+ checkout_ready_to_complete,+ subscription_checkout_filter_shipping_method_webhook_with_available_ship_methods,+):+ # given+ webhooks = [+ subscription_checkout_filter_shipping_method_webhook_with_available_ship_methods+ ]+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, (checkout_ready_to_complete, []), webhooks+ )++ # then+ payload = json.loads(deliveries[0].payload.get_payload())++ assert len(payload["errors"]) == 1+ assert (+ payload["errors"][0]["message"]+ == "Resolving this field is not allowed in synchronous events."+ )+ assert payload["checkout"] is None+++def test_checkout_filter_shipping_methods_with_circular_call_for_available_gateways(+ checkout_ready_to_complete,+ subscription_checkout_filter_shipping_method_webhook_with_payment_gateways,+):+ # given+ webhooks = [+ subscription_checkout_filter_shipping_method_webhook_with_payment_gateways+ ]+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, (checkout_ready_to_complete, []), webhooks+ )++ # then+ payload = json.loads(deliveries[0].payload.get_payload())++ assert len(payload["errors"]) == 1+ assert (+ payload["errors"][0]["message"]+ == "Resolving this field is not allowed in synchronous events."+ )+ assert payload["checkout"] is Nonediff --git a/saleor/checkout/tests/webhooks/test_exclude_shipping.py b/saleor/checkout/tests/webhooks/test_exclude_shipping.pynew file mode 100644index 0000000000..8c1c270278--- /dev/null+++ b/saleor/checkout/tests/webhooks/test_exclude_shipping.py@@ -0,0 +1,737 @@+import json+import uuid+from decimal import Decimal+from unittest import mock+from unittest.mock import call++import graphene+import pytest+from measurement.measures import Weight+from prices import Money++from ....graphql.core.utils import to_global_id_or_none+from ....graphql.tests.utils import get_graphql_content+from ....graphql.webhook.utils import get_subscription_query_hash+from ....shipping.interface import ExcludedShippingMethod, ShippingMethodData+from ....shipping.models import ShippingMethod+from ....webhook.event_types import WebhookEventSyncType+from ....webhook.models import Webhook+from ....webhook.response_schemas.shipping import logger as schema_logger+from ....webhook.response_schemas.utils.annotations import logger as annotations_logger+from ....webhook.transport.shipping_helpers import to_shipping_app_id+from ....webhook.transport.utils import generate_cache_key_for_webhook+from ...webhooks.exclude_shipping import (+ CACHE_EXCLUDED_SHIPPING_TIME,+ _generate_excluded_shipping_methods_for_checkout_payload,+ _get_cache_data_for_exclude_shipping_methods,+ _get_excluded_shipping_methods_from_response,+ _get_excluded_shipping_methods_or_fetch,+ excluded_shipping_methods_for_checkout,+)++CHECKOUT_QUERY_SHIPPING_METHOD = """+query Checkout($id: ID){+ checkout(id: $id) {+ shippingMethods {+ id+ name+ active+ }+ availableShippingMethods {+ id+ name+ active+ }+ }+}+"""+++def available_shipping_methods():+ return [+ ShippingMethodData(+ id="1",+ price=Money(Decimal(10), "usd"),+ name=uuid.uuid4().hex,+ maximum_order_weight=Weight(kg=0),+ minimum_order_weight=Weight(kg=0),+ maximum_delivery_days=0,+ minimum_delivery_days=5,+ ),+ ShippingMethodData(+ id="2",+ price=Money(Decimal(10), "usd"),+ name=uuid.uuid4().hex,+ maximum_order_weight=Weight(kg=0),+ minimum_order_weight=Weight(kg=0),+ maximum_delivery_days=0,+ minimum_delivery_days=5,+ ),+ ]+++ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"+)+def test_checkout_deliveries(+ mocked_webhook,+ staff_api_client,+ checkout_ready_to_complete,+ permission_manage_checkouts,+ settings,+ shipping_method_weight_based,+):+ # given+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ webhook_reason = "spanish-inquisition"+ excluded_shipping_method_id = (+ checkout_ready_to_complete.assigned_delivery.shipping_method_id+ )+ mocked_webhook.return_value = [+ ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)+ ]+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ # when+ response = staff_api_client.post_graphql(+ CHECKOUT_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(checkout_ready_to_complete)},+ )+ content = get_graphql_content(response)+ checkout_data = content["data"]["checkout"]++ shipping_methods = checkout_data["shippingMethods"]+ # then+ assert len(shipping_methods) == 2+ inactive_method = list(+ filter(+ lambda s: s["id"]+ == graphene.Node.to_global_id(+ "ShippingMethod", excluded_shipping_method_id+ ),+ shipping_methods,+ )+ )+ assert not inactive_method[0]["active"]+++ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"+)+def test_checkout_available_shipping_methods(+ mocked_webhook,+ staff_api_client,+ checkout_ready_to_complete,+ permission_manage_checkouts,+ settings,+ shipping_method_weight_based,+):+ # given+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ webhook_reason = "spanish-inquisition"++ excluded_shipping_method_id = (+ checkout_ready_to_complete.assigned_delivery.shipping_method_id+ )+ mocked_webhook.return_value = [+ ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)+ ]++ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ # when+ response = staff_api_client.post_graphql(+ CHECKOUT_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(checkout_ready_to_complete)},+ )+ content = get_graphql_content(response)+ shipping_methods = content["data"]["checkout"]["availableShippingMethods"]+ # then+ assert len(shipping_methods) == 1+ assert shipping_methods[0]["active"]+++ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"+)+def test_checkout_deliveries_webhook_called_once(+ mocked_webhook,+ staff_api_client,+ checkout_ready_to_complete,+ permission_manage_checkouts,+):+ # given+ mocked_webhook.side_effect = [[], AssertionError("called twice.")]+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ # when+ response = staff_api_client.post_graphql(+ CHECKOUT_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(checkout_ready_to_complete)},+ )+ content = get_graphql_content(response)+ checkout_data = content["data"]["checkout"]+ # then+ expected_count = ShippingMethod.objects.count()+ assert len(checkout_data["availableShippingMethods"]) == expected_count+ assert len(checkout_data["shippingMethods"]) == expected_count+ assert mocked_webhook.called+++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++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload"+)+def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_payload(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ checkout_with_items,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,+ settings,+):+ # given+ shipping_app = app_exclude_shipping_for_checkout+ shipping_webhook = shipping_app.webhooks.get()+ webhook_reason = "Checkout contains dangerous products."++ webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }++ mocked_webhook.return_value = webhook_response++ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}+ payload = json.dumps(payload_dict)+ mocked_payload.return_value = payload++ # when+ excluded_methods = excluded_shipping_methods_for_checkout(+ checkout_with_items,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )+ # then+ assert len(excluded_methods) == 1+ em = excluded_methods[0]+ assert em.id == "1"+ assert webhook_reason in em.reason++ mocked_webhook.assert_called_once_with(+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ payload,+ shipping_webhook,+ False,+ subscribable_object=(checkout_with_items, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ pregenerated_subscription_payload=None,+ )+ 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,+ webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ )++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload"+)+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"+)+def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_pregenerated_payload(+ mocked_subscription_payload,+ mocked_static_payload,+ mocked_webhook,+ mocked_cache_set,+ checkout_with_items,+ available_shipping_methods,+ exclude_shipping_app_with_subscription,+ settings,+):+ # given+ shipping_app = exclude_shipping_app_with_subscription+ shipping_webhook = shipping_app.webhooks.get()+ webhook_reason = "Checkout contains dangerous products."++ webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }++ mocked_webhook.return_value = webhook_response++ payload_dict = {"checkout": {"id": 1, "some_field": "12"}}+ query_hash = get_subscription_query_hash(shipping_webhook.subscription_query)+ pregenerated_payloads = {shipping_app.id: {query_hash: payload_dict}}+ payload = json.dumps(payload_dict)+ mocked_static_payload.return_value = payload++ # when+ excluded_methods = excluded_shipping_methods_for_checkout(+ checkout_with_items,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ pregenerated_subscription_payloads=pregenerated_payloads,+ )+ # then+ assert len(excluded_methods) == 1+ em = excluded_methods[0]+ assert em.id == "1"+ assert webhook_reason in em.reason++ mocked_webhook.assert_called_once_with(+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ payload,+ shipping_webhook,+ False,+ subscribable_object=(checkout_with_items, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ pregenerated_subscription_payload=payload_dict,+ )+ 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,+ webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ )+ mocked_subscription_payload.assert_not_called()++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload"+)+def test_multiple_app_with_excluded_shipping_methods_for_checkout(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ checkout_with_items,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,+ second_app_exclude_shipping_for_checkout,+ settings,+):+ # given+ shipping_app = app_exclude_shipping_for_checkout+ shipping_webhook = shipping_app.webhooks.get()++ second_shipping_app = second_app_exclude_shipping_for_checkout+ second_shipping_webhook = second_shipping_app.webhooks.get()++ webhook_reason = "Checkout contains dangerous products."+ webhook_second_reason = "Shipping is not applicable for this checkout."++ 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++ # when+ excluded_methods = excluded_shipping_methods_for_checkout(+ checkout_with_items,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )++ # then+ assert len(excluded_methods) == 2+ em = excluded_methods[0]+ assert em.id == "1"+ assert webhook_reason in em.reason+ assert webhook_second_reason in em.reason+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS+ mocked_webhook.assert_any_call(+ event_type,+ payload,+ shipping_webhook,+ False,+ subscribable_object=(checkout_with_items, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ pregenerated_subscription_payload=None,+ )+ mocked_webhook.assert_any_call(+ event_type,+ payload,+ second_shipping_webhook,+ False,+ subscribable_object=(checkout_with_items, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ pregenerated_subscription_payload=None,+ )+ assert mocked_webhook.call_count == 2++ 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,+ )++ 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,+ ),+ ]+ )++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload"+)+def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_checkout(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ checkout_with_items,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,+ settings,+):+ # given+ shipping_app = app_exclude_shipping_for_checkout+ 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/apiv2/",+ )+ second_webhook.events.create(+ event_type=event_type,+ webhook=second_webhook,+ )++ webhook_reason = "Checkout contains dangerous products."+ webhook_second_reason = "Shipping is not applicable for this checkout."++ 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++ # when+ excluded_methods = excluded_shipping_methods_for_checkout(+ checkout=checkout_with_items,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )++ # then+ assert len(excluded_methods) == 2+ em = excluded_methods[0]+ assert em.id == "1"+ assert webhook_reason in em.reason+ assert webhook_second_reason in em.reason++ mocked_webhook.assert_any_call(+ event_type,+ payload,+ first_webhook,+ False,+ subscribable_object=(checkout_with_items, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ pregenerated_subscription_payload=None,+ )+ mocked_webhook.assert_any_call(+ event_type,+ payload,+ second_webhook,+ False,+ subscribable_object=(checkout_with_items, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ pregenerated_subscription_payload=None,+ )+ assert mocked_webhook.call_count == 2++ 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,+ ),+ ]+ )+++ "saleor.checkout.webhooks.exclude_shipping._parse_excluded_shipping_methods"+)[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.checkout.webhooks.exclude_shipping._get_excluded_shipping_methods_from_response"+)+def test_get_excluded_shipping_methods_or_fetch_invalid_response_type(+ mocked_get_excluded,+ mocked_webhook_sync_trigger,+ mocked_parse,+ app,+ checkout,+):+ # given+ mocked_webhook_sync_trigger.return_value = ["incorrect_type"]+ webhook = Webhook.objects.create(+ name="Simple webhook", app=app, target_url="http://www.example.com/test"+ )+ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS+ webhook.events.create(event_type=event_type)+ webhooks = Webhook.objects.all()++ # when+ _get_excluded_shipping_methods_or_fetch(+ webhooks, event_type, '{"test":"payload"}', checkout, False, None+ )+ # then+ mocked_get_excluded.asssert_not_called()+ mocked_parse.assert_called_once_with([])++[email protected](annotations_logger, "warning")[email protected](schema_logger, "warning")+def test_parse_excluded_shipping_methods_response(+ mocked_schema_logger, mocked_annotations_logger, app+):+ # given+ external_id = to_shipping_app_id(app, "test-1234")+ response = {+ "excluded_methods": [+ {+ "id": "",+ },+ {+ "id": "not-an-id",+ },+ {+ "id": graphene.Node.to_global_id("Car", "1"),+ },+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),+ },+ {+ "id": external_id,+ },+ ]+ }+ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway.com/apiv2/",+ )++ # when+ excluded_methods = _get_excluded_shipping_methods_from_response(response, webhook)++ # then+ assert len(excluded_methods) == 2+ assert excluded_methods[0].id == "2"+ assert excluded_methods[1].id == external_id+ # 2 warning for each invalid data+ # warning for malformed id+ assert mocked_schema_logger.call_count == 3+ # warning for skipping shipping method+ assert mocked_annotations_logger.call_count == 3++[email protected](annotations_logger, "warning")[email protected](schema_logger, "warning")+def test_parse_excluded_shipping_methods_response_invalid(+ mocked_schema_logger, mocked_annotations_logger, app+):+ # given+ response = {+ "excluded_methods": [+ {+ "id": "not-an-id",+ },+ ]+ }+ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway.com/apiv2/",+ )++ # when+ excluded_methods = _get_excluded_shipping_methods_from_response(response, webhook)++ # then+ assert not excluded_methods+ assert mocked_schema_logger.call_count == 1+ assert (+ "Malformed ShippingMethod id was provided:"+ in mocked_schema_logger.call_args[0][0]+ )+ assert mocked_annotations_logger.call_count == 1+ error_msg = mocked_annotations_logger.call_args[0][1]+ assert "Skipping invalid shipping method (FilterShippingMethodsSchema)" in error_msg++[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+def test_excluded_shipping_methods_for_checkout(+ mocked_webhook,+ checkout_with_items,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,+):+ # given+ webhook_reason = "Order contains dangerous products."++ mocked_webhook.return_value = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }++ # when+ excluded_methods = excluded_shipping_methods_for_checkout(+ checkout_with_items,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )++ # then+ assert len(excluded_methods) == 1+ em = excluded_methods[0]+ assert em.id == "1"+ assert webhook_reason in em.reason+ mocked_webhook.assert_called_once()diff --git a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py b/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.pysimilarity index 66%rename from saleor/plugins/webhook/tests/test_shipping_exclude_cache.pyrename to saleor/checkout/tests/webhooks/test_exclude_shipping_cache.pyindex eae4c7b133..28bdb46e8b 100644--- a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py+++ b/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py@@ -1,35 +1,58 @@import json+import uuid+from decimal import Decimalfrom unittest import mockimport graphene+import pytest+from measurement.measures import Weight+from prices import Money-from ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIME+from ....shipping.interface import ShippingMethodDatafrom ....webhook.event_types import WebhookEventSyncTypefrom ....webhook.transport.utils import generate_cache_key_for_webhook-from ...base_plugin import ExcludedShippingMethod+from ...webhooks.exclude_shipping import (+ CACHE_EXCLUDED_SHIPPING_TIME,+ excluded_shipping_methods_for_checkout,+)+++def available_shipping_methods():+ methods = []+ for i in range(2):+ methods.append(+ ShippingMethodData(+ id=str(i),+ price=Money(Decimal(10), "usd"),+ name=uuid.uuid4().hex,+ maximum_order_weight=Weight(kg=0),+ minimum_order_weight=Weight(kg=0),+ maximum_delivery_days=0,+ minimum_delivery_days=5,+ )+ )+ return methods@mock.patch("saleor.webhook.transport.synchronous.transport.cache.get")@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")@mock.patch(- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload")def test_excluded_shipping_methods_for_checkout_use_cache(mocked_payload,mocked_webhook,mocked_cache_set,mocked_cache_get,- webhook_plugin,checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,):# given- shipping_app_factory()webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."mocked_webhook.return_value = {"excluded_methods": [@@ -45,18 +68,12 @@ def test_excluded_shipping_methods_for_checkout_use_cache(mocked_cache_get.return_value = (payload, [{"id": "1", "reason": webhook_reason}])- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-# when- plugin.excluded_shipping_methods_for_checkout(+ excluded_shipping_methods_for_checkout(checkout_with_items,available_shipping_methods=available_shipping_methods,- previous_value=previous_value,+ allow_replica=True,+ requestor=None,)# then@@ -69,25 +86,22 @@ def test_excluded_shipping_methods_for_checkout_use_cache(@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")@mock.patch(- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload")def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(mocked_payload,mocked_webhook,mocked_cache_set,mocked_cache_get,- webhook_plugin,checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,):# given- shipping_app = shipping_app_factory()- shipping_webhook = shipping_app.webhooks.get()+ shipping_webhook = app_exclude_shipping_for_checkout.webhooks.get()webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."webhook_response = {"excluded_methods": [@@ -105,18 +119,12 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(mocked_cache_get.return_value = None- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-# when- plugin.excluded_shipping_methods_for_checkout(+ excluded_shipping_methods_for_checkout(checkout_with_items,available_shipping_methods=available_shipping_methods,- previous_value=previous_value,+ allow_replica=True,+ requestor=None,)# then@@ -126,7 +134,7 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(payload_dict,shipping_webhook.target_url,WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- shipping_app.id,+ app_exclude_shipping_for_checkout.id,)mocked_cache_set.assert_called_once_with(@@ -140,25 +148,23 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")@mock.patch(- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"+ "saleor.checkout.webhooks.exclude_shipping."+ "_generate_excluded_shipping_methods_for_checkout_payload")def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_different(mocked_payload,mocked_webhook,mocked_cache_set,mocked_cache_get,- webhook_plugin,checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,+ available_shipping_methods,+ app_exclude_shipping_for_checkout,):# given- shipping_app = shipping_app_factory()- shipping_webhook = shipping_app.webhooks.get()++ shipping_webhook = app_exclude_shipping_for_checkout.webhooks.get()webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."webhook_response = {"excluded_methods": [@@ -177,17 +183,12 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_difmocked_cache_get.return_value = None- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]# when- plugin.excluded_shipping_methods_for_checkout(+ excluded_shipping_methods_for_checkout(checkout_with_items,available_shipping_methods=available_shipping_methods,- previous_value=previous_value,+ allow_replica=True,+ requestor=None,)# thenassert mocked_webhook.called@@ -196,7 +197,7 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_difpayload_dict,shipping_webhook.target_url,WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- shipping_app.id,+ app_exclude_shipping_for_checkout.id,)mocked_cache_get.assert_called_once_with(expected_cache_key)diff --git a/saleor/checkout/webhooks/__init__.py b/saleor/checkout/webhooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/checkout/webhooks/exclude_shipping.py b/saleor/checkout/webhooks/exclude_shipping.pynew file mode 100644index 0000000000..22739d36bd--- /dev/null+++ b/saleor/checkout/webhooks/exclude_shipping.py@@ -0,0 +1,231 @@+import json+import logging+from collections import defaultdict+from collections.abc import Callable+from typing import TYPE_CHECKING, Union++from django.conf import settings+from django.db.models import QuerySet+from pydantic import ValidationError++from ...app.models import App+from ...core.db.connection import allow_writer+from ...core.utils.json_serializer import CustomJsonEncoder+from ...graphql.webhook.utils import get_pregenerated_subscription_payload+from ...shipping.interface import ExcludedShippingMethod, ShippingMethodData+from ...webhook import traced_payload_generator+from ...webhook.event_types import WebhookEventSyncType+from ...webhook.models import Webhook+from ...webhook.payloads import (+ generate_checkout_payload,+)+from ...webhook.response_schemas.shipping import (+ ExcludedShippingMethodSchema,+ FilterShippingMethodsSchema,+)+from ...webhook.transport.synchronous.transport import (+ trigger_webhook_sync_if_not_cached,+)+from ...webhook.utils import get_webhooks_for_event+from ..models import Checkout++if TYPE_CHECKING:+ from ...account.models import User+ from ...app.models import App++logger = logging.getLogger(__name__)++CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3+++def excluded_shipping_methods_for_checkout(+ checkout: "Checkout",+ available_shipping_methods: list["ShippingMethodData"],+ allow_replica: bool,+ requestor: Union["App", "User", None],+ pregenerated_subscription_payloads: dict | None = None,+) -> list[ExcludedShippingMethod]:+ if pregenerated_subscription_payloads is None:+ pregenerated_subscription_payloads = {}+ if not available_shipping_methods:+ return []++ generate_function = _generate_excluded_shipping_methods_for_checkout_payload+ payload_function = lambda: generate_function( # noqa: E731+ checkout,+ available_shipping_methods,+ )+ return _get_excluded_shipping_data(+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ payload_fun=payload_function,+ subscribable_object=(checkout, available_shipping_methods),+ allow_replica=allow_replica,+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,+ requestor=requestor,+ )+++def _generate_payload_for_shipping_method(method: ShippingMethodData):+ payload = {+ "id": method.graphql_id,+ "price": method.price.amount,+ "currency": method.price.currency,+ "name": method.name,+ "maximum_order_weight": method.maximum_order_weight,+ "minimum_order_weight": method.minimum_order_weight,+ "maximum_delivery_days": method.maximum_delivery_days,+ "minimum_delivery_days": method.minimum_delivery_days,+ }+ return payload+++@allow_writer()+@traced_payload_generator+def _generate_excluded_shipping_methods_for_checkout_payload(+ checkout: "Checkout",+ available_shipping_methods: list[ShippingMethodData],+):+ checkout_data = json.loads(generate_checkout_payload(checkout))[0]+ payload = {+ "checkout": checkout_data,+ "shipping_methods": [+ _generate_payload_for_shipping_method(shipping_method)+ for shipping_method in available_shipping_methods+ ],+ }+ return json.dumps(payload, cls=CustomJsonEncoder)+++def _get_excluded_shipping_data(+ event_type: str,+ payload_fun: Callable[[], str],+ subscribable_object: tuple["Checkout", list["ShippingMethodData"]],+ allow_replica: bool,+ requestor: Union["App", "User", None],+ pregenerated_subscription_payloads: dict | None = None,+) -> list[ExcludedShippingMethod]:+ """Exclude not allowed shipping methods by sync webhook.++ Fetch excluded shipping methods from sync webhooks and return them as a list of+ excluded shipping methods.+ The function uses a cache_key to reduce the number of+ requests which we call to the external APIs. In case when we have the same payload+ in a cache as we're going to send now, we will skip an additional request and use+ the response fetched from cache.+ The function will fetch the payload only in the case that we have any defined+ webhook.+ """+ if pregenerated_subscription_payloads is None:+ pregenerated_subscription_payloads = {}+ excluded_methods_map: dict[str, list[ExcludedShippingMethod]] = defaultdict(list)+ webhooks = get_webhooks_for_event(event_type)+ if webhooks:+ payload = payload_fun()++ excluded_methods_map = _get_excluded_shipping_methods_or_fetch(+ webhooks,+ event_type,+ payload,+ subscribable_object,+ allow_replica,+ requestor,+ pregenerated_subscription_payloads,+ )++ # Return a list of excluded methods, unique by id+ excluded_methods = []+ for method_id, methods in excluded_methods_map.items():+ reason = None+ if reasons := [m.reason for m in methods if m.reason]:+ reason = " ".join(reasons)+ excluded_methods.append(ExcludedShippingMethod(id=method_id, reason=reason))+ return excluded_methods+++def _get_excluded_shipping_methods_or_fetch(+ webhooks: QuerySet,+ event_type: str,+ payload: str,+ subscribable_object: tuple["Checkout", list["ShippingMethodData"]],+ allow_replica: bool,+ requestor: Union["App", "User", None],+ pregenerated_subscription_payloads: dict | None = None,+) -> 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.+ """+ if pregenerated_subscription_payloads is None:+ pregenerated_subscription_payloads = {}+ cache_data = _get_cache_data_for_exclude_shipping_methods(payload)+ excluded_methods: list[ExcludedShippingMethodSchema] = []+ # Gather responses from webhooks+ for webhook in webhooks:+ pregenerated_subscription_payload = get_pregenerated_subscription_payload(+ webhook, pregenerated_subscription_payloads+ )+ 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,+ request_timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ cache_timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ requestor=requestor,+ pregenerated_subscription_payload=pregenerated_subscription_payload,+ )+ if response_data and isinstance(response_data, dict):+ excluded_methods.extend(+ _get_excluded_shipping_methods_from_response(response_data, webhook)+ )+ return _parse_excluded_shipping_methods(excluded_methods)+++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)+ source_object.pop("shipping_method", None)+ return payload_dict+++def _parse_excluded_shipping_methods(+ excluded_methods: list[ExcludedShippingMethodSchema],+) -> dict[str, list[ExcludedShippingMethod]]:+ """Prepare method_id to excluded methods map."""+ excluded_methods_map = defaultdict(list)+ for excluded_method in excluded_methods:+ method_id = excluded_method.id+ reason = excluded_method.reason or ""+ excluded_methods_map[method_id].append(+ ExcludedShippingMethod(id=method_id, reason=reason)+ )+ return excluded_methods_map+++def _get_excluded_shipping_methods_from_response(+ response_data: dict,+ webhook: "Webhook",+) -> list[ExcludedShippingMethodSchema]:+ excluded_methods = []+ try:+ filter_methods_schema = FilterShippingMethodsSchema.model_validate(+ response_data,+ context={+ "custom_message": "Skipping invalid shipping method (FilterShippingMethodsSchema)"+ },+ )+ excluded_methods.extend(filter_methods_schema.excluded_methods)+ except ValidationError:+ logger.warning(+ "Skipping invalid response from app %s: %s",+ str(webhook.app.identifier),+ response_data,+ )+ return excluded_methodsdiff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 4e12420ec9..a7d4ef9c39 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -569,7 +569,7 @@ def test_create_checkout_with_order_promotion(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(105):+ with django_assert_num_queries(106):response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)# thendiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.pyindex 567bbf5059..1b66ab58cb 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@@ -20,9 +20,9 @@ from .....checkout.fetch import (from .....checkout.models import CheckoutDeliveryfrom .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkoutfrom .....core.models import EventDelivery-from .....plugins.base_plugin import ExcludedShippingMethodfrom .....plugins.manager import get_plugins_managerfrom .....shipping import models as shipping_models+from .....shipping.interface import ExcludedShippingMethodfrom .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_content@@ -273,7 +273,7 @@ def test_checkout_shipping_method_update_deletes_external_shipping_when_not_vali@mock.patch(- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout")def test_checkout_shipping_method_update_excluded_webhook(mocked_webhook,diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 2e497d85ed..926624ffd6 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -458,10 +458,7 @@ query getCheckout($id: ID) {"""- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_checkout"-)-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.checkout.webhooks.exclude_shipping._get_excluded_shipping_data")def test_query_checkout_empty_address_with_shipping_method_without_exclude_webhook(mock_excluded_shipping_methods_for_checkout,api_client,@@ -489,7 +486,7 @@ def test_query_checkout_empty_address_with_shipping_method_without_exclude_webho@mock.patch(- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_checkout"+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout")@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])def test_query_checkout_with_address_with_shipping_method_without_exclude_webhook(diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex e925286bca..c907b391a7 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -29,9 +29,9 @@ from .....order.interface import OrderTaxedPricesDatafrom .....order.models import OrderEvent, OrderLinefrom .....payment.model_helpers import get_subtotalfrom .....plugins import PLUGIN_IDENTIFIER_PREFIX-from .....plugins.base_plugin import ExcludedShippingMethodfrom .....plugins.tests.sample_plugins import PluginSamplefrom .....product.models import ProductVariant+from .....shipping.interface import ExcludedShippingMethodfrom .....tests import race_conditionfrom .....warehouse.models import Allocation, PreorderAllocation, Stockfrom .....warehouse.tests.utils import get_available_quantity_for_stockdiff --git a/saleor/order/delivery_context.py b/saleor/order/delivery_context.pyindex 89735e9b45..99e6f35aaf 100644--- a/saleor/order/delivery_context.py+++ b/saleor/order/delivery_context.py@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Unionfrom django.conf import settingsfrom promise import Promise-from ..shipping.interface import ShippingMethodData+from ..shipping.interface import ExcludedShippingMethod, ShippingMethodDatafrom ..shipping.models import ShippingMethod, ShippingMethodChannelListingfrom ..shipping.utils import (convert_to_shipping_method_data,@@ -81,7 +81,6 @@ def get_valid_shipping_methods_for_order(# and their usage in webhook/transport layer. Until moving them out from the# transport, we will have circular imports.from .webhooks.exclude_shipping import (- ExcludedShippingMethod,excluded_shipping_methods_for_order,)diff --git a/saleor/order/tests/webhooks/test_exclude_shipping.py b/saleor/order/tests/webhooks/test_exclude_shipping.pyindex d13f416d24..81f0677de1 100644--- a/saleor/order/tests/webhooks/test_exclude_shipping.py+++ b/saleor/order/tests/webhooks/test_exclude_shipping.py@@ -12,12 +12,12 @@ from promise import Promisefrom ....core.prices import quantize_pricefrom ....shipping.interface import ShippingMethodData-from ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIMEfrom ....webhook.event_types import WebhookEventSyncTypefrom ....webhook.models import Webhookfrom ....webhook.transport.shipping_helpers import to_shipping_app_idfrom ....webhook.transport.utils import generate_cache_key_for_webhookfrom ...webhooks.exclude_shipping import (+ CACHE_EXCLUDED_SHIPPING_TIME,_get_excluded_shipping_methods_from_response,excluded_shipping_methods_for_order,generate_excluded_shipping_methods_for_order_payload,diff --git a/saleor/order/webhooks/exclude_shipping.py b/saleor/order/webhooks/exclude_shipping.pyindex 0eeb13b53e..b4efb7c9bc 100644--- a/saleor/order/webhooks/exclude_shipping.py+++ b/saleor/order/webhooks/exclude_shipping.py@@ -1,7 +1,6 @@import jsonimport loggingfrom collections import defaultdict-from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Unionfrom django.conf import settings@@ -12,13 +11,12 @@ from pydantic import ValidationErrorfrom ...core.db.connection import allow_writerfrom ...core.prices import quantize_pricefrom ...core.utils.json_serializer import CustomJsonEncoder-from ...shipping.interface import ShippingMethodData+from ...shipping.interface import ExcludedShippingMethod, ShippingMethodDatafrom ...webhook import traced_payload_generatorfrom ...webhook.event_types import WebhookEventSyncTypefrom ...webhook.models import Webhookfrom ...webhook.payloads import (generate_order_payload,- generate_payload_for_shipping_method,)from ...webhook.response_schemas.shipping import (ExcludedShippingMethodSchema,@@ -39,10 +37,18 @@ CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3logger = logging.getLogger(__name__)-@dataclass-class ExcludedShippingMethod:- id: str- reason: str | None+def generate_payload_for_shipping_method(method: ShippingMethodData):+ payload = {+ "id": method.graphql_id,+ "price": method.price.amount,+ "currency": method.price.currency,+ "name": method.name,+ "maximum_order_weight": method.maximum_order_weight,+ "minimum_order_weight": method.minimum_order_weight,+ "maximum_delivery_days": method.maximum_delivery_days,+ "minimum_delivery_days": method.minimum_delivery_days,+ }+ return payload@allow_writer()diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 74853c98eb..5bf52ae26f 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -98,12 +98,6 @@ class ExternalAccessTokens:user: Optional["User"] = None-@dataclass-class ExcludedShippingMethod:- id: str- reason: str | None--class BasePlugin:"""Abstract class for storing all methods available for any plugin.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 19f74ed366..f9d14092bd 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -49,7 +49,7 @@ from ..payment.interface import (TransactionSessionResult,)from ..tax.utils import calculate_tax_rate-from .base_plugin import ExcludedShippingMethod, ExternalAccessTokens+from .base_plugin import ExternalAccessTokensfrom .models import PluginConfigurationif TYPE_CHECKING:@@ -2865,28 +2865,6 @@ class PluginsManager(PaymentInterface):plugin, "external_verify", default_value, data, request)- def excluded_shipping_methods_for_checkout(- self,- checkout: "Checkout",- channel: "Channel",- available_shipping_methods: list["ShippingMethodData"],- pregenerated_subscription_payloads: dict | None = None,- ) -> list[ExcludedShippingMethod]:- default_value: list[ExcludedShippingMethod] = []-- if not available_shipping_methods:- return default_value- if pregenerated_subscription_payloads is None:- pregenerated_subscription_payloads = {}- return self.__run_method_on_plugins(- "excluded_shipping_methods_for_checkout",- default_value,- checkout,- available_shipping_methods,- pregenerated_subscription_payloads=pregenerated_subscription_payloads,- channel_slug=channel.slug,- )-def is_event_active_for_any_plugin(self, event: str, channel_slug: str | None = None) -> bool:diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex ac4778cbbf..8741cb60af 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -41,7 +41,6 @@ from ...payment.interface import (TransactionSessionResult,)from ...product.models import Product-from ...shipping.interface import ShippingMethodDatafrom ..base_plugin import ExternalAccessTokensfrom ..manager import PluginsManager, get_plugins_managerfrom ..models import PluginConfiguration@@ -1646,62 +1645,3 @@ def test_manager_skips_external_shipping_with_different_currency_than_checkout_c# thenassert len(shipping_methods) == 1assert shipping_methods[0].price.currency == checkout_with_item.currency--- "saleor.plugins.manager.PluginsManager._PluginsManager__run_method_on_plugins"-)-def test_excluded_shipping_methods_for_checkout_run_webhook_on_existing_shipping_methods(- mock__run_method_on_plugins, channel_USD, checkout-):- plugins = [- "saleor.plugins.tests.sample_plugins.PluginSample",- ]-- manager = PluginsManager(plugins=plugins)-- # given shipping methods contain at least 1 method-- shipping_method = ShippingMethodData(- id="123",- price=Money(Decimal("10.59"), "USD"),- )-- non_empty_shipping_methods = [shipping_method]-- # when manager executes for shipping methods exclusion-- manager.excluded_shipping_methods_for_checkout(- checkout, channel_USD, non_empty_shipping_methods- )-- # then webhook should be emitted-- mock__run_method_on_plugins.assert_called_once()--- "saleor.plugins.manager.PluginsManager._PluginsManager__run_method_on_plugins"-)-def test_excluded_shipping_methods_for_checkout_dont_run_webhook_on_missing_shipping_methods(- mock__run_method_on_plugins, channel_USD, checkout-):- plugins = [- "saleor.plugins.tests.sample_plugins.PluginSample",- ]-- manager = PluginsManager(plugins=plugins)-- # given shipping methods are empty-- empty_shipping_methods = []-- # when manager executes for shipping methods exclusion-- manager.excluded_shipping_methods_for_checkout(- checkout, channel_USD, empty_shipping_methods- )-- # then webhook should not be emitted-- mock__run_method_on_plugins.assert_not_called()diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex d642d9deb9..f3d08f8ca5 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -69,7 +69,6 @@ from ...webhook.payloads import (generate_checkout_payload_for_tax_calculation,generate_collection_payload,generate_customer_payload,- generate_excluded_shipping_methods_for_checkout_payload,generate_fulfillment_payload,generate_invoice_payload,generate_list_gateways_payload,@@ -114,7 +113,6 @@ from ...webhook.transport.payment import ()from ...webhook.transport.shipping import (get_cache_data_for_shipping_list_methods_for_checkout,- get_excluded_shipping_data,parse_list_shipping_methods_response,)from ...webhook.transport.synchronous.transport import (@@ -131,7 +129,7 @@ from ...webhook.transport.utils import (get_sqs_message_group_id,)from ...webhook.utils import get_webhooks_for_event-from ..base_plugin import BasePlugin, ExcludedShippingMethod+from ..base_plugin import BasePluginif TYPE_CHECKING:from ...account.models import Address, Group, User@@ -3664,29 +3662,6 @@ class WebhookPlugin(BasePlugin):description=description,)- def excluded_shipping_methods_for_checkout(- self,- checkout: "Checkout",- available_shipping_methods: list["ShippingMethodData"],- previous_value: list[ExcludedShippingMethod],- pregenerated_subscription_payloads: dict | None = None,- ) -> list[ExcludedShippingMethod]:- if pregenerated_subscription_payloads is None:- pregenerated_subscription_payloads = {}- generate_function = generate_excluded_shipping_methods_for_checkout_payload- payload_function = lambda: generate_function( # noqa: E731- checkout,- available_shipping_methods,- )- return get_excluded_shipping_data(- event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- previous_value=previous_value,- payload_fun=payload_function,- subscribable_object=(checkout, available_shipping_methods),- allow_replica=self.allow_replica,- pregenerated_subscription_payloads=pregenerated_subscription_payloads,- )-def is_event_active(self, event: str, channel: str | None = None):map_event = {"invoice_request": WebhookEventAsyncType.INVOICE_REQUESTED,diff --git a/saleor/plugins/webhook/tests/conftest.py b/saleor/plugins/webhook/tests/conftest.pyindex c5ad4e161a..e9048181dd 100644--- a/saleor/plugins/webhook/tests/conftest.py+++ b/saleor/plugins/webhook/tests/conftest.py@@ -1,16 +1,7 @@-import uuid-from decimal import Decimal-import pytest-from measurement.measures import Weight-from prices import Money-from ....app.models import Appfrom ....plugins.manager import get_plugins_managerfrom ....plugins.webhook.plugin import WebhookPlugin-from ....shipping.interface import ShippingMethodData-from ....webhook.event_types import WebhookEventSyncType-from ....webhook.models import Webhook, WebhookEvent@pytest.fixture@@ -22,54 +13,3 @@ def webhook_plugin(settings):return manager.global_plugins[0]return factory---def available_shipping_methods_factory():- def factory(num_methods=1) -> list[ShippingMethodData]:- methods = []- for i in range(num_methods):- methods.append(- ShippingMethodData(- id=str(i),- price=Money(Decimal(10), "usd"),- name=uuid.uuid4().hex,- maximum_order_weight=Weight(kg=0),- minimum_order_weight=Weight(kg=0),- maximum_delivery_days=0,- minimum_delivery_days=5,- )- )- return methods-- return factory---def shipping_app_factory(db, permission_manage_orders, permission_manage_checkouts):- def create_app(app_name="Shipping App"):- app = App.objects.create(name=app_name, is_active=True)- app.tokens.create(name="Default")- app.permissions.add(permission_manage_orders)- app.permissions.add(permission_manage_checkouts)-- webhook = Webhook.objects.create(- name="shipping-webhook-1",- app=app,- target_url="https://shipping-gateway.com/api/",- )- webhook.events.bulk_create(- [- WebhookEvent(- event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- webhook=webhook,- ),- WebhookEvent(- event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- webhook=webhook,- ),- ]- )- return app-- return create_appdiff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex cf2e55de97..d84bd2a9d8 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -1,233 +1,12 @@-import jsonfrom unittest import mock-from unittest.mock import call--import graphenefrom ....core.models import EventDelivery-from ....graphql.core.utils import to_global_id_or_none-from ....graphql.tests.utils import get_graphql_content-from ....graphql.webhook.utils import get_subscription_query_hash-from ....shipping.models import ShippingMethod-from ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIMEfrom ....webhook.event_types import WebhookEventSyncType-from ....webhook.models import Webhook-from ....webhook.payloads import (- generate_excluded_shipping_methods_for_checkout_payload,-)-from ....webhook.response_schemas.shipping import logger as schema_loggerfrom ....webhook.response_schemas.utils.annotations import logger as annotations_loggerfrom ....webhook.transport.shipping import (- get_excluded_shipping_methods_from_response,- get_excluded_shipping_methods_or_fetch,parse_list_shipping_methods_response,)-from ....webhook.transport.shipping_helpers import to_shipping_app_idfrom ....webhook.transport.synchronous.transport import trigger_webhook_sync-from ....webhook.transport.utils import generate_cache_key_for_webhook-from ...base_plugin import ExcludedShippingMethod--CHECKOUT_QUERY_SHIPPING_METHOD = """-query Checkout($id: ID){- checkout(id: $id) {- shippingMethods {- id- name- active- }- availableShippingMethods {- id- name- active- }- }-}-"""--[email protected](annotations_logger, "warning")[email protected](schema_logger, "warning")-def test_parse_excluded_shipping_methods_response(- mocked_schema_logger, mocked_annotations_logger, app-):- # given- external_id = to_shipping_app_id(app, "test-1234")- response = {- "excluded_methods": [- {- "id": "",- },- {- "id": "not-an-id",- },- {- "id": graphene.Node.to_global_id("Car", "1"),- },- {- "id": graphene.Node.to_global_id("ShippingMethod", "2"),- },- {- "id": external_id,- },- ]- }- webhook = Webhook.objects.create(- name="shipping-webhook-1",- app=app,- target_url="https://shipping-gateway.com/apiv2/",- )-- # when- excluded_methods = get_excluded_shipping_methods_from_response(response, webhook)-- # then- assert len(excluded_methods) == 2- assert excluded_methods[0].id == "2"- assert excluded_methods[1].id == external_id- # 2 warning for each invalid data- # warning for malformed id- assert mocked_schema_logger.call_count == 3- # warning for skipping shipping method- assert mocked_annotations_logger.call_count == 3--[email protected](annotations_logger, "warning")[email protected](schema_logger, "warning")-def test_parse_excluded_shipping_methods_response_invalid(- mocked_schema_logger, mocked_annotations_logger, app-):- # given- response = {- "excluded_methods": [- {- "id": "not-an-id",- },- ]- }- webhook = Webhook.objects.create(- name="shipping-webhook-1",- app=app,- target_url="https://shipping-gateway.com/apiv2/",- )-- # when- excluded_methods = get_excluded_shipping_methods_from_response(response, webhook)-- # then- assert not excluded_methods- assert mocked_schema_logger.call_count == 1- assert (- "Malformed ShippingMethod id was provided:"- in mocked_schema_logger.call_args[0][0]- )- assert mocked_annotations_logger.call_count == 1- error_msg = mocked_annotations_logger.call_args[0][1]- assert "Skipping invalid shipping method (FilterShippingMethodsSchema)" in error_msg--- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_checkout"-)-def test_checkout_deliveries(- mocked_webhook,- staff_api_client,- checkout_ready_to_complete,- permission_manage_checkouts,- settings,- shipping_method_weight_based,-):- # given- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- webhook_reason = "spanish-inquisition"- excluded_shipping_method_id = (- checkout_ready_to_complete.assigned_delivery.shipping_method_id- )- mocked_webhook.return_value = [- ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)- ]- staff_api_client.user.user_permissions.add(permission_manage_checkouts)- # when- response = staff_api_client.post_graphql(- CHECKOUT_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(checkout_ready_to_complete)},- )- content = get_graphql_content(response)- checkout_data = content["data"]["checkout"]-- shipping_methods = checkout_data["shippingMethods"]- # then- assert len(shipping_methods) == 2- inactive_method = list(- filter(- lambda s: s["id"]- == graphene.Node.to_global_id(- "ShippingMethod", excluded_shipping_method_id- ),- shipping_methods,- )- )- assert not inactive_method[0]["active"]--- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"-)-def test_checkout_available_shipping_methods(- mocked_webhook,- staff_api_client,- checkout_ready_to_complete,- permission_manage_checkouts,- settings,- shipping_method_weight_based,-):- # given- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- webhook_reason = "spanish-inquisition"-- excluded_shipping_method_id = (- checkout_ready_to_complete.assigned_delivery.shipping_method_id- )- mocked_webhook.return_value = [- ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)- ]-- staff_api_client.user.user_permissions.add(permission_manage_checkouts)- # when- response = staff_api_client.post_graphql(- CHECKOUT_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(checkout_ready_to_complete)},- )- content = get_graphql_content(response)- shipping_methods = content["data"]["checkout"]["availableShippingMethods"]- # then- assert len(shipping_methods) == 1- assert shipping_methods[0]["active"]--- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"-)-def test_checkout_deliveries_webhook_called_once(- mocked_webhook,- staff_api_client,- checkout_ready_to_complete,- permission_manage_checkouts,-):- # given- mocked_webhook.side_effect = [[], AssertionError("called twice.")]- staff_api_client.user.user_permissions.add(permission_manage_checkouts)- # when- response = staff_api_client.post_graphql(- CHECKOUT_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(checkout_ready_to_complete)},- )- content = get_graphql_content(response)- checkout_data = content["data"]["checkout"]- # then- expected_count = ShippingMethod.objects.count()- assert len(checkout_data["availableShippingMethods"]) == expected_count- assert len(checkout_data["shippingMethods"]) == expected_count- assert mocked_webhook.called@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")@@ -241,531 +20,6 @@ def test_trigger_webhook_sync(mock_request, shipping_app):assert not EventDelivery.objects.exists()[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"-)-def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_payload(- mocked_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,- settings,-):- # 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."-- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }-- 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 = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]- # when- excluded_methods = plugin.excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert other_reason in em.reason-- mocked_webhook.assert_called_once_with(- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- payload,- shipping_webhook,- False,- subscribable_object=(checkout_with_items, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- 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,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"-)- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"-)-def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_pregenerated_payload(- mocked_subscription_payload,- mocked_static_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- checkout_with_items,- available_shipping_methods_factory,- exclude_shipping_app_with_subscription,- settings,-):- # given- shipping_app = exclude_shipping_app_with_subscription- shipping_webhook = shipping_app.webhooks.get()- webhook_reason = "Checkout contains dangerous products."- other_reason = "Shipping is not applicable for this checkout."-- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }-- mocked_webhook.return_value = webhook_response-- payload_dict = {"checkout": {"id": 1, "some_field": "12"}}- query_hash = get_subscription_query_hash(shipping_webhook.subscription_query)- pregenerated_payloads = {shipping_app.id: {query_hash: payload_dict}}- payload = json.dumps(payload_dict)- mocked_static_payload.return_value = payload-- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]- # when- excluded_methods = plugin.excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- pregenerated_subscription_payloads=pregenerated_payloads,- )- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert other_reason in em.reason-- mocked_webhook.assert_called_once_with(- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- payload,- shipping_webhook,- False,- subscribable_object=(checkout_with_items, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=payload_dict,- )- 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,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )- mocked_subscription_payload.assert_not_called()--[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_excluded_shipping_methods_for_checkout(- mocked_webhook,- webhook_plugin,- checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,-):- # given- shipping_app_factory()- webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."-- mocked_webhook.return_value = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }-- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-- # when- excluded_methods = plugin.excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )-- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert other_reason in em.reason- mocked_webhook.assert_called_once()--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"-)-def test_multiple_app_with_excluded_shipping_methods_for_checkout(- mocked_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,- settings,-):- # 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."-- 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 = []-- # when- excluded_methods = plugin.excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )-- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert webhook_second_reason in em.reason- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS- mocked_webhook.assert_any_call(- event_type,- payload,- shipping_webhook,- False,- subscribable_object=(checkout_with_items, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- mocked_webhook.assert_any_call(- event_type,- payload,- second_shipping_webhook,- False,- subscribable_object=(checkout_with_items, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- assert mocked_webhook.call_count == 2-- 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,- )-- 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,- ),- ]- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.plugins.webhook.plugin."- "generate_excluded_shipping_methods_for_checkout_payload"-)-def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_checkout(- mocked_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- checkout_with_items,- available_shipping_methods_factory,- shipping_app_factory,- settings,-):- # 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/apiv2/",- )- second_webhook.events.create(- event_type=event_type,- webhook=second_webhook,- )-- webhook_reason = "Checkout contains dangerous products."- webhook_second_reason = "Shipping is not applicable for this checkout."-- 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 = []-- # when- excluded_methods = plugin.excluded_shipping_methods_for_checkout(- checkout=checkout_with_items,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )-- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert webhook_second_reason in em.reason-- mocked_webhook.assert_any_call(- event_type,- payload,- first_webhook,- False,- subscribable_object=(checkout_with_items, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- mocked_webhook.assert_any_call(- event_type,- payload,- second_webhook,- False,- subscribable_object=(checkout_with_items, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- assert mocked_webhook.call_count == 2-- 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,- ),- ]- )---def test_generate_excluded_shipping_methods_for_checkout_payload(- webhook_plugin,- checkout_with_items,- available_shipping_methods_factory,-):- # given- methods = available_shipping_methods_factory(num_methods=3)-- # when- json_payload = json.loads(- generate_excluded_shipping_methods_for_checkout_payload(- checkout_with_items, available_shipping_methods=methods- )- )- # then- assert len(json_payload["shipping_methods"]) == 3- assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(- "ShippingMethod", methods[0].id- )- assert json_payload["shipping_methods"][1]["id"] == graphene.Node.to_global_id(- "ShippingMethod", methods[1].id- )- assert json_payload["shipping_methods"][2]["id"] == graphene.Node.to_global_id(- "ShippingMethod", methods[2].id- )- assert "checkout" in json_payload- assert "channel" in json_payload["checkout"]--[email protected]("saleor.webhook.transport.shipping.parse_excluded_shipping_methods")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.webhook.transport.shipping.get_excluded_shipping_methods_from_response"-)-def test_get_excluded_shipping_methods_or_fetch_invalid_response_type(- mocked_get_excluded,- mocked_webhook_sync_trigger,- mocked_parse,- app,- checkout,-):- # given- mocked_webhook_sync_trigger.return_value = ["incorrect_type"]- webhook = Webhook.objects.create(- name="Simple webhook", app=app, target_url="http://www.example.com/test"- )- event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS- webhook.events.create(event_type=event_type)- webhooks = Webhook.objects.all()-- # when- get_excluded_shipping_methods_or_fetch(- webhooks, event_type, '{"test":"payload"}', checkout, False, None- )- # then- mocked_get_excluded.asssert_not_called()- mocked_parse.assert_called_once_with([])--@mock.patch.object(annotations_logger, "warning")def test_parse_list_shipping_methods_response_response_incorrect_format(mocked_logger, appdiff --git a/saleor/shipping/interface.py b/saleor/shipping/interface.pyindex 8dc71ed28f..364cdc136d 100644--- a/saleor/shipping/interface.py+++ b/saleor/shipping/interface.py@@ -51,3 +51,9 @@ class ShippingMethodData:if self.is_external:return self.idreturn graphene.Node.to_global_id("ShippingMethod", self.id)+++@dataclass+class ExcludedShippingMethod:+ id: str+ reason: str | Nonediff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex 2b20b70b20..31c7ba8c04 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -6,7 +6,7 @@ from prices import Moneyfrom ..checkout.models import Checkout, CheckoutDeliveryfrom ..core.db.connection import allow_writer-from ..plugins.base_plugin import ExcludedShippingMethod+from ..shipping.interface import ExcludedShippingMethodfrom ..tax.models import TaxClassfrom .interface import ShippingMethodDatadiff --git a/saleor/webhook/const.py b/saleor/webhook/const.pyindex 3abb50aa40..d136b4c4c1 100644--- a/saleor/webhook/const.py+++ b/saleor/webhook/const.py@@ -1,4 +1,3 @@-CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3WEBHOOK_CACHE_DEFAULT_TTL: int = 5 * 60 # 5 minutesSYNC_WEBHOOK_FAILURE_CACHE_TTL: int = 1 # 1 secondSYNC_WEBHOOK_FAILURE_SENTINEL = (diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 4e1d2f8e79..64d3dee8b6 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -35,7 +35,6 @@ from ..payment import ChargeStatusfrom ..payment.models import Payment, TransactionItemfrom ..product import ProductMediaTypesfrom ..product.models import Collection, Product, ProductMedia, ProductVariant-from ..shipping.interface import ShippingMethodDatafrom ..shipping.models import ShippingMethodfrom ..tax.models import TaxClassCountryRatefrom ..thumbnail.models import Thumbnail@@ -1243,37 +1242,6 @@ def generate_translation_payload(return json.dumps(translation_data)-def generate_payload_for_shipping_method(method: ShippingMethodData):- payload = {- "id": method.graphql_id,- "price": method.price.amount,- "currency": method.price.currency,- "name": method.name,- "maximum_order_weight": method.maximum_order_weight,- "minimum_order_weight": method.minimum_order_weight,- "maximum_delivery_days": method.maximum_delivery_days,- "minimum_delivery_days": method.minimum_delivery_days,- }- return payload---@allow_writer()-@traced_payload_generator-def generate_excluded_shipping_methods_for_checkout_payload(- checkout: "Checkout",- available_shipping_methods: list[ShippingMethodData],-):- checkout_data = json.loads(generate_checkout_payload(checkout))[0]- payload = {- "checkout": checkout_data,- "shipping_methods": [- generate_payload_for_shipping_method(shipping_method)- for shipping_method in available_shipping_methods- ],- }- return json.dumps(payload, cls=CustomJsonEncoder)--@allow_writer()@traced_payload_generatordef generate_checkout_payload_for_tax_calculation(diff --git a/saleor/webhook/tests/fixtures/subscription_webhooks.py b/saleor/webhook/tests/fixtures/subscription_webhooks.pyindex f430f84848..39c80dd701 100644--- a/saleor/webhook/tests/fixtures/subscription_webhooks.py+++ b/saleor/webhook/tests/fixtures/subscription_webhooks.py@@ -1301,14 +1301,6 @@ def subscription_payment_list_gateways_webhook(subscription_webhook):)-def subscription_checkout_filter_shipping_methods_webhook(subscription_webhook):- return subscription_webhook(- queries.CHECKOUT_FILTER_SHIPPING_METHODS,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- )--@pytest.fixturedef subscription_shipping_list_methods_for_checkout_webhook(subscription_webhook):return subscription_webhook(@@ -1317,36 +1309,6 @@ def subscription_shipping_list_methods_for_checkout_webhook(subscription_webhook)-def subscription_checkout_filter_shipping_method_webhook_with_shipping_methods(- subscription_webhook,-):- return subscription_webhook(- queries.CHECKOUT_FILTER_SHIPPING_METHODS_CIRCULAR_SHIPPING_METHODS,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- )---def subscription_checkout_filter_shipping_method_webhook_with_available_ship_methods(- subscription_webhook,-):- return subscription_webhook(- queries.CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_SHIPPING_METHODS,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- )---def subscription_checkout_filter_shipping_method_webhook_with_payment_gateways(- subscription_webhook,-):- return subscription_webhook(- queries.CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_PAYMENT_GATEWAYS,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- )--@pytest.fixturedef subscription_thumbnail_created_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/webhook/tests/subscription_webhooks/subscription_queries.pyindex 5e56f43595..1af3e13c58 100644--- a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py@@ -3084,23 +3084,6 @@ PAYMENT_LIST_GATEWAYS = """"""-CHECKOUT_FILTER_SHIPPING_METHODS = """-subscription{- event{- ...on CheckoutFilterShippingMethods{- checkout{- id- }- shippingMethods{- name- id- }- }- }-}-"""--SHIPPING_LIST_METHODS_FOR_CHECKOUT = """subscription{event{@@ -3118,52 +3101,6 @@ subscription{"""-CHECKOUT_FILTER_SHIPPING_METHODS_CIRCULAR_SHIPPING_METHODS = """-subscription{- event{- ...on CheckoutFilterShippingMethods{- checkout{- id- shippingMethods{- id- }- }- }- }-}-"""--CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_SHIPPING_METHODS = """-subscription{- event{- ...on CheckoutFilterShippingMethods{- checkout{- id- availableShippingMethods{- id- }- }- }- }-}-"""--CHECKOUT_FILTER_SHIPPING_METHODS_AVAILABLE_PAYMENT_GATEWAYS = """-subscription{- event{- ...on CheckoutFilterShippingMethods{- checkout{- id- availablePaymentGateways{- id- }- }- }- }-}-"""--INVALID_MULTIPLE_EVENTS = """subscription{event{@@ -3258,22 +3195,3 @@ THUMBNAIL_CREATED = """}}"""--CHECKOUT_SHIPPING_LIST_AND_FILTER = """- subscription {- event {- ... on CheckoutFilterShippingMethods {- __typename- checkout {- id- }- }- ... on ShippingListMethodsForCheckout {- __typename- checkout {- id- }- }- }- }-"""diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex f26b091ced..5eab3584de 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -2913,151 +2913,6 @@ def test_shipping_list_methods_for_checkout(assert deliveries[0].webhook == webhooks[0]-def test_checkout_filter_shipping_methods(- checkout_with_shipping_required,- subscription_checkout_filter_shipping_methods_webhook,- address,- shipping_method,-):- # given- checkout = checkout_with_shipping_required- checkout.shipping_address = address- checkout.shipping_method = shipping_method- webhooks = [subscription_checkout_filter_shipping_methods_webhook]- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)-- internal_methods: list[ShippingMethodData] = []- for method in ShippingMethod.objects.all():- shipping_method_data = convert_to_shipping_method_data(- method, method.channel_listings.get(channel=checkout.channel)- )- internal_methods.append(shipping_method_data)-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, (checkout, internal_methods), webhooks- )-- # then- shipping_methods = [- {- "id": graphene.Node.to_global_id("ShippingMethod", sm.id),- "name": sm.name,- }- for sm in internal_methods- ]- payload = json.loads(deliveries[0].payload.get_payload())-- assert payload["checkout"] == {"id": checkout_id}- for method in shipping_methods:- assert method in payload["shippingMethods"]- assert len(deliveries) == len(webhooks)- assert deliveries[0].webhook == webhooks[0]---def test_checkout_filter_shipping_methods_no_methods_in_channel(- checkout,- subscription_checkout_filter_shipping_methods_webhook,- address,- shipping_method,- shipping_method_channel_PLN,-):- # given- webhooks = [subscription_checkout_filter_shipping_methods_webhook]- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, (checkout, []), webhooks- )-- # then- expected_payload = {"checkout": {"id": checkout_id}, "shippingMethods": []}- assert json.loads(deliveries[0].payload.get_payload()) == expected_payload- assert len(deliveries) == len(webhooks)- assert deliveries[0].webhook == webhooks[0]---def test_checkout_filter_shipping_methods_with_circular_call_for_shipping_methods(- checkout_ready_to_complete,- subscription_checkout_filter_shipping_method_webhook_with_shipping_methods,-):- # given- webhooks = [- subscription_checkout_filter_shipping_method_webhook_with_shipping_methods- ]- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, (checkout_ready_to_complete, []), webhooks- )-- # then- payload = json.loads(deliveries[0].payload.get_payload())-- assert len(payload["errors"]) == 1- assert (- payload["errors"][0]["message"]- == "Resolving this field is not allowed in synchronous events."- )- assert payload["checkout"] is None---def test_checkout_filter_shipping_methods_with_available_shipping_methods_field(- checkout_ready_to_complete,- subscription_checkout_filter_shipping_method_webhook_with_available_ship_methods,-):- # given- webhooks = [- subscription_checkout_filter_shipping_method_webhook_with_available_ship_methods- ]- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, (checkout_ready_to_complete, []), webhooks- )-- # then- payload = json.loads(deliveries[0].payload.get_payload())-- assert len(payload["errors"]) == 1- assert (- payload["errors"][0]["message"]- == "Resolving this field is not allowed in synchronous events."- )- assert payload["checkout"] is None---def test_checkout_filter_shipping_methods_with_circular_call_for_available_gateways(- checkout_ready_to_complete,- subscription_checkout_filter_shipping_method_webhook_with_payment_gateways,-):- # given- webhooks = [- subscription_checkout_filter_shipping_method_webhook_with_payment_gateways- ]- event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, (checkout_ready_to_complete, []), webhooks- )-- # then- payload = json.loads(deliveries[0].payload.get_payload())-- assert len(payload["errors"]) == 1- assert (- payload["errors"][0]["message"]- == "Resolving this field is not allowed in synchronous events."- )- assert payload["checkout"] is None--def test_checkout_list_methods_mismatch_in_subscription_query_definition(checkout_ready_to_complete,subscription_checkout_shipping_filter_and_list_missing_one_in_definition,diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 831ba7c19f..2cbdce9b7c 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -10,7 +10,6 @@ import grapheneimport pytestfrom django.core.serializers.json import DjangoJSONEncoderfrom freezegun import freeze_time-from measurement.measures import Weightfrom prices import Moneyfrom ... import __version__@@ -32,7 +31,6 @@ from ...payment.interface import RefundData, TransactionActionData, TransactionDfrom ...payment.models import TransactionItemfrom ...plugins.manager import get_plugins_managerfrom ...product.models import ProductVariant, ProductVariantChannelListing-from ...shipping.interface import ShippingMethodDatafrom ...warehouse import WarehouseClickAndCollectOptionfrom ..payloads import (PRODUCT_VARIANT_FIELDS,@@ -42,7 +40,6 @@ from ..payloads import (generate_checkout_payload_for_tax_calculation,generate_collection_payload,generate_customer_payload,- generate_excluded_shipping_methods_for_checkout_payload,generate_fulfillment_lines_payload,generate_invoice_payload,generate_list_gateways_payload,@@ -2244,37 +2241,6 @@ def test_generate_checkout_payload(}-def test_generate_excluded_shipping_methods_for_checkout(checkout):- shipping_method = ShippingMethodData(- id="123",- price=Money(Decimal("10.59"), "USD"),- name="shipping",- maximum_order_weight=Weight(kg=10),- minimum_order_weight=Weight(g=1),- maximum_delivery_days=10,- minimum_delivery_days=2,- )- response = json.loads(- generate_excluded_shipping_methods_for_checkout_payload(- checkout, [shipping_method]- )- )-- assert "checkout" in response- assert response["shipping_methods"] == [- {- "id": graphene.Node.to_global_id("ShippingMethod", "123"),- "price": "10.59",- "currency": "USD",- "name": "shipping",- "maximum_order_weight": "10.0:kg",- "minimum_order_weight": "1.0:g",- "maximum_delivery_days": 10,- "minimum_delivery_days": 2,- }- ]--def test_generate_requestor_returns_dict_with_user_id_and_user_type(staff_user, rf):request = rf.request()request.user = staff_userdiff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.pyindex 75f98cd6d0..675a61ca04 100644--- a/saleor/webhook/transport/shipping.py+++ b/saleor/webhook/transport/shipping.py@@ -1,28 +1,14 @@import jsonimport logging-from collections import defaultdict-from collections.abc import Callable-from typing import Any, Union+from typing import Any-from django.db.models import QuerySetfrom pydantic import ValidationErrorfrom ...app.models import App-from ...checkout.models import Checkout-from ...graphql.webhook.utils import get_pregenerated_subscription_payload-from ...order.models import Order-from ...plugins.base_plugin import ExcludedShippingMethod, RequestorOrLazyObject-from ...settings import WEBHOOK_SYNC_TIMEOUTfrom ...shipping.interface import ShippingMethodData-from ...webhook.utils import get_webhooks_for_event-from ..const import CACHE_EXCLUDED_SHIPPING_TIME-from ..models import Webhookfrom ..response_schemas.shipping import (- ExcludedShippingMethodSchema,- FilterShippingMethodsSchema,ListShippingMethodsSchema,)-from .synchronous.transport import trigger_webhook_sync_if_not_cachedlogger = logging.getLogger(__name__)@@ -57,150 +43,6 @@ def parse_list_shipping_methods_response(]-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)- source_object.pop("shipping_method", None)- return payload_dict---def get_excluded_shipping_methods_or_fetch(- webhooks: QuerySet,- event_type: str,- payload: str,- subscribable_object: (- tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None- ),- allow_replica: bool,- requestor: RequestorOrLazyObject | None,- pregenerated_subscription_payloads: dict | None = None,-) -> 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.- """- if pregenerated_subscription_payloads is None:- pregenerated_subscription_payloads = {}- cache_data = get_cache_data_for_exclude_shipping_methods(payload)- excluded_methods: list[ExcludedShippingMethodSchema] = []- # Gather responses from webhooks- for webhook in webhooks:- pregenerated_subscription_payload = get_pregenerated_subscription_payload(- webhook, pregenerated_subscription_payloads- )- 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,- request_timeout=WEBHOOK_SYNC_TIMEOUT,- cache_timeout=CACHE_EXCLUDED_SHIPPING_TIME,- requestor=requestor,- pregenerated_subscription_payload=pregenerated_subscription_payload,- )- if response_data and isinstance(response_data, dict):- excluded_methods.extend(- get_excluded_shipping_methods_from_response(response_data, webhook)- )- return parse_excluded_shipping_methods(excluded_methods)---def get_excluded_shipping_data(- event_type: str,- previous_value: list[ExcludedShippingMethod],- payload_fun: Callable[[], str],- subscribable_object: (- tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None- ),- allow_replica: bool,- requestor: RequestorOrLazyObject | None = None,- pregenerated_subscription_payloads: dict | None = None,-) -> list[ExcludedShippingMethod]:- """Exclude not allowed shipping methods by sync webhook.-- Fetch excluded shipping methods from sync webhooks and return them as a list of- excluded shipping methods.- The function uses a cache_key to reduce the number of- requests which we call to the external APIs. In case when we have the same payload- in a cache as we're going to send now, we will skip an additional request and use- the response fetched from cache.- The function will fetch the payload only in the case that we have any defined- webhook.- """- if pregenerated_subscription_payloads is None:- pregenerated_subscription_payloads = {}- excluded_methods_map: dict[str, list[ExcludedShippingMethod]] = defaultdict(list)- webhooks = get_webhooks_for_event(event_type)- if webhooks:- payload = payload_fun()-- excluded_methods_map = get_excluded_shipping_methods_or_fetch(- webhooks,- event_type,- payload,- subscribable_object,- allow_replica,- requestor,- pregenerated_subscription_payloads,- )-- # Gather responses for previous plugins- for method in previous_value:- excluded_methods_map[method.id].append(method)-- # Return a list of excluded methods, unique by id- excluded_methods = []- for method_id, methods in excluded_methods_map.items():- reason = None- if reasons := [m.reason for m in methods if m.reason]:- reason = " ".join(reasons)- excluded_methods.append(ExcludedShippingMethod(id=method_id, reason=reason))- return excluded_methods---def get_excluded_shipping_methods_from_response(- response_data: dict,- webhook: "Webhook",-) -> list[ExcludedShippingMethodSchema]:- excluded_methods = []- try:- filter_methods_schema = FilterShippingMethodsSchema.model_validate(- response_data,- context={- "custom_message": "Skipping invalid shipping method (FilterShippingMethodsSchema)"- },- )- excluded_methods.extend(filter_methods_schema.excluded_methods)- except ValidationError:- logger.warning(- "Skipping invalid response from app %s: %s",- str(webhook.app.identifier),- response_data,- )- return excluded_methods---def parse_excluded_shipping_methods(- excluded_methods: list[ExcludedShippingMethodSchema],-) -> dict[str, list[ExcludedShippingMethod]]:- """Prepare method_id to excluded methods map."""- excluded_methods_map = defaultdict(list)- for excluded_method in excluded_methods:- method_id = excluded_method.id- reason = excluded_method.reason or ""- excluded_methods_map[method_id].append(- ExcludedShippingMethod(id=method_id, reason=reason)- )- return excluded_methods_map--def get_cache_data_for_shipping_list_methods_for_checkout(payload: str) -> dict:key_data = json.loads(payload)diff --git a/saleor/webhook/transport/tests/test_shipping.py b/saleor/webhook/transport/tests/test_shipping.pyindex 0be285e0ea..dd725bf925 100644--- a/saleor/webhook/transport/tests/test_shipping.py+++ b/saleor/webhook/transport/tests/test_shipping.py@@ -1,10 +1,8 @@from ....checkout.utils import get_or_create_checkout_metadatafrom ...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,)@@ -26,19 +24,3 @@ def test_get_cache_data_for_shipping_list_methods_for_checkout(checkout_with_iteassert "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