Skip to content

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

Extract shared filter shippingmethods webhook logic from checkout and order into unified module (#18850)

Maciej Korycinski6a4cf706b4cc
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index f07bda2b66..f18803cf84 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -768,8 +768,7 @@ def fetch_shipping_methods_for_checkout(
available_shipping_methods=all_methods,
allow_replica=allow_replica,
requestor=requestor,
- pregenerated_subscription_payloads=checkout_info.pregenerated_payloads_for_excluded_shipping_method,
- )
+ ).get()
initialize_shipping_method_active_status(all_methods, excluded_methods)
checkout_deliveries = {}
diff --git a/saleor/checkout/tests/test_fetch.py b/saleor/checkout/tests/test_fetch.py
index 82915e8f68..363438281f 100644
--- a/saleor/checkout/tests/test_fetch.py
+++ b/saleor/checkout/tests/test_fetch.py
@@ -5,6 +5,7 @@ import pytest
from django.utils import timezone
from freezegun import freeze_time
from prices import Money
+from promise import Promise
from ...product.models import ProductChannelListing, ProductVariantChannelListing
from ...shipping.interface import ExcludedShippingMethod, ShippingMethodData
@@ -662,12 +663,14 @@ def test_fetch_shipping_methods_for_checkout_with_excluded_built_in_shipping_met
# given
unavailable_shipping_method = ShippingMethod.objects.get()
exclude_reason = "This shipping method is not available."
- mocked_exclude_shipping_methods.return_value = [
- ExcludedShippingMethod(
- id=str(unavailable_shipping_method.id),
- reason=exclude_reason,
- )
- ]
+ mocked_exclude_shipping_methods.return_value = Promise.resolve(
+ [
+ ExcludedShippingMethod(
+ id=str(unavailable_shipping_method.id),
+ reason=exclude_reason,
+ )
+ ]
+ )
checkout = checkout_with_item
checkout.shipping_address = address
@@ -1039,6 +1042,7 @@ def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_external_sh
name="Old External Shipping name",
price_amount=Decimal(99),
currency="USD",
+ is_external=True,
)
checkout.shipping_address = address
checkout.delivery_methods_stale_at = timezone.now()
@@ -1104,12 +1108,14 @@ def test_fetch_shipping_methods_for_checkout_with_excluded_external_shipping_met
},
)
exclude_reason = "This shipping method is not available."
- mocked_exclude_shipping_methods.return_value = [
- ExcludedShippingMethod(
- id=str(unavailable_shipping_method.id),
- reason=exclude_reason,
- )
- ]
+ mocked_exclude_shipping_methods.return_value = Promise.resolve(
+ [
+ ExcludedShippingMethod(
+ id=str(unavailable_shipping_method.id),
+ reason=exclude_reason,
+ )
+ ]
+ )
mocked_list_shipping_methods.return_value = [unavailable_shipping_method]
@@ -1165,7 +1171,7 @@ def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_ship
},
)
- mocked_webhook.return_value = [available_shipping_method]
+ mocked_webhook.return_value = Promise.resolve([available_shipping_method])
new_shipping_price_amount = shipping_price_amount + Decimal(99)
checkout = checkout_with_item
diff --git a/saleor/checkout/tests/webhooks/test_exclude_shipping.py b/saleor/checkout/tests/webhooks/test_exclude_shipping.py
index 8c1c270278..fd18f75f46 100644
--- a/saleor/checkout/tests/webhooks/test_exclude_shipping.py
+++ b/saleor/checkout/tests/webhooks/test_exclude_shipping.py
@@ -8,24 +8,19 @@ import graphene
import pytest
from measurement.measures import Weight
from prices import Money
+from promise import Promise
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 ....shipping.webhooks.shared import CACHE_EXCLUDED_SHIPPING_TIME
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,
)
@@ -88,9 +83,9 @@ def test_checkout_deliveries(
excluded_shipping_method_id = (
checkout_ready_to_complete.assigned_delivery.shipping_method_id
)
- mocked_webhook.return_value = [
- ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
- ]
+ mocked_webhook.return_value = Promise.resolve(
+ [ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)]
+ )
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
# when
response = staff_api_client.post_graphql(
@@ -133,9 +128,9 @@ def test_checkout_available_shipping_methods(
excluded_shipping_method_id = (
checkout_ready_to_complete.assigned_delivery.shipping_method_id
)
- mocked_webhook.return_value = [
- ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
- ]
+ mocked_webhook.return_value = Promise.resolve(
+ [ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)]
+ )
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
# when
@@ -160,7 +155,7 @@ def test_checkout_deliveries_webhook_called_once(
permission_manage_checkouts,
):
# given
- mocked_webhook.side_effect = [[], AssertionError("called twice.")]
+ mocked_webhook.side_effect = [Promise.resolve([]), AssertionError("called twice.")]
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
# when
response = staff_api_client.post_graphql(
@@ -193,7 +188,9 @@ def test_get_cache_data_for_exclude_shipping_methods(checkout_with_items):
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
@mock.patch(
"saleor.checkout.webhooks.exclude_shipping."
"_generate_excluded_shipping_methods_for_checkout_payload"
@@ -221,7 +218,7 @@ def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_pay
]
}
- mocked_webhook.return_value = webhook_response
+ mocked_webhook.return_value = Promise.resolve(webhook_response)
payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
payload = json.dumps(payload_dict)
@@ -233,7 +230,7 @@ def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_pay
available_shipping_methods=available_shipping_methods,
allow_replica=False,
requestor=None,
- )
+ ).get()
# then
assert len(excluded_methods) == 1
em = excluded_methods[0]
@@ -242,14 +239,13 @@ def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_pay
mocked_webhook.assert_called_once_with(
WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
- payload,
shipping_webhook,
False,
+ static_payload=payload,
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,
@@ -266,16 +262,14 @@ def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_pay
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
- "saleor.checkout.webhooks.exclude_shipping."
- "_generate_excluded_shipping_methods_for_checkout_payload"
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
)
@mock.patch(
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+ "saleor.checkout.webhooks.exclude_shipping."
+ "_generate_excluded_shipping_methods_for_checkout_payload"
)
-def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_pregenerated_payload(
- mocked_subscription_payload,
+def test_excluded_shipping_methods_for_checkout_webhook_with_subscription(
mocked_static_payload,
mocked_webhook,
mocked_cache_set,
@@ -298,11 +292,9 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_p
]
}
- mocked_webhook.return_value = webhook_response
+ mocked_webhook.return_value = Promise.resolve(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
@@ -312,8 +304,7 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_p
available_shipping_methods=available_shipping_methods,
allow_replica=False,
requestor=None,
- pregenerated_subscription_payloads=pregenerated_payloads,
- )
+ ).get()
# then
assert len(excluded_methods) == 1
em = excluded_methods[0]
@@ -322,14 +313,13 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_p
mocked_webhook.assert_called_once_with(
WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
- payload,
shipping_webhook,
False,
+ static_payload=payload,
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,
@@ -343,11 +333,12 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_p
webhook_response,
timeout=CACHE_EXCLUDED_SHIPPING_TIME,
)
- mocked_subscription_payload.assert_not_called()
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
@mock.patch(
"saleor.checkout.webhooks.exclude_shipping."
"_generate_excluded_shipping_methods_for_checkout_payload"
@@ -393,7 +384,10 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
]
}
- mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]
+ mocked_webhook.side_effect = [
+ Promise.resolve(first_webhook_response),
+ Promise.resolve(second_webhook_response),
+ ]
payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
payload = json.dumps(payload_dict)
@@ -405,7 +399,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
available_shipping_methods=available_shipping_methods,
allow_replica=False,
requestor=None,
- )
+ ).get()
# then
assert len(excluded_methods) == 2
@@ -416,25 +410,23 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
mocked_webhook.assert_any_call(
event_type,
- payload,
shipping_webhook,
False,
+ static_payload=payload,
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,
+ static_payload=payload,
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
@@ -467,7 +459,9 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
@mock.patch(
"saleor.checkout.webhooks.exclude_shipping."
"_generate_excluded_shipping_methods_for_checkout_payload"
@@ -521,7 +515,10 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
]
}
- mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]
+ mocked_webhook.side_effect = [
+ Promise.resolve(first_webhook_response),
+ Promise.resolve(second_webhook_response),
+ ]
payload_dict = {"checkout": {"id": 1, "some_field": "12"}}
payload = json.dumps(payload_dict)
@@ -533,7 +530,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
available_shipping_methods=available_shipping_methods,
allow_replica=False,
requestor=None,
- )
+ ).get()
# then
assert len(excluded_methods) == 2
@@ -544,25 +541,23 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
mocked_webhook.assert_any_call(
event_type,
- payload,
first_webhook,
False,
+ static_payload=payload,
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,
+ static_payload=payload,
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
@@ -590,118 +585,6 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
)
- "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
-
-
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_excluded_shipping_methods_for_checkout(
mocked_webhook,
@@ -727,7 +610,7 @@ def test_excluded_shipping_methods_for_checkout(
available_shipping_methods=available_shipping_methods,
allow_replica=False,
requestor=None,
- )
+ ).get()
# then
assert len(excluded_methods) == 1
diff --git a/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py b/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py
index 28bdb46e8b..45dc29738d 100644
--- a/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py
+++ b/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py
@@ -9,10 +9,10 @@ from measurement.measures import Weight
from prices import Money
from ....shipping.interface import ShippingMethodData
+from ....shipping.webhooks.shared import CACHE_EXCLUDED_SHIPPING_TIME
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.transport.utils import generate_cache_key_for_webhook
from ...webhooks.exclude_shipping import (
- CACHE_EXCLUDED_SHIPPING_TIME,
excluded_shipping_methods_for_checkout,
)
diff --git a/saleor/checkout/webhooks/exclude_shipping.py b/saleor/checkout/webhooks/exclude_shipping.py
index 22739d36bd..3ca3d6b997 100644
--- a/saleor/checkout/webhooks/exclude_shipping.py
+++ b/saleor/checkout/webhooks/exclude_shipping.py
@@ -1,31 +1,21 @@
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 promise import Promise
-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 ...shipping.webhooks.shared import (
+ generate_payload_for_shipping_method,
+ get_excluded_shipping_data,
+)
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
@@ -35,50 +25,38 @@ if TYPE_CHECKING:
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 = {}
+) -> "Promise[list[ExcludedShippingMethod]]":
if not available_shipping_methods:
- return []
+ return Promise.resolve([])
- generate_function = _generate_excluded_shipping_methods_for_checkout_payload
- payload_function = lambda: generate_function( # noqa: E731
+ webhooks = get_webhooks_for_event(
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ )
+ if not webhooks:
+ return Promise.resolve([])
+
+ static_payload = _generate_excluded_shipping_methods_for_checkout_payload(
checkout,
available_shipping_methods,
)
- return _get_excluded_shipping_data(
+ cache_data = _get_cache_data_for_exclude_shipping_methods(static_payload)
+ return get_excluded_shipping_data(
+ webhooks=webhooks,
event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
- payload_fun=payload_function,
+ static_payload=static_payload,
subscribable_object=(checkout, available_shipping_methods),
allow_replica=allow_replica,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
requestor=requestor,
+ cache_data=cache_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(
@@ -89,101 +67,13 @@ def _generate_excluded_shipping_methods_for_checkout_payload(
payload = {
"checkout": checkout_data,
"shipping_methods": [
- _generate_payload_for_shipping_method(shipping_method)
+ 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", {}))
@@ -193,39 +83,3 @@ def _get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:
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_methods
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 1b66ab58cb..fba58cb922 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
@@ -7,6 +7,7 @@ import graphene
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
+from promise import Promise
from .....account.models import Address
from .....checkout.actions import call_checkout_info_event
@@ -289,9 +290,9 @@ def test_checkout_shipping_method_update_excluded_webhook(
checkout.save(update_fields=["shipping_address"])
query = MUTATION_UPDATE_SHIPPING_METHOD
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
- mocked_webhook.return_value = [
- ExcludedShippingMethod(shipping_method.id, webhook_reason)
- ]
+ mocked_webhook.return_value = Promise.resolve(
+ [ExcludedShippingMethod(shipping_method.id, webhook_reason)]
+ )
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index c7a7d28ae3..95c0bd387a 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -485,7 +485,7 @@ query getCheckout($id: ID) {
"""
[email protected]("saleor.checkout.webhooks.exclude_shipping._get_excluded_shipping_data")
[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,
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
index 0d42f261a5..e1f6820b05 100644
--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
@@ -3,6 +3,7 @@ from unittest import mock
from django.test import override_settings
from django.utils import timezone
+from promise import Promise
from .....shipping.models import ShippingMethod
from ....core.utils import to_global_id_or_none
@@ -404,9 +405,11 @@ def test_checkout_line_total_price_use_pregenerated_payload(
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
)
def test_shipping_methods_use_pregenerated_payload(
mock_generate_payload,
@@ -439,14 +442,16 @@ def test_shipping_methods_use_pregenerated_payload(
"""
variables = {"id": checkout_global_id}
- mock_request.return_value = {
- "excluded_methods": [
- {
- "id": shipping_method_global_ids[1],
- "reason": exclude_msg,
- },
- ]
- }
+ mock_request.return_value = Promise.resolve(
+ {
+ "excluded_methods": [
+ {
+ "id": shipping_method_global_ids[1],
+ "reason": exclude_msg,
+ },
+ ]
+ }
+ )
# when
response = api_client.post_graphql(checkout_shipping_query, variables)
@@ -477,9 +482,11 @@ def test_shipping_methods_use_pregenerated_payload(
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
)
def test_available_shipping_methods_use_pregenerated_payload(
mock_generate_payload,
@@ -512,14 +519,16 @@ def test_available_shipping_methods_use_pregenerated_payload(
"""
variables = {"id": checkout_global_id}
- mock_request.return_value = {
- "excluded_methods": [
- {
- "id": shipping_method_global_ids[1],
- "reason": exclude_msg,
- },
- ]
- }
+ mock_request.return_value = Promise.resolve(
+ {
+ "excluded_methods": [
+ {
+ "id": shipping_method_global_ids[1],
+ "reason": exclude_msg,
+ },
+ ]
+ }
+ )
# when
response = api_client.post_graphql(checkout_shipping_query, variables)
@@ -541,9 +550,11 @@ def test_available_shipping_methods_use_pregenerated_payload(
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")
@mock.patch(
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
)
def test_shipping_methods_and_taxes_use_pregenerated_payload(
mock_generate_payload,
@@ -589,14 +600,16 @@ def test_shipping_methods_and_taxes_use_pregenerated_payload(
"""
variables = {"id": checkout_global_id}
- mock_shipping_request.return_value = {
- "excluded_methods": [
- {
- "id": shipping_method_global_ids[1],
- "reason": exclude_msg,
- },
- ]
- }
+ mock_shipping_request.return_value = Promise.resolve(
+ {
+ "excluded_methods": [
+ {
+ "id": shipping_method_global_ids[1],
+ "reason": exclude_msg,
+ },
+ ]
+ }
+ )
mock_tax_request.return_value = TAX_DATA_RESPONSE
# when
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.py
index db0064e688..b3d7eb8757 100644
--- 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.py
@@ -1,6 +1,7 @@
from unittest import mock
from django.test import override_settings
+from promise import Promise
from .....shipping.models import ShippingMethod
from ....core.utils import to_global_id_or_none
@@ -8,9 +9,11 @@ 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")
@mock.patch(
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
)
def test_shipping_methods_use_pregenerated_payloads_app_without_subscription(
mock_generate_payload,
@@ -43,14 +46,16 @@ def test_shipping_methods_use_pregenerated_payloads_app_without_subscription(
"""
variables = {"id": checkout_global_id}
- mock_request.return_value = {
- "excluded_methods": [
- {
- "id": shipping_method_global_ids[1],
- "reason": exclude_msg,
- },
- ]
- }
+ mock_request.return_value = Promise.resolve(
+ {
+ "excluded_methods": [
+ {
+ "id": shipping_method_global_ids[1],
+ "reason": exclude_msg,
+ },
+ ]
+ }
+ )
# when
response = api_client.post_graphql(checkout_shipping_query, variables)
diff --git a/saleor/order/tests/webhooks/test_exclude_shipping.py b/saleor/order/tests/webhooks/test_exclude_shipping.py
index 81f0677de1..831ecc35e7 100644
--- a/saleor/order/tests/webhooks/test_exclude_shipping.py
+++ b/saleor/order/tests/webhooks/test_exclude_shipping.py
@@ -12,13 +12,11 @@ from promise import Promise
from ....core.prices import quantize_price
from ....shipping.interface import ShippingMethodData
+from ....shipping.webhooks.shared import CACHE_EXCLUDED_SHIPPING_TIME
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
-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,
- _get_excluded_shipping_methods_from_response,
excluded_shipping_methods_for_order,
generate_excluded_shipping_methods_for_order_payload,
)
@@ -61,31 +59,7 @@ def available_shipping_methods():
return methods
[email protected]("saleor.order.webhooks.exclude_shipping._get_excluded_shipping_data")
-def test_excluded_shipping_methods_for_order_run_webhook_when_shipping_methods_provided(
- mocked_get_excluded_shipping_data, draft_order
-):
- # given
- shipping_method = ShippingMethodData(
- id="123",
- price=Money(Decimal("10.59"), "USD"),
- )
-
- non_empty_shipping_methods = [shipping_method]
-
- # when
- excluded_shipping_methods_for_order(
- order=draft_order,
- available_shipping_methods=non_empty_shipping_methods,
- allow_replica=False,
- requestor=None,
- ).get()
-
- # then
- mocked_get_excluded_shipping_data.assert_called_once()
-
-
[email protected]("saleor.order.webhooks.exclude_shipping._get_excluded_shipping_data")
[email protected]("saleor.order.webhooks.exclude_shipping.get_excluded_shipping_data")
def test_excluded_shipping_methods_for_order_dont_run_webhook_on_missing_shipping_methods(
mocked_get_excluded_shipping_data, draft_order
):
@@ -513,65 +487,6 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
)
-def test_parse_excluded_shipping_methods_response(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
-
-
-def test_parse_excluded_shipping_methods_response_invalid(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
-
-
def test_generate_excluded_shipping_methods_for_order_payload(
order_with_lines,
available_shipping_methods,
diff --git a/saleor/order/tests/webhooks/test_exclude_shipping_cache.py b/saleor/order/tests/webhooks/test_exclude_shipping_cache.py
index e5045970c5..49a0cae0a5 100644
--- a/saleor/order/tests/webhooks/test_exclude_shipping_cache.py
+++ b/saleor/order/tests/webhooks/test_exclude_shipping_cache.py
@@ -10,10 +10,10 @@ from prices import Money
from ....core.prices import quantize_price
from ....shipping.interface import ShippingMethodData
+from ....shipping.webhooks.shared import CACHE_EXCLUDED_SHIPPING_TIME
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.transport.utils import generate_cache_key_for_webhook
from ...webhooks.exclude_shipping import (
- CACHE_EXCLUDED_SHIPPING_TIME,
excluded_shipping_methods_for_order,
)
diff --git a/saleor/order/webhooks/exclude_shipping.py b/saleor/order/webhooks/exclude_shipping.py
index b4efb7c9bc..c1ca296120 100644
--- a/saleor/order/webhooks/exclude_shipping.py
+++ b/saleor/order/webhooks/exclude_shipping.py
@@ -1,30 +1,22 @@
import json
import logging
-from collections import defaultdict
-from typing import TYPE_CHECKING, Any, Union
+from typing import TYPE_CHECKING, Union
-from django.conf import settings
-from django.db.models import QuerySet
from promise import Promise
-from pydantic import ValidationError
from ...core.db.connection import allow_writer
from ...core.prices import quantize_price
from ...core.utils.json_serializer import CustomJsonEncoder
from ...shipping.interface import ExcludedShippingMethod, ShippingMethodData
+from ...shipping.webhooks.shared import (
+ generate_payload_for_shipping_method,
+ get_excluded_shipping_data,
+)
from ...webhook import traced_payload_generator
from ...webhook.event_types import WebhookEventSyncType
-from ...webhook.models import Webhook
from ...webhook.payloads import (
generate_order_payload,
)
-from ...webhook.response_schemas.shipping import (
- ExcludedShippingMethodSchema,
- FilterShippingMethodsSchema,
-)
-from ...webhook.transport.synchronous.transport import (
- trigger_webhook_sync_promise_if_not_cached,
-)
from ...webhook.utils import get_webhooks_for_event
if TYPE_CHECKING:
@@ -37,20 +29,6 @@ CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3
logger = logging.getLogger(__name__)
-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_order_payload(
@@ -77,15 +55,25 @@ def excluded_shipping_methods_for_order(
if not available_shipping_methods:
return Promise.resolve([])
- return _get_excluded_shipping_data(
+ webhooks = get_webhooks_for_event(
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ )
+ if not webhooks:
+ return Promise.resolve([])
+
+ static_payload = generate_excluded_shipping_methods_for_order_payload(
+ order,
+ available_shipping_methods,
+ )
+ cache_data = _get_cache_data_for_exclude_shipping_methods(order, static_payload)
+ return get_excluded_shipping_data(
+ webhooks=webhooks,
event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
- static_payload=generate_excluded_shipping_methods_for_order_payload(
- order,
- available_shipping_methods,
- ),
+ static_payload=static_payload,
subscribable_object=(order, available_shipping_methods),
allow_replica=allow_replica,
requestor=requestor,
+ cache_data=cache_data,
)
@@ -140,131 +128,3 @@ def _get_cache_data_for_exclude_shipping_methods(order: "Order", payload: str) -
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,
- static_payload: str,
- subscribable_object: tuple["Order", list["ShippingMethodData"]],
- allow_replica: bool,
- requestor: Union["App", "User", None],
-) -> Promise[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.
- """
- order, _ = subscribable_object
- cache_data = _get_cache_data_for_exclude_shipping_methods(order, static_payload)
- # Gather responses from webhooks
- promised_responses = []
- for webhook in webhooks:
- promised_responses.append(
- trigger_webhook_sync_promise_if_not_cached(
- event_type=event_type,
- static_payload=static_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,
- )
- )
-
- def process_responses(
- responses: list[Any],
- ) -> dict[str, list[ExcludedShippingMethod]]:
- excluded_methods: list[ExcludedShippingMethodSchema] = []
- for response_data, webhook in zip(responses, webhooks, strict=True):
- 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)
-
- return Promise.all(promised_responses).then(process_responses)
-
-
-def _get_excluded_shipping_data(
- event_type: str,
- static_payload: str,
- subscribable_object: tuple["Order", list["ShippingMethodData"]],
- allow_replica: bool,
- requestor: Union["App", "User", None],
-) -> Promise[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.
- """
- webhooks = get_webhooks_for_event(event_type)
- if webhooks:
- promised_excluded_methods_map = _get_excluded_shipping_methods_or_fetch(
- webhooks,
- event_type,
- static_payload,
- subscribable_object,
- allow_replica,
- requestor,
- )
- else:
- promised_excluded_methods_map = Promise.resolve({})
-
- def merge_excluded_methods_map(
- excluded_methods_map: dict[str, list[ExcludedShippingMethod]],
- ) -> list[ExcludedShippingMethod]:
- # 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
-
- return promised_excluded_methods_map.then(merge_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_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
diff --git a/saleor/shipping/tests/webhooks/__init__.py b/saleor/shipping/tests/webhooks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/shipping/tests/webhooks/test_shared.py b/saleor/shipping/tests/webhooks/test_shared.py
new file mode 100644
index 0000000000..5cc1da214b
--- /dev/null
+++ b/saleor/shipping/tests/webhooks/test_shared.py
@@ -0,0 +1,124 @@
+from unittest import mock
+
+import graphene
+from promise import Promise
+
+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 ...webhooks.shared import (
+ _get_excluded_shipping_methods_from_response,
+ _get_excluded_shipping_methods_or_fetch,
+)
+
+
[email protected](annotations_logger, "warning")
[email protected](schema_logger, "warning")
+def test_get_excluded_shipping_methods_from_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
+ assert mocked_schema_logger.call_count == 3
+ assert mocked_annotations_logger.call_count == 3
+
+
[email protected](annotations_logger, "warning")
[email protected](schema_logger, "warning")
+def test_get_excluded_shipping_methods_from_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.shipping.webhooks.shared._parse_excluded_shipping_methods")
+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"
+)
+ "saleor.shipping.webhooks.shared._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 = Promise.resolve(["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, {}
+ ).get()
+
+ # then
+ mocked_get_excluded.assert_not_called()
+ mocked_parse.assert_called_once_with([])
diff --git a/saleor/shipping/webhooks/__init__.py b/saleor/shipping/webhooks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/shipping/webhooks/shared.py b/saleor/shipping/webhooks/shared.py
new file mode 100644
index 0000000000..59185a0472
--- /dev/null
+++ b/saleor/shipping/webhooks/shared.py
@@ -0,0 +1,165 @@
+import logging
+from collections import defaultdict
+from typing import TYPE_CHECKING, Any, Union
+
+from django.conf import settings
+from django.db.models import QuerySet
+from promise import Promise
+from pydantic import ValidationError
+
+from ...webhook.models import Webhook
+from ...webhook.response_schemas.shipping import (
+ ExcludedShippingMethodSchema,
+ FilterShippingMethodsSchema,
+)
+from ...webhook.transport.synchronous.transport import (
+ trigger_webhook_sync_promise_if_not_cached,
+)
+from ..interface import ExcludedShippingMethod, ShippingMethodData
+
+if TYPE_CHECKING:
+ from ...account.models import User
+ from ...app.models import App
+ from ...checkout.models import Checkout
+ from ...order.models import Order
+
+CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3
+
+logger = logging.getLogger(__name__)
+
+
+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
+
+
+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_excluded_shipping_methods_or_fetch(
+ webhooks: QuerySet,
+ event_type: str,
+ static_payload: str,
+ subscribable_object: "tuple[Order | Checkout, list[ShippingMethodData]]",
+ allow_replica: bool,
+ requestor: Union["App", "User", None],
+ cache_data: dict,
+) -> "Promise[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.
+ """
+ promised_responses = []
+ for webhook in webhooks:
+ promised_responses.append(
+ trigger_webhook_sync_promise_if_not_cached(
+ event_type=event_type,
+ static_payload=static_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,
+ )
+ )
+
+ def process_responses(
+ responses: list[Any],
+ ) -> dict[str, list[ExcludedShippingMethod]]:
+ excluded_methods: list[ExcludedShippingMethodSchema] = []
+ for response_data, webhook in zip(responses, webhooks, strict=True):
+ 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)
+
+ return Promise.all(promised_responses).then(process_responses)
+
+
+def get_excluded_shipping_data(
+ webhooks: QuerySet[Webhook],
+ event_type: str,
+ static_payload: str,
+ subscribable_object: "tuple[Order | Checkout, list[ShippingMethodData]]",
+ allow_replica: bool,
+ requestor: Union["App", "User", None],
+ cache_data: dict,
+) -> "Promise[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.
+ """
+
+ def merge_excluded_methods_map(
+ excluded_methods_map: dict[str, list[ExcludedShippingMethod]],
+ ) -> list[ExcludedShippingMethod]:
+ 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
+
+ return _get_excluded_shipping_methods_or_fetch(
+ webhooks,
+ event_type,
+ static_payload,
+ subscribable_object,
+ allow_replica,
+ requestor,
+ cache_data=cache_data,
+ ).then(merge_excluded_methods_map)
diff --git a/saleor/webhook/transport/shipping_helpers.py b/saleor/webhook/transport/shipping_helpers.py
index c8ba25fa4d..1791bcd6d0 100644
--- a/saleor/webhook/transport/shipping_helpers.py
+++ b/saleor/webhook/transport/shipping_helpers.py
@@ -9,24 +9,3 @@ def to_shipping_app_id(app: App, shipping_method_id: str) -> str:
return base64.b64encode(
str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}")
).decode("utf-8")
-
-
-def convert_to_app_id_with_identifier(shipping_app_id: str) -> None | str:
- """Prepare the shipping_app_id in format `app:<app-identifier>:method_id>`.
-
- The format of shipping_app_id has been changes so we need to support both of them.
- This method is preparing the new shipping_app_id format based on assumptions
- that right now the old one is used which is `app:<app-pk>:<method_id>`
- """
- decoded_id = base64.b64decode(shipping_app_id).decode()
- splitted_id = decoded_id.split(":")
- if len(splitted_id) != 3:
- return None
- try:
- app_id = int(splitted_id[1])
- except (TypeError, ValueError):
- return None
- app = App.objects.filter(id=app_id).first()
- if app is None:
- return None
- return to_shipping_app_id(app, splitted_id[2])