Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Generate sync webhook payloads in the dataloaders for filtering checkout shipping methods. (#16586)
Filip Owczareke4961c662afb
diff --git a/saleor/app/tests/fixtures/webhooks/shipping_app.py b/saleor/app/tests/fixtures/webhooks/shipping_app.pyindex 2582af223b..535f57532c 100644--- a/saleor/app/tests/fixtures/webhooks/shipping_app.py+++ b/saleor/app/tests/fixtures/webhooks/shipping_app.py@@ -59,3 +59,48 @@ def shipping_app_with_subscription(db, permission_manage_shipping):])return app+++def exclude_shipping_app_without_subscription(db, permission_manage_checkouts):+ app = App.objects.create(name="Shipping App without subscription", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_checkouts)++ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-app.com/api/",+ )+ WebhookEvent.objects.create(+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ webhook=webhook,+ )+ return app+++def exclude_shipping_app_with_subscription(db, permission_manage_checkouts):+ app = App.objects.create(name="Shipping App with subscription", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_checkouts)++ webhook = Webhook.objects.create(+ name="shipping-webhook-2",+ app=app,+ target_url="https://shipping-app.com/api/",+ subscription_query="""+ subscription {+ event {+ ... on CheckoutFilterShippingMethods {+ __typename+ }+ }+ }+ """,+ )+ WebhookEvent.objects.create(+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ webhook=webhook,+ )+ return appdiff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex c7f46a97b6..b820f7ff2e 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -107,6 +107,7 @@ class CheckoutInfo:voucher: Optional["Voucher"] = Nonevoucher_code: Optional["VoucherCode"] = Nonedatabase_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME+ pregenerated_payloads_for_excluded_shipping_method: Optional[dict] = None@cached_propertydef all_shipping_methods(self) -> list["ShippingMethodData"]:@@ -123,6 +124,7 @@ class CheckoutInfo:self.checkout,self.channel,all_methods,+ self.pregenerated_payloads_for_excluded_shipping_method,)initialize_shipping_method_active_status(all_methods, excluded_methods)return all_methodsdiff --git a/saleor/graphql/app/dataloaders/__init__.py b/saleor/graphql/app/dataloaders/__init__.pyindex 47cda81aea..e65cbf6649 100644--- a/saleor/graphql/app/dataloaders/__init__.py+++ b/saleor/graphql/app/dataloaders/__init__.py@@ -1,7 +1,7 @@-from .app import AppByIdLoader, AppByTokenLoader+from .app import ActiveAppByIdLoader, AppByIdLoader, AppByTokenLoaderfrom .app_extension import AppExtensionByAppIdLoader, AppExtensionByIdLoaderfrom .app_tokens import AppTokensByAppIdLoader-from .apps import ActiveAppsByAppIdentifierLoader+from .apps import ActiveAppsByAppIdentifierLoader, AppsByEventTypeLoaderfrom .thumbnail import (ThumbnailByAppIdSizeAndFormatLoader,ThumbnailByAppInstallationIdSizeAndFormatLoader,@@ -9,6 +9,7 @@ from .thumbnail import (from .utils import app_promise_callback, get_app_promise__all__ = [+ "ActiveAppByIdLoader","ActiveAppsByAppIdentifierLoader","app_promise_callback","AppByIdLoader",@@ -16,6 +17,7 @@ __all__ = ["AppExtensionByAppIdLoader","AppExtensionByIdLoader","AppTokensByAppIdLoader",+ "AppsByEventTypeLoader","get_app_promise","ThumbnailByAppIdSizeAndFormatLoader","ThumbnailByAppInstallationIdSizeAndFormatLoader",diff --git a/saleor/graphql/app/dataloaders/app.py b/saleor/graphql/app/dataloaders/app.pyindex 832bbc5312..4ed1cdd8f7 100644--- a/saleor/graphql/app/dataloaders/app.py+++ b/saleor/graphql/app/dataloaders/app.py@@ -46,3 +46,16 @@ class AppByTokenLoader(DataLoader[str, App]):)return [apps.get(authed_apps.get(key)) for key in keys]+++class ActiveAppByIdLoader(DataLoader):+ context_key = "active_app_by_id"++ def batch_load(self, keys):+ apps_map = (+ App.objects.using(self.database_connection_name)+ .filter(is_active=True, removed_at__isnull=True)+ .prefetch_related("permissions__content_type")+ .in_bulk()+ )+ return [apps_map.get(app_id) for app_id in keys]diff --git a/saleor/graphql/app/dataloaders/apps.py b/saleor/graphql/app/dataloaders/apps.pyindex aa4b5fa48b..a72b81c2de 100644--- a/saleor/graphql/app/dataloaders/apps.py+++ b/saleor/graphql/app/dataloaders/apps.py@@ -2,6 +2,8 @@ from collections import defaultdictfrom ....app.models import Appfrom ...core.dataloaders import DataLoader+from ...webhook.dataloaders.models import WebhooksByEventTypeLoader+from .app import AppByIdLoaderclass ActiveAppsByAppIdentifierLoader(DataLoader[str, App]):@@ -15,3 +17,37 @@ class ActiveAppsByAppIdentifierLoader(DataLoader[str, App]):for app in apps:apps_map[app.identifier].append(app)return [apps_map.get(app_identifier, []) for app_identifier in keys]+++class AppsByEventTypeLoader(DataLoader):+ context_key = "app_by_event_type"++ def batch_load(self, keys):+ app_ids_by_event_type: dict[str, list[int]] = defaultdict(list)+ app_ids = set()++ def return_apps_for_webhooks(webhooks_by_event_type):+ for event_type, webhooks in zip(keys, webhooks_by_event_type):+ ids = [webhook.app_id for webhook in webhooks]+ app_ids_by_event_type[event_type] = ids+ app_ids.update(ids)++ def return_apps(+ apps, app_ids_by_event_type=app_ids_by_event_type, keys=keys+ ):+ apps_by_event_type = defaultdict(list)+ app_by_id = defaultdict(list)+ for app in apps:+ app_by_id[app.id] = app+ for event_type in keys:+ for app_id in app_ids_by_event_type[event_type]:+ apps_by_event_type[event_type].append(app_by_id[app_id])+ return [apps_by_event_type[event_type] for event_type in keys]++ return AppByIdLoader(self.context).load_many(app_ids).then(return_apps)++ return (+ WebhooksByEventTypeLoader(self.context)+ .load_many(keys)+ .then(return_apps_for_webhooks)+ )diff --git a/saleor/graphql/checkout/dataloaders/checkout_infos.py b/saleor/graphql/checkout/dataloaders/checkout_infos.pyindex f881eea5ff..3783870a2e 100644--- a/saleor/graphql/checkout/dataloaders/checkout_infos.py+++ b/saleor/graphql/checkout/dataloaders/checkout_infos.py@@ -35,6 +35,9 @@ from ...tax.dataloaders import TaxClassByVariantIdLoader, TaxConfigurationByChanfrom ...warehouse.dataloaders import (WarehouseByIdLoader,)+from ...webhook.dataloaders.pregenerated_payloads_for_checkout_filter_shipping_methods import (+ PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader,+)from .models import CheckoutByTokenLoader, CheckoutLinesByCheckoutTokenLoaderfrom .promotion_rule_infos import VariantPromotionRuleInfoByCheckoutLineIdLoader@@ -44,7 +47,13 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):def batch_load(self, keys):def with_checkout(data):- checkouts, checkout_line_infos, checkout_discounts, manager = data+ (+ checkouts,+ checkout_line_infos,+ checkout_discounts,+ manager,+ pregenerated_payloads_for_excluded_shipping_methods,+ ) = datachannel_pks = [checkout.channel_id for checkout in checkouts]@@ -133,12 +142,20 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):}checkout_info_map = {}- for key, checkout, channel, checkout_lines, discounts in zip(+ for (+ key,+ checkout,+ channel,+ checkout_lines,+ discounts,+ pregenerated_payloads_for_excluded_shipping_method,+ ) in zip(keys,checkouts,channels,checkout_line_infos,checkout_discounts,+ pregenerated_payloads_for_excluded_shipping_methods,):shipping_method = shipping_method_map.get(checkout.shipping_method_id@@ -177,6 +194,9 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):voucher=voucher_code.voucher if voucher_code else None,voucher_code=voucher_code,database_connection_name=self.database_connection_name,+ pregenerated_payloads_for_excluded_shipping_method=(+ pregenerated_payloads_for_excluded_shipping_method+ ),)checkout_info_map[key] = checkout_info@@ -206,9 +226,20 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):).load_many(keys)discounts = CheckoutDiscountByCheckoutIdLoader(self.context).load_many(keys)manager = get_plugin_manager_promise(self.context)- return Promise.all([checkouts, checkout_line_infos, discounts, manager]).then(- with_checkout+ pregenerated_payloads_for_excluded_shipping_methods_loader = (+ PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(+ self.context+ ).load_many(keys))+ return Promise.all(+ [+ checkouts,+ checkout_line_infos,+ discounts,+ manager,+ pregenerated_payloads_for_excluded_shipping_methods_loader,+ ]+ ).then(with_checkout)class CheckoutLinesInfoByCheckoutTokenLoader(diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 592a42dd65..17e68b8a3c 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1,4 +1,5 @@import datetime+from collections import defaultdictfrom decimal import Decimalfrom unittest import mock@@ -229,6 +230,7 @@ def test_checkout_available_payment_gateways_valid_info_sent(# thencheckout_info.manager = mock.ANYcheckout_info.database_connection_name = mock.ANY+ checkout_info.pregenerated_payloads_for_excluded_shipping_method = defaultdict(dict)mocked_list_gateways.assert_called_with(currency=currency,checkout_info=checkout_info,diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 5545d8eb2d..f84b6e74a0 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -79,7 +79,9 @@ from ..tax.dataloaders import (from ..utils import get_user_or_app_from_contextfrom ..warehouse.dataloaders import StocksReservationsByCheckoutTokenLoaderfrom ..warehouse.types import Warehouse-from ..webhook.dataloaders import PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader+from ..webhook.dataloaders.pregenerated_payload_for_checkout_tax import (+ PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,+)from .dataloaders import (CheckoutByTokenLoader,CheckoutInfoByCheckoutTokenLoader,diff --git a/saleor/graphql/webhook/dataloaders/__init__.py b/saleor/graphql/webhook/dataloaders/__init__.pyindex 6bc545f027..793a8c8f2f 100644--- a/saleor/graphql/webhook/dataloaders/__init__.py+++ b/saleor/graphql/webhook/dataloaders/__init__.py@@ -2,14 +2,14 @@ from .models import (PayloadByIdLoader,WebhookEventsByWebhookIdLoader,WebhooksByAppIdLoader,+ WebhooksByEventTypeLoader,)-from .pregenerated_payload_for_checkout_tax import (- PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,-)+from .request_context import PayloadsRequestContextByEventTypeLoader__all__ = ["PayloadByIdLoader",- "PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader",+ "PayloadsRequestContextByEventTypeLoader","WebhookEventsByWebhookIdLoader","WebhooksByAppIdLoader",+ "WebhooksByEventTypeLoader",]diff --git a/saleor/graphql/webhook/dataloaders/models.py b/saleor/graphql/webhook/dataloaders/models.pyindex 759ff19ff8..445a62a963 100644--- a/saleor/graphql/webhook/dataloaders/models.py+++ b/saleor/graphql/webhook/dataloaders/models.py@@ -1,7 +1,12 @@from collections import defaultdictfrom ....core.models import EventPayload+from ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.models import Webhook, WebhookEvent+from ....webhook.utils import (+ calculate_webhooks_for_multiple_events,+)+from ...app.dataloaders import ActiveAppByIdLoaderfrom ...core.dataloaders import DataLoader@@ -45,3 +50,95 @@ class WebhooksByAppIdLoader(DataLoader):for webhook in webhooks:webhooks_by_app_map[webhook.app_id].append(webhook)return [webhooks_by_app_map.get(app_id, []) for app_id in keys]+++class WebhookEventsByEventTypeLoader(DataLoader):+ context_key = "webhook_events_by_event_type"++ def batch_load(self, keys):+ webhook_events_by_event_type: dict[str, list[WebhookEvent]] = defaultdict(list)+ webhooks_events = WebhookEvent.objects.using(+ self.database_connection_name+ ).filter(event_type__in=keys)+ for webhook_event in webhooks_events:+ webhook_events_by_event_type[webhook_event.event_type].append(webhook_event)+ return [webhook_events_by_event_type[event_type] for event_type in keys]+++class ActiveWebhooksByIdLoader(DataLoader):+ context_key = "active_webhooks_by_id"++ def batch_load(self, keys):+ webhooks_map = (+ Webhook.objects.using(self.database_connection_name)+ .filter(is_active=True)+ .in_bulk(keys)+ )+ return [webhooks_map.get(webhook_id) for webhook_id in keys]+++class WebhooksByEventTypeLoader(DataLoader):+ context_key = "webhooks_by_event_type"++ def batch_load(self, keys):+ set_event_types = set(keys)+ if set_event_types.intersection(WebhookEventAsyncType.ALL):+ set_event_types.add(WebhookEventAsyncType.ANY)++ def fetch_webhooks(+ webhook_events_by_event_types, set_event_types=set_event_types+ ):+ events_types_by_webhook_id_map: dict[int, set[str]] = defaultdict(set)+ webhooks_ids = set()+ for webhook_events_by_event_type in webhook_events_by_event_types:+ for webhook_event in webhook_events_by_event_type:+ webhooks_id = webhook_event.webhook_id+ events_types_by_webhook_id_map[webhook_event.webhook_id].add(+ webhook_event.event_type+ )+ webhooks_ids.add(webhooks_id)++ def fetch_apps(+ webhooks,+ set_event_types=set_event_types,+ events_types_by_webhook_id_map=events_types_by_webhook_id_map,+ ):+ # Filter out None values due to webhooks that are not active.+ webhooks = [webhook for webhook in webhooks if webhook]+ app_ids = {webhook.app_id for webhook in webhooks}++ def return_webhooks_by_event_type(+ apps,+ set_event_types=set_event_types,+ events_types_by_webhook_id_map=events_types_by_webhook_id_map,+ webhooks=webhooks,+ ):+ apps_by_id = {app.id: app for app in apps if app}+ webhooks_by_event_type_map = calculate_webhooks_for_multiple_events(+ set_event_types,+ apps_by_id,+ webhooks,+ events_types_by_webhook_id_map,+ )+ return [+ webhooks_by_event_type_map.get(event_type, [])+ for event_type in keys+ ]++ return (+ ActiveAppByIdLoader(self.context)+ .load_many(app_ids)+ .then(return_webhooks_by_event_type)+ )++ return (+ ActiveWebhooksByIdLoader(self.context)+ .load_many(webhooks_ids)+ .then(fetch_apps)+ )++ return (+ WebhookEventsByEventTypeLoader(self.context)+ .load_many(set_event_types)+ .then(fetch_webhooks)+ )diff --git a/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.pyindex cb05bcd590..7e1c681f48 100644--- a/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py+++ b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py@@ -12,19 +12,18 @@ from ....tax.utils import (get_tax_configuration_for_checkout,)from ....webhook.event_types import WebhookEventSyncType-from ....webhook.utils import get_webhooks_for_event-from ...app.dataloaders import AppByIdLoader-from ...checkout.dataloaders import (+from ...app.dataloaders.apps import AppsByEventTypeLoader+from ...checkout.dataloaders.checkout_infos import (CheckoutInfoByCheckoutTokenLoader,CheckoutLinesInfoByCheckoutTokenLoader,)from ...core.dataloaders import DataLoader-from ...utils import get_user_or_app_from_context-from ..subscription_payload import (- generate_payload_promise_from_subscription,- initialize_request,-)+from ..subscription_payload import generate_payload_promise_from_subscriptionfrom ..utils import get_subscription_query_hash+from .models import WebhooksByEventTypeLoader+from .request_context import (+ PayloadsRequestContextByEventTypeLoader,+)class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):@@ -54,19 +53,10 @@ class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):)event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES- requestor = get_user_or_app_from_context(self.context)- request_context = initialize_request(- requestor,- sync_event=True,- allow_replica=False,- event_type=event_type,- )- webhooks = get_webhooks_for_event(event_type)- apps_ids = [webhook.app_id for webhook in webhooks]@allow_writer_in_context(self.context)def generate_payloads(data):- checkouts_info, checkout_lines_info, apps = data+ checkouts_info, checkout_lines_info, apps, request_context, webhooks = dataapps_map = {app.id: app for app in apps}promises = []for checkout_info, lines_info in zip(checkouts_info, checkout_lines_info):@@ -130,5 +120,11 @@ class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):checkouts_info = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)- apps = AppByIdLoader(self.context).load_many(apps_ids)- return Promise.all([checkouts_info, lines, apps]).then(generate_payloads)+ apps = AppsByEventTypeLoader(self.context).load(event_type)+ request_context = PayloadsRequestContextByEventTypeLoader(self.context).load(+ event_type+ )+ webhooks = WebhooksByEventTypeLoader(self.context).load(event_type)+ return Promise.all(+ [checkouts_info, lines, apps, request_context, webhooks]+ ).then(generate_payloads)diff --git a/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.py b/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.pynew file mode 100644index 0000000000..37a774fafb--- /dev/null+++ b/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.py@@ -0,0 +1,96 @@+from collections import defaultdict+from typing import Any++from promise import Promise++from ....webhook.event_types import WebhookEventSyncType+from ...app.dataloaders.apps import AppsByEventTypeLoader+from ...checkout.dataloaders.models import CheckoutByTokenLoader+from ...core.dataloaders import DataLoader+from ..subscription_payload import (+ generate_payload_promise_from_subscription,+)+from ..utils import get_subscription_query_hash+from .models import WebhooksByEventTypeLoader+from .request_context import (+ PayloadsRequestContextByEventTypeLoader,+)+++class PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(DataLoader):+ context_key = (+ "pregenerated_checkout_filter_shipping_method_payloads_by_checkout_token"+ )++ def batch_load(self, keys):+ """Fetch pregenerated tax payloads for checkout shipping method filtering.++ This loader is used to fetch pregenerated payloads for checkouts shipping method filtering.++ return: A dict of shipping method filtering payloads for checkouts.++ Example:+ {+ "checkout_token": {+ "app_id": {+ "query_hash": {+ <payload>+ }+ }+ }+ }++ """++ results: dict[str, dict[int, dict[str, dict[str, Any]]]] = defaultdict(+ lambda: defaultdict(dict)+ )++ event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS++ def generate_payloads(data):+ checkouts, apps, request_context, webhooks = data+ apps_map = {app.id: app for app in apps}+ promises = []+ for checkout in checkouts:+ for webhook in webhooks:+ if not webhook.subscription_query:+ continue+ query_hash = get_subscription_query_hash(webhook.subscription_query)+ app_id = webhook.app_id+ app = apps_map[app_id]+ checkout_token = str(checkout.token)+ promise_payload = generate_payload_promise_from_subscription(+ event_type=event_type,+ subscribable_object=checkout,+ subscription_query=webhook.subscription_query,+ request=request_context,+ app=app,+ )+ promises.append(promise_payload)++ def store_payload(+ payload,+ checkout_token=checkout_token,+ app_id=app_id,+ query_hash=query_hash,+ ):+ if payload:+ results[checkout_token][app_id][query_hash] = payload++ promise_payload.then(store_payload)++ def return_payloads(_payloads):+ return [results[str(checkout.token)] for checkout in checkouts]++ return Promise.all(promises).then(return_payloads)++ checkouts = CheckoutByTokenLoader(self.context).load_many(keys)+ apps = AppsByEventTypeLoader(self.context).load(event_type)+ request_context = PayloadsRequestContextByEventTypeLoader(self.context).load(+ event_type+ )+ webhooks = WebhooksByEventTypeLoader(self.context).load(event_type)+ return Promise.all([checkouts, apps, request_context, webhooks]).then(+ generate_payloads+ )diff --git a/saleor/graphql/webhook/dataloaders/request_context.py b/saleor/graphql/webhook/dataloaders/request_context.pynew file mode 100644index 0000000000..2a91c8112b--- /dev/null+++ b/saleor/graphql/webhook/dataloaders/request_context.py@@ -0,0 +1,25 @@+from collections import defaultdict+from typing import Optional++from ...core import SaleorContext+from ...core.dataloaders import DataLoader+from ...utils import get_user_or_app_from_context+from ..subscription_payload import initialize_request+++class PayloadsRequestContextByEventTypeLoader(DataLoader):+ context_key = "payloads_request_context_by_event_type"++ def batch_load(self, keys):+ request_context_by_event_type: dict[str, Optional[SaleorContext]] = (+ defaultdict()+ )+ requestor = get_user_or_app_from_context(self.context)+ for event_type in keys:+ request_context_by_event_type[event_type] = initialize_request(+ requestor,+ sync_event=True,+ allow_replica=False,+ event_type=event_type,+ )+ return [request_context_by_event_type.get(event_type) for event_type in keys]diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.pyindex 0e1e2bd500..ac14fde6a3 100644--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py@@ -4,9 +4,23 @@ from unittest import mockfrom django.test import override_settingsfrom django.utils import timezone+from .....shipping.models import ShippingMethodfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_content+_line_tax_data = {+ "total_gross_amount": 2.5,+ "total_net_amount": 2,+ "tax_rate": 20,+}+TAX_DATA_RESPONSE = {+ "currency": "USD",+ "shipping_price_gross_amount": 10,+ "shipping_price_net_amount": 8,+ "shipping_tax_rate": 20,+ "lines": [_line_tax_data for _ in range(4)],+}+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")@@ -16,12 +30,12 @@ from ....tests.utils import get_graphql_contentdef test_checkout_total_price_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given+ checkout = checkout_with_shipping_addresscheckout.price_expiration = timezone.now() - datetime.timedelta(days=1)checkout.save()checkout_global_id = to_global_id_or_none(checkout)@@ -42,7 +56,7 @@ def test_checkout_total_price_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -52,6 +66,8 @@ def test_checkout_total_price_use_pregenerated_payload(mock_generate_payload.assert_not_called()mock_request.assert_called_once()assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["totalPrice"]["net"]["amount"] == 16+ assert content["data"]["checkout"]["totalPrice"]["gross"]["amount"] == 20@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])@@ -62,12 +78,12 @@ def test_checkout_total_price_use_pregenerated_payload(def test_checkout_subtotal_price_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given+ checkout = checkout_with_shipping_addresscheckout.price_expiration = timezone.now() - datetime.timedelta(days=1)checkout.save()checkout_global_id = to_global_id_or_none(checkout)@@ -88,7 +104,7 @@ def test_checkout_subtotal_price_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -98,6 +114,8 @@ def test_checkout_subtotal_price_use_pregenerated_payload(mock_generate_payload.assert_not_called()mock_request.assert_called_once()assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["subtotalPrice"]["net"]["amount"] == 8+ assert content["data"]["checkout"]["subtotalPrice"]["gross"]["amount"] == 10@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])@@ -108,12 +126,12 @@ def test_checkout_subtotal_price_use_pregenerated_payload(def test_checkout_total_balance_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given+ checkout = checkout_with_shipping_addresscheckout.price_expiration = timezone.now() - datetime.timedelta(days=1)checkout.save()checkout_global_id = to_global_id_or_none(checkout)@@ -129,7 +147,7 @@ def test_checkout_total_balance_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -139,6 +157,7 @@ def test_checkout_total_balance_use_pregenerated_payload(mock_generate_payload.assert_not_called()mock_request.assert_called_once()assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["totalBalance"]["amount"] == -20@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])@@ -149,12 +168,12 @@ def test_checkout_total_balance_use_pregenerated_payload(def test_checkout_shipping_price_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given+ checkout = checkout_with_shipping_addresscheckout.price_expiration = timezone.now() - datetime.timedelta(days=1)checkout.save()checkout_global_id = to_global_id_or_none(checkout)@@ -178,7 +197,7 @@ def test_checkout_shipping_price_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -188,6 +207,8 @@ def test_checkout_shipping_price_use_pregenerated_payload(mock_generate_payload.assert_not_called()mock_request.assert_called_once()assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["shippingPrice"]["net"]["amount"] == 8+ assert content["data"]["checkout"]["shippingPrice"]["gross"]["amount"] == 10@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])@@ -198,12 +219,12 @@ def test_checkout_shipping_price_use_pregenerated_payload(def test_checkout_authorize_status_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given+ checkout = checkout_with_shipping_addresscheckout.price_expiration = timezone.now() - datetime.timedelta(days=1)checkout.save()checkout_global_id = to_global_id_or_none(checkout)@@ -217,7 +238,7 @@ def test_checkout_authorize_status_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -237,12 +258,12 @@ def test_checkout_authorize_status_use_pregenerated_payload(def test_checkout_charge_status_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given+ checkout = checkout_with_shipping_addresscheckout.price_expiration = timezone.now() - datetime.timedelta(days=1)checkout.save()checkout_global_id = to_global_id_or_none(checkout)@@ -256,7 +277,7 @@ def test_checkout_charge_status_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -276,15 +297,15 @@ def test_checkout_charge_status_use_pregenerated_payload(def test_checkout_line_unit_price_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout_with_item,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given- checkout_with_item.price_expiration = timezone.now() - datetime.timedelta(days=1)- checkout_with_item.save()- checkout_global_id = to_global_id_or_none(checkout_with_item)+ checkout = checkout_with_shipping_address+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)+ checkout.save()+ checkout_global_id = to_global_id_or_none(checkout)checkout_total_price_query = """query getCheckout($id: ID!) {checkout(id: $id) {@@ -307,7 +328,7 @@ def test_checkout_line_unit_price_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -315,6 +336,15 @@ def test_checkout_line_unit_price_use_pregenerated_payload(# thenassert content["data"]["checkout"]["id"] == checkout_global_id+ lines_data = content["data"]["checkout"]["lines"]+ assert lines_data[0]["unitPrice"]["net"]["amount"] == 2+ assert lines_data[0]["unitPrice"]["gross"]["amount"] == 2.5+ assert lines_data[1]["unitPrice"]["net"]["amount"] == 0.2+ assert lines_data[1]["unitPrice"]["gross"]["amount"] == 0.25+ assert lines_data[2]["unitPrice"]["net"]["amount"] == 0.67+ assert lines_data[2]["unitPrice"]["gross"]["amount"] == 0.83+ assert lines_data[3]["unitPrice"]["net"]["amount"] == 0.4+ assert lines_data[3]["unitPrice"]["gross"]["amount"] == 0.5mock_generate_payload.assert_not_called()mock_request.assert_called_once()@@ -327,15 +357,15 @@ def test_checkout_line_unit_price_use_pregenerated_payload(def test_checkout_line_total_price_use_pregenerated_payload(mock_generate_payload,mock_request,- checkout_with_item,+ checkout_with_shipping_address,api_client,- tax_data_response,tax_app,):# given- checkout_with_item.price_expiration = timezone.now() - datetime.timedelta(days=1)- checkout_with_item.save()- checkout_global_id = to_global_id_or_none(checkout_with_item)+ checkout = checkout_with_shipping_address+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)+ checkout.save()+ checkout_global_id = to_global_id_or_none(checkout)checkout_total_price_query = """query getCheckout($id: ID!) {checkout(id: $id) {@@ -358,7 +388,7 @@ def test_checkout_line_total_price_use_pregenerated_payload("""variables = {"id": checkout_global_id}- mock_request.return_value = tax_data_response+ mock_request.return_value = TAX_DATA_RESPONSE# whenresponse = api_client.post_graphql(checkout_total_price_query, variables)@@ -366,5 +396,227 @@ def test_checkout_line_total_price_use_pregenerated_payload(# thenassert content["data"]["checkout"]["id"] == checkout_global_id+ for line_data in content["data"]["checkout"]["lines"]:+ assert line_data["totalPrice"]["net"]["amount"] == 2+ assert line_data["totalPrice"]["gross"]["amount"] == 2.5mock_generate_payload.assert_not_called()mock_request.assert_called_once()+++@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"+)+def test_shipping_methods_use_pregenerated_payload(+ mock_generate_payload,+ mock_request,+ checkout_with_shipping_address,+ shipping_method,+ api_client,+ exclude_shipping_app_with_subscription,+):+ # given+ checkout = checkout_with_shipping_address+ checkout_global_id = to_global_id_or_none(checkout)+ shipping_methods = ShippingMethod.objects.order_by("id").all()+ shipping_method_global_ids = [+ to_global_id_or_none(shipping_method) for shipping_method in shipping_methods+ ]+ exclude_msg = "Shipping method is excluded via metadata by external app."+ checkout_shipping_query = """+ query getCheckout($id: ID!) {+ checkout(id: $id) {+ id+ shippingMethods {+ id+ name+ active+ message+ }+ }+ }+ """+ variables = {"id": checkout_global_id}++ mock_request.return_value = {+ "excluded_methods": [+ {+ "id": shipping_method_global_ids[1],+ "reason": exclude_msg,+ },+ ]+ }++ # when+ response = api_client.post_graphql(checkout_shipping_query, variables)+ content = get_graphql_content(response)++ # then+ assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["shippingMethods"] == [+ {+ "id": shipping_method_global_ids[0],+ "name": "DHL",+ "active": True,+ "message": "",+ },+ {+ "id": shipping_method_global_ids[1],+ "name": "DHL",+ "active": False,+ "message": exclude_msg,+ },+ ]+ mock_request.assert_called_once()+ mock_generate_payload.assert_not_called()+++@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"+)+def test_available_shipping_methods_use_pregenerated_payload(+ mock_generate_payload,+ mock_request,+ checkout_with_shipping_address,+ shipping_method,+ api_client,+ exclude_shipping_app_with_subscription,+):+ # given+ checkout = checkout_with_shipping_address+ checkout_global_id = to_global_id_or_none(checkout)+ shipping_methods = ShippingMethod.objects.order_by("id").all()+ shipping_method_global_ids = [+ to_global_id_or_none(shipping_method) for shipping_method in shipping_methods+ ]+ exclude_msg = "Shipping method is excluded via metadata by external app."+ checkout_shipping_query = """+ query getCheckout($id: ID!) {+ checkout(id: $id) {+ id+ availableShippingMethods {+ id+ name+ active+ message+ }+ }+ }+ """+ variables = {"id": checkout_global_id}++ mock_request.return_value = {+ "excluded_methods": [+ {+ "id": shipping_method_global_ids[1],+ "reason": exclude_msg,+ },+ ]+ }++ # when+ response = api_client.post_graphql(checkout_shipping_query, variables)+ content = get_graphql_content(response)++ # then+ assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["availableShippingMethods"] == [+ {+ "id": shipping_method_global_ids[0],+ "name": "DHL",+ "active": True,+ "message": "",+ }+ ]+ mock_request.assert_called_once()+ mock_generate_payload.assert_not_called()+++@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"+)+def test_shipping_methods_and_taxes_use_pregenerated_payload(+ mock_generate_payload,+ mock_shipping_request,+ mock_tax_request,+ checkout_with_shipping_address,+ shipping_method,+ api_client,+ exclude_shipping_app_with_subscription,+ tax_data_response,+ tax_app,+):+ # given+ checkout = checkout_with_shipping_address+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)+ checkout.save()+ checkout_global_id = to_global_id_or_none(checkout)+ shipping_methods = ShippingMethod.objects.order_by("id").all()+ shipping_method_global_ids = [+ to_global_id_or_none(shipping_method) for shipping_method in shipping_methods+ ]+ exclude_msg = "Shipping method is excluded via metadata by external app."+ checkout_shipping_query = """+ query getCheckout($id: ID!) {+ checkout(id: $id) {+ id+ totalPrice {+ net {+ amount+ }+ gross {+ amount+ }+ }+ shippingMethods {+ id+ name+ active+ message+ }+ }+ }+ """+ variables = {"id": checkout_global_id}++ mock_shipping_request.return_value = {+ "excluded_methods": [+ {+ "id": shipping_method_global_ids[1],+ "reason": exclude_msg,+ },+ ]+ }+ mock_tax_request.return_value = TAX_DATA_RESPONSE++ # when+ response = api_client.post_graphql(checkout_shipping_query, variables)+ content = get_graphql_content(response)++ # then+ assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["shippingMethods"] == [+ {+ "id": shipping_method_global_ids[0],+ "name": "DHL",+ "active": True,+ "message": "",+ },+ {+ "id": shipping_method_global_ids[1],+ "name": "DHL",+ "active": False,+ "message": exclude_msg,+ },+ ]+ assert content["data"]["checkout"]["totalPrice"]["net"]["amount"] == 16+ assert content["data"]["checkout"]["totalPrice"]["gross"]["amount"] == 20+ mock_tax_request.assert_called_once()+ mock_shipping_request.assert_called_once()+ mock_generate_payload.assert_not_called()diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_exclude_shipping_methods_pregenerated_payloads.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_exclude_shipping_methods_pregenerated_payloads.pynew file mode 100644index 0000000000..11b2354e56--- /dev/null+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_exclude_shipping_methods_pregenerated_payloads.py@@ -0,0 +1,76 @@+from unittest import mock++from django.test import override_settings++from .....shipping.models import ShippingMethod+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content+++@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"+)+def test_shipping_methods_use_pregenerated_payloads_app_without_subscription(+ mock_generate_payload,+ mock_request,+ checkout_with_shipping_address,+ shipping_method,+ api_client,+ exclude_shipping_app_without_subscription,+):+ # given+ checkout = checkout_with_shipping_address+ checkout_global_id = to_global_id_or_none(checkout)+ shipping_methods = ShippingMethod.objects.order_by("id").all()+ shipping_method_global_ids = [+ to_global_id_or_none(shipping_method) for shipping_method in shipping_methods+ ]+ exclude_msg = "Shipping method is excluded via metadata by external app."+ checkout_shipping_query = """+ query getCheckout($id: ID!) {+ checkout(id: $id) {+ id+ shippingMethods {+ id+ name+ active+ message+ }+ }+ }+ """+ variables = {"id": checkout_global_id}++ mock_request.return_value = {+ "excluded_methods": [+ {+ "id": shipping_method_global_ids[1],+ "reason": exclude_msg,+ },+ ]+ }++ # when+ response = api_client.post_graphql(checkout_shipping_query, variables)+ content = get_graphql_content(response)++ # then+ assert content["data"]["checkout"]["id"] == checkout_global_id+ assert content["data"]["checkout"]["shippingMethods"] == [+ {+ "id": shipping_method_global_ids[0],+ "name": "DHL",+ "active": True,+ "message": "",+ },+ {+ "id": shipping_method_global_ids[1],+ "name": "DHL",+ "active": False,+ "message": exclude_msg,+ },+ ]+ mock_request.assert_called_once()+ mock_generate_payload.assert_not_called()diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 759de4a755..838b6f6688 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -2880,12 +2880,16 @@ class PluginsManager(PaymentInterface):checkout: "Checkout",channel: "Channel",available_shipping_methods: list["ShippingMethodData"],+ pregenerated_subscription_payloads: Optional[dict] = None,) -> list[ExcludedShippingMethod]:+ if pregenerated_subscription_payloads is None:+ pregenerated_subscription_payloads = {}return self.__run_method_on_plugins("excluded_shipping_methods_for_checkout",[],checkout,available_shipping_methods,+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,channel_slug=channel.slug,)diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex b0ee232927..bf37f61eaf 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -3502,7 +3502,10 @@ class WebhookPlugin(BasePlugin):checkout: "Checkout",available_shipping_methods: list["ShippingMethodData"],previous_value: list[ExcludedShippingMethod],+ pregenerated_subscription_payloads: Optional[dict] = None,) -> list[ExcludedShippingMethod]:+ if pregenerated_subscription_payloads is None:+ pregenerated_subscription_payloads = {}generate_function = generate_excluded_shipping_methods_for_checkout_payloadpayload_function = lambda: generate_function( # noqa: E731checkout,@@ -3514,6 +3517,7 @@ class WebhookPlugin(BasePlugin):payload_fun=payload_function,subscribable_object=checkout,allow_replica=self.allow_replica,+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,)def is_event_active(self, event: str, channel=Optional[str]):diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex a5e5020c14..41b2fb520d 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -7,6 +7,7 @@ import pytestfrom ....core.models import EventDeliveryfrom ....graphql.tests.utils import get_graphql_content+from ....graphql.webhook.utils import get_subscription_query_hashfrom ....order import OrderStatusfrom ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIMEfrom ....webhook.event_types import WebhookEventSyncType@@ -131,6 +132,7 @@ def test_excluded_shipping_methods_for_order(timeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)expected_cache_key = generate_cache_key_for_webhook(payload_dict,@@ -222,6 +224,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(timeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)mocked_webhook.assert_any_call(event_type,@@ -232,7 +235,9 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(timeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)+ assert mocked_webhook.call_count == 2expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(payload_dict,shipping_webhook.target_url,@@ -351,6 +356,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ortimeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)mocked_webhook.assert_any_call(event_type,@@ -361,7 +367,9 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ortimeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)+ assert mocked_webhook.call_count == 2expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(payload_dict,@@ -691,7 +699,7 @@ def test_trigger_webhook_sync(mock_request, shipping_app):"saleor.plugins.webhook.plugin.""generate_excluded_shipping_methods_for_checkout_payload")-def test_excluded_shipping_methods_for_checkout_webhook(+def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_payload(mocked_payload,mocked_webhook,mocked_cache_set,@@ -750,6 +758,7 @@ def test_excluded_shipping_methods_for_checkout_webhook(timeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)expected_cache_key = generate_cache_key_for_webhook(payload_dict,@@ -765,6 +774,95 @@ def test_excluded_shipping_methods_for_checkout_webhook()[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,+ 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()++@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")def test_excluded_shipping_methods_for_checkout(mocked_webhook,@@ -890,6 +988,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(timeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)mocked_webhook.assert_any_call(event_type,@@ -900,7 +999,9 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(timeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)+ assert mocked_webhook.call_count == 2expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(payload_dict, shipping_webhook.target_url, event_type, shipping_app.id@@ -1019,6 +1120,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_chtimeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)mocked_webhook.assert_any_call(event_type,@@ -1029,7 +1131,9 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_chtimeout=settings.WEBHOOK_SYNC_TIMEOUT,request=None,requestor=None,+ pregenerated_subscription_payload=None,)+ assert mocked_webhook.call_count == 2expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(payload_dict, first_webhook.target_url, event_type, shipping_app.iddiff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.pyindex 82861c8d9c..8f6a83503d 100644--- a/saleor/webhook/transport/shipping.py+++ b/saleor/webhook/transport/shipping.py@@ -12,6 +12,7 @@ from ...app.models import Appfrom ...checkout.models import Checkoutfrom ...graphql.core.utils import from_global_id_or_errorfrom ...graphql.shipping.types import ShippingMethod+from ...graphql.webhook.utils import get_pregenerated_subscription_payloadfrom ...order.models import Orderfrom ...plugins.base_plugin import ExcludedShippingMethod, RequestorOrLazyObjectfrom ...settings import WEBHOOK_SYNC_TIMEOUT@@ -119,16 +120,22 @@ def get_excluded_shipping_methods_or_fetch(subscribable_object: Optional[Union["Order", "Checkout"]],allow_replica: bool,requestor: Optional[RequestorOrLazyObject],+ pregenerated_subscription_payloads: Optional[dict] = 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 alldefined 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 = []# Gather responses from webhooksfor 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,@@ -139,6 +146,7 @@ def get_excluded_shipping_methods_or_fetch(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(@@ -154,6 +162,7 @@ def get_excluded_shipping_data(subscribable_object: Optional[Union["Order", "Checkout"]],allow_replica: bool,requestor: Optional[RequestorOrLazyObject] = None,+ pregenerated_subscription_payloads: Optional[dict] = None,) -> list[ExcludedShippingMethod]:"""Exclude not allowed shipping methods by sync webhook.@@ -166,14 +175,21 @@ def get_excluded_shipping_data(The function will fetch the payload only in the case that we have any definedwebhook."""-+ 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+ webhooks,+ event_type,+ payload,+ subscribable_object,+ allow_replica,+ requestor,+ pregenerated_subscription_payloads,)# Gather responses for previous pluginsdiff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex 520a475889..4f2c66dfa1 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -181,6 +181,7 @@ def trigger_webhook_sync_if_not_cached(cache_timeout=None,request=None,requestor=None,+ pregenerated_subscription_payload: Optional[dict] = None,) -> Optional[dict]:"""Get response for synchronous webhook.@@ -202,6 +203,7 @@ def trigger_webhook_sync_if_not_cached(timeout=request_timeout,request=request,requestor=requestor,+ pregenerated_subscription_payload=pregenerated_subscription_payload,)if response_data is not None:cache.set(diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.pyindex 247bd04aaa..56b40478e2 100644--- a/saleor/webhook/utils.py+++ b/saleor/webhook/utils.py@@ -109,9 +109,19 @@ def get_webhooks_for_multiple_events(.prefetch_related("permissions__content_type").in_bulk())+ return calculate_webhooks_for_multiple_events(+ set_event_types, apps, list(webhooks), webhook_id_to_event_types_map+ )++def calculate_webhooks_for_multiple_events(+ set_event_types: set[str],+ app_by_id_map: dict[int, App],+ webhooks: list[Webhook],+ events_types_by_webhook_id_map: dict[int, set[str]],+) -> dict[str, set[Webhook]]:app_perm_map = {}- for app in apps.values():+ for app in app_by_id_map.values():app_perms = app.permissions.all()app_permission_codenames = [(permission.content_type.app_label, permission.codename)@@ -120,12 +130,12 @@ def get_webhooks_for_multiple_events(app_perm_map[app.id] = app_permission_codenamesactive_event_map = defaultdict(set)for webhook in webhooks:- if webhook.app_id not in apps:+ if webhook.app_id not in app_by_id_map:continue- app = apps[webhook.app_id]+ app = app_by_id_map[webhook.app_id]webhook.app = appapp_permissions = app_perm_map.get(webhook.app_id, [])- events = webhook_id_to_event_types_map.get(webhook.id, set())+ events = events_types_by_webhook_id_map.get(webhook.id, set())for event in events:required_permission = WebhookEventAsyncType.PERMISSIONS.get(event, WebhookEventSyncType.PERMISSIONS.get(event)