Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add tests for exclude-shipping-for-order on Promise (#18719) (#18781)
Maciej Korycinski24fe545e1aad
diff --git a/saleor/app/tests/fixtures/app.py b/saleor/app/tests/fixtures/app.pyindex 0172816bdc..e6240f7984 100644--- a/saleor/app/tests/fixtures/app.py+++ b/saleor/app/tests/fixtures/app.py@@ -3,6 +3,8 @@ from django.utils import timezonefrom ....app.models import Appfrom ....app.types import AppType+from ....webhook.event_types import WebhookEventSyncType+from ....webhook.models import Webhook, WebhookEvent@pytest.fixture@@ -100,3 +102,57 @@ def apps_without_webhooks(db):App(name="App4", is_active=False),])+++def app_exclude_shipping_for_order(+ db,+ permission_manage_orders,+ permission_manage_checkouts,+):+ app = App.objects.create(name="Shipping App", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_orders)+ app.permissions.add(permission_manage_checkouts)++ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ webhook=webhook,+ ),+ ]+ )+ return app+++def second_app_exclude_shipping_for_order(+ db,+ permission_manage_orders,+ permission_manage_checkouts,+):+ app = App.objects.create(name="Second Shipping App", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_orders)+ app.permissions.add(permission_manage_checkouts)++ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway2.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ webhook=webhook,+ ),+ ]+ )+ return appdiff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex 4ea83a479b..0a5c27ec45 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -1,5 +1,3 @@-from typing import cast-import graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transaction@@ -121,7 +119,7 @@ class DraftOrderComplete(BaseMutation):cls, _root, info: ResolveInfo, /, *, id: str):user = info.context.user- user = cast(User, user)+ app = get_app_promise(info.context).get()manager = get_plugin_manager_promise(info.context).get()order = cls.get_node_or_error(@@ -143,7 +141,9 @@ class DraftOrderComplete(BaseMutation):cls.validate_order(order)country = get_order_country(order)- validate_draft_order(order, order.lines.all(), country, manager)+ validate_draft_order(+ order, order.lines.all(), country, requestor=app or user+ ).get()with traced_atomic_transaction():update_fields = ["status",@@ -237,7 +237,7 @@ class DraftOrderComplete(BaseMutation):payment=order.get_last_payment(),lines_data=order_lines_info,)- app = get_app_promise(info.context).get()+transaction.on_commit(lambda: store_user_addresses_from_draft_order(order=order,diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 224be4a199..854ea3d52d 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -413,8 +413,11 @@ class DraftOrderCreate(ShippingMethodUpdateMixin.clear_shipping_method_from_order(instance)else:ShippingMethodUpdateMixin.process_shipping_method(- instance, method, manager, update_shipping_discount=False- )+ instance,+ method,+ requestor=app or info.context.user,+ update_shipping_discount=False,+ ).get()if "voucher" in cleaned_input:cls.handle_order_voucher(diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.pyindex a37347231a..751cb7dd53 100644--- a/saleor/graphql/order/mutations/draft_order_update.py+++ b/saleor/graphql/order/mutations/draft_order_update.py@@ -35,6 +35,7 @@ from ...meta.inputs import MetadataInputfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ...shipping.utils import get_shipping_model_by_object_idfrom ...site.dataloaders import get_site_promise+from ...utils import get_user_or_app_from_contextfrom ..types import Orderfrom . import draft_order_cleanerfrom .draft_order_create import DraftOrderInput@@ -359,7 +360,7 @@ class DraftOrderUpdate(release_voucher_code_usage(voucher_code, old_voucher, user_email=None)@classmethod- def handle_shipping(cls, cleaned_input, instance: models.Order, manager):+ def handle_shipping(cls, cleaned_input, instance: models.Order, info):if "shipping_method" not in cleaned_input:return@@ -368,8 +369,11 @@ class DraftOrderUpdate(ShippingMethodUpdateMixin.clear_shipping_method_from_order(instance)else:ShippingMethodUpdateMixin.process_shipping_method(- instance, method, manager, update_shipping_discount=True- )+ instance,+ method,+ requestor=get_user_or_app_from_context(info.context),+ update_shipping_discount=True,+ ).get()@classmethoddef handle_metadata(cls, instance: models.Order, cleaned_input):@@ -420,7 +424,7 @@ class DraftOrderUpdate(cls.clean_instance(info, instance)manager = get_plugin_manager_promise(info.context).get()- cls.handle_shipping(cleaned_input, instance, manager)+ cls.handle_shipping(cleaned_input, instance, info)cls.handle_order_voucher(cleaned_input, instance, old_voucher, old_voucher_code)order_modified, metadata_modified = cls._save(diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.pyindex 05c93d553f..a7e3b6fb1f 100644--- a/saleor/graphql/order/mutations/order_update_shipping.py+++ b/saleor/graphql/order/mutations/order_update_shipping.py@@ -17,6 +17,7 @@ from ...core.mutations import BaseMutationfrom ...core.types import BaseInputObjectType, OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ...shipping.types import ShippingMethod+from ...utils import get_user_or_app_from_contextfrom ..types import Orderfrom .utils import (SHIPPING_METHOD_UPDATE_FIELDS,@@ -140,8 +141,11 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):)manager = get_plugin_manager_promise(info.context).get()ShippingMethodUpdateMixin.process_shipping_method(- order, method, manager, update_shipping_discount=True- )+ order,+ method,+ requestor=get_user_or_app_from_context(info.context),+ update_shipping_discount=True,+ ).get()order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)# Post-process the resultsdiff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.pyindex ea3a3c2ee1..26eaea7466 100644--- a/saleor/graphql/order/mutations/utils.py+++ b/saleor/graphql/order/mutations/utils.py@@ -1,8 +1,9 @@-from typing import NamedTuple+from typing import TYPE_CHECKING, NamedTuple, Unionimport graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationError+from promise import Promisefrom ....checkout.fetch import get_variant_channel_listingfrom ....core.taxes import zero_money, zero_taxed_money@@ -16,7 +17,6 @@ from ....order.error_codes import OrderErrorCodefrom ....order.utils import invalidate_order_pricesfrom ....payment import PaymentErrorfrom ....payment import models as payment_models-from ....plugins.manager import PluginsManagerfrom ....product import models as product_modelsfrom ....shipping.interface import ShippingMethodDatafrom ....shipping.models import ShippingMethod, ShippingMethodChannelListing@@ -25,6 +25,10 @@ from ....webhook.event_types import WebhookEventAsyncTypefrom ...meta.mutations.utils import update_metadata, update_private_metadatafrom ..utils import get_shipping_method_availability_error+if TYPE_CHECKING:+ from ....account.models import User+ from ....app.models import App+DRAFT_ORDER_UPDATE_FIELDS = {"base_shipping_price_amount","billing_address",@@ -193,40 +197,59 @@ class ShippingMethodUpdateMixin:cls,order: models.Order,method: ShippingMethod,- manager: "PluginsManager",+ requestor: Union["App", "User", None],update_shipping_discount: bool,- ):+ ) -> Promise[None]:shipping_channel_listing = cls.validate_shipping_channel_listing(method, order)++ promised_clean_shipping = Promise.resolve(None)if order.status != OrderStatus.DRAFT:shipping_method_data = convert_to_shipping_method_data(method,shipping_channel_listing,)- clean_order_update_shipping(order, shipping_method_data, manager)- cls.update_shipping_method(order, method)- cls.assign_shipping_price(order, shipping_channel_listing)- # for new instance the shipping discount is created later- if update_shipping_discount:- cls.update_shipping_discount(order)+ promised_clean_shipping = clean_order_update_shipping(+ order, shipping_method_data, requestor+ )++ def update_shipping(_):+ cls.update_shipping_method(order, method)+ cls.assign_shipping_price(order, shipping_channel_listing)+ # for new instance the shipping discount is created later+ if update_shipping_discount:+ cls.update_shipping_discount(order)++ return promised_clean_shipping.then(update_shipping)def clean_order_update_shipping(- order, method: ShippingMethodData, manager: "PluginsManager"-):- if not order.shipping_address:- raise ValidationError(- {- "order": ValidationError(- "Cannot choose a shipping method for an order without "- "the shipping address.",- code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value,- )- }+ order,+ method: ShippingMethodData,+ requestor: Union["App", "User", None],+) -> Promise[None]:+ def check_shipping(_):+ if not order.shipping_address_id:+ raise ValidationError(+ {+ "order": ValidationError(+ "Cannot choose a shipping method for an order without "+ "the shipping address.",+ code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value,+ )+ }+ )++ promised_availability_error = get_shipping_method_availability_error(+ order, method, requestor)- error = get_shipping_method_availability_error(order, method, manager)- if error:- raise ValidationError({"shipping_method": error})+ def handle_availability_error(error):+ if error:+ raise ValidationError({"shipping_method": error})++ return promised_availability_error.then(handle_availability_error)++ return Promise.resolve(None).then(check_shipping)def call_event_by_order_status(order, manager):diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 55f9f11590..a13091d4e1 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -9,6 +9,7 @@ from django.test import override_settingsfrom django.utils import timezonefrom freezegun import freeze_timefrom prices import Money, TaxedMoney+from promise import Promisefrom .....core import EventDeliveryStatusfrom .....core.models import EventDelivery@@ -786,7 +787,7 @@ def test_draft_order_complete_not_available_shipping_method(assert {error["field"] for error in data["errors"]} == {"shipping", "lines"}-@patch("saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_order")+@patch("saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order")def test_draft_order_complete_with_excluded_shipping_method(mocked_webhook,draft_order,@@ -798,9 +799,9 @@ def test_draft_order_complete_with_excluded_shipping_method(permission_group_manage_orders.user_set.add(staff_api_client.user)settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]webhook_reason = "archives-are-incomplete"- mocked_webhook.return_value = [- ExcludedShippingMethod(str(shipping_method.id), webhook_reason)- ]+ mocked_webhook.return_value = Promise.resolve(+ [ExcludedShippingMethod(str(shipping_method.id), webhook_reason)]+ )order = draft_orderorder.status = OrderStatus.DRAFTorder.shipping_method = shipping_method@@ -817,7 +818,7 @@ def test_draft_order_complete_with_excluded_shipping_method(assert data["errors"][0]["field"] == "shipping"-@patch("saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_order")+@patch("saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order")def test_draft_order_complete_with_not_excluded_shipping_method(mocked_webhook,draft_order,@@ -831,9 +832,9 @@ def test_draft_order_complete_with_not_excluded_shipping_method(webhook_reason = "archives-are-incomplete"other_shipping_method_id = "1337"assert other_shipping_method_id != shipping_method.id- mocked_webhook.return_value = [- ExcludedShippingMethod(other_shipping_method_id, webhook_reason)- ]+ mocked_webhook.return_value = Promise.resolve(+ [ExcludedShippingMethod(other_shipping_method_id, webhook_reason)]+ )order = draft_orderorder.status = OrderStatus.DRAFTorder.shipping_method = shipping_method@@ -877,8 +878,8 @@ def test_draft_order_complete_builtin_shipping_method_metadata_denormalization(shipping_method.metadata = {}shipping_method.save()- with race_condition.RunAfter(- "saleor.graphql.order.mutations.draft_order_complete.get_app_promise",+ with race_condition.RunBefore(+ "saleor.graphql.order.mutations.draft_order_complete.OrderInfo",clear_shipping_metadata,):response = staff_api_client.post_graphql(diff --git a/saleor/graphql/order/tests/queries/test_draft_order.py b/saleor/graphql/order/tests/queries/test_draft_order.pyindex a6e2b8b360..9f9892594e 100644--- a/saleor/graphql/order/tests/queries/test_draft_order.py+++ b/saleor/graphql/order/tests/queries/test_draft_order.py@@ -15,7 +15,6 @@ from .....order.events import (from .....order.models import Orderfrom .....order.search import prepare_order_search_vector_valuefrom .....payment.models import Payment-from .....plugins.manager import PluginsManagerfrom .....tax.calculations.order import update_order_prices_with_flat_ratesfrom ....tests.utils import assert_no_permission, get_graphql_contentfrom .shared_query_fragments import ORDER_FRAGMENT_WITH_WEBHOOK_RELATED_FIELDS@@ -349,7 +348,7 @@ def test_query_orders_for_order_with_events_when_tax_app_active(mocked_calculate_prices.assert_not_called()[email protected](PluginsManager, "excluded_shipping_methods_for_order")+@patch("saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order")def test_query_draft_orders_with_active_filter_shipping_methods_webhook(mocked_webhook_handler,settings,diff --git a/saleor/graphql/order/tests/queries/test_order_excluded_shipping_methods.py b/saleor/graphql/order/tests/queries/test_order_excluded_shipping_methods.pynew file mode 100644index 0000000000..8e9615a2a6--- /dev/null+++ b/saleor/graphql/order/tests/queries/test_order_excluded_shipping_methods.py@@ -0,0 +1,187 @@+from unittest import mock++import pytest+from promise import Promise++from .....order import OrderStatus+from .....order.webhooks.exclude_shipping import ExcludedShippingMethod+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content++ORDER_QUERY_SHIPPING_METHOD = """+query OrderQuery($id: ID) {+ order(id: $id) {+ shippingMethods {+ id+ name+ active+ message+ }+ availableShippingMethods {+ id+ name+ active+ message+ }+ }+}+"""+++ "saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order"+)+def test_order_shipping_methods(+ mocked_webhook,+ staff_api_client,+ order_with_lines,+ permission_group_manage_orders,+ settings,+):+ # given+ order_with_lines.status = OrderStatus.UNCONFIRMED+ order_with_lines.save(update_fields=["status"])+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ webhook_reason = "spanish-inquisition"+ excluded_shipping_method_id = str(order_with_lines.shipping_method.id)+ mocked_webhook.return_value = Promise.resolve(+ [ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)]+ )+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ # when+ response = staff_api_client.post_graphql(+ ORDER_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(order_with_lines)},+ )+ content = get_graphql_content(response)+ order_data = content["data"]["order"]++ shipping_methods = order_data["shippingMethods"]+ # then+ assert len(shipping_methods) == 1+ assert not shipping_methods[0]["active"]+ assert shipping_methods[0]["message"] == webhook_reason+++ "saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order"+)+def test_draft_order_shipping_methods(+ mocked_webhook,+ staff_api_client,+ order_with_lines,+ permission_group_manage_orders,+ settings,+):+ # given+ order_with_lines.status = OrderStatus.DRAFT+ order_with_lines.save(update_fields=["status"])+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ webhook_reason = "spanish-inquisition"+ excluded_shipping_method_id = str(order_with_lines.shipping_method.id)+ mocked_webhook.return_value = Promise.resolve(+ [ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)]+ )+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # when+ response = staff_api_client.post_graphql(+ ORDER_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(order_with_lines)},+ )+ content = get_graphql_content(response)+ order_data = content["data"]["order"]++ shipping_methods = order_data["shippingMethods"]+ # then+ assert len(shipping_methods) == 1+ assert not shipping_methods[0]["active"]+ assert shipping_methods[0]["message"] == webhook_reason+++ "order_status",+ [+ OrderStatus.UNFULFILLED,+ OrderStatus.PARTIALLY_FULFILLED,+ OrderStatus.FULFILLED,+ OrderStatus.CANCELED,+ OrderStatus.EXPIRED,+ OrderStatus.RETURNED,+ OrderStatus.PARTIALLY_RETURNED,+ ],+)+ "saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order"+)+def test_order_shipping_methods_skips_sync_webhook_for_non_editable_statuses(+ mocked_webhook,+ order_status,+ staff_api_client,+ order_with_lines,+ permission_group_manage_orders,+ settings,+):+ # given+ order_with_lines.status = order_status+ order_with_lines.save(update_fields=["status"])+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # when+ response = staff_api_client.post_graphql(+ ORDER_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(order_with_lines)},+ )+ content = get_graphql_content(response)+ order_data = content["data"]["order"]++ shipping_methods = order_data["shippingMethods"]++ # then+ assert not mocked_webhook.called+ assert len(shipping_methods) == 1+ assert shipping_methods[0]["active"]+++ ("webhook_response", "expected_count"),+ [+ (lambda s: [ExcludedShippingMethod(str(s.id), "")], 0),+ (lambda s: [], 1),+ ],+)+ "saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order"+)+def test_order_available_shipping_methods(+ mocked_webhook,+ staff_api_client,+ order_with_lines,+ permission_group_manage_orders,+ settings,+ webhook_response,+ expected_count,+):+ # given+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ order_with_lines.status = OrderStatus.UNCONFIRMED+ order_with_lines.save(update_fields=["status"])+ shipping_method = order_with_lines.shipping_method++ def respond(*args, **kwargs):+ return Promise.resolve(webhook_response(shipping_method))++ mocked_webhook.side_effect = respond+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ # when+ response = staff_api_client.post_graphql(+ ORDER_QUERY_SHIPPING_METHOD,+ variables={"id": to_global_id_or_none(order_with_lines)},+ )+ content = get_graphql_content(response)+ order_data = content["data"]["order"]++ # then+ assert len(order_data["availableShippingMethods"]) == expected_countdiff --git a/saleor/graphql/order/tests/queries/test_orders.py b/saleor/graphql/order/tests/queries/test_orders.pyindex 4664e84bc4..8e5b399371 100644--- a/saleor/graphql/order/tests/queries/test_orders.py+++ b/saleor/graphql/order/tests/queries/test_orders.py@@ -7,7 +7,6 @@ from .....order.events import (fulfillment_fulfilled_items_event,order_added_products_event,)-from .....plugins.manager import PluginsManagerfrom .....tax.calculations.order import update_order_prices_with_flat_ratesfrom ....tests.utils import get_graphql_contentfrom .shared_query_fragments import ORDER_FRAGMENT_WITH_WEBHOOK_RELATED_FIELDS@@ -225,7 +224,7 @@ def test_query_orders_for_order_with_events_when_tax_app_active(mocked_calculate_prices.assert_not_called()[email protected](PluginsManager, "excluded_shipping_methods_for_order")+@patch("saleor.order.webhooks.exclude_shipping.excluded_shipping_methods_for_order")def test_query_orders_with_active_filter_shipping_methods_webhook(mocked_webhook_handler,settings,diff --git a/saleor/graphql/order/tests/test_draft_order_validate.py b/saleor/graphql/order/tests/test_draft_order_validate.pyindex 5ef79560cc..8a83c60877 100644--- a/saleor/graphql/order/tests/test_draft_order_validate.py+++ b/saleor/graphql/order/tests/test_draft_order_validate.py@@ -18,7 +18,7 @@ def test_validate_draft_order(draft_order):draft_order.lines.all(),"US",get_plugins_manager(allow_replica=False),- )+ ).get()is None)@@ -33,7 +33,7 @@ def test_validate_draft_order_without_sku(draft_order):draft_order.lines.all(),"US",get_plugins_manager(allow_replica=False),- )+ ).get()is None)@@ -47,7 +47,7 @@ def test_validate_draft_order_wrong_shipping(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Shipping method is not valid for chosen shipping address"assert e.value.error_dict["shipping"][0].message == msg@@ -57,7 +57,7 @@ def test_validate_draft_order_no_order_lines(order, shipping_method):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Could not create order without any products."assert e.value.error_dict["lines"][0].message == msg@@ -73,7 +73,7 @@ def test_validate_draft_order_non_existing_variant(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Could not create orders with non-existing products."assert e.value.error_dict["lines"][0].message == msg@@ -90,7 +90,7 @@ def test_validate_draft_order_with_unpublished_product(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Can't finalize draft with unpublished product."error = e.value.error_dict["lines"][0]@@ -108,7 +108,7 @@ def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order)with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Can't finalize draft with product unavailable for purchase."error = e.value.error_dict["lines"][0]@@ -131,7 +131,7 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Can't finalize draft with product unavailable for purchase."error = e.value.error_dict["lines"][0]@@ -151,7 +151,7 @@ def test_validate_draft_order_out_of_stock_variant(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()msg = "Insufficient product stock."assert e.value.error_dict["lines"][0].message == msg@@ -163,7 +163,7 @@ def test_validate_draft_order_no_shipping_address(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()error = e.value.error_dict["order"][0]assert error.message == "Can't finalize draft with no shipping address."assert error.code == OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value@@ -176,7 +176,7 @@ def test_validate_draft_order_no_billing_address(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()error = e.value.error_dict["order"][0]assert error.message == "Can't finalize draft with no billing address."assert error.code == OrderErrorCode.BILLING_ADDRESS_NOT_SET.value@@ -189,7 +189,7 @@ def test_validate_draft_order_no_shipping_method(draft_order):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()error = e.value.error_dict["shipping"][0]assert error.message == "Shipping method is required."assert error.code == OrderErrorCode.SHIPPING_METHOD_REQUIRED.value@@ -206,7 +206,7 @@ def test_validate_draft_order_no_shipping_method_shipping_not_required(assert (validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()is None)@@ -224,7 +224,7 @@ def test_validate_draft_order_no_shipping_address_no_method_shipping_not_requireassert (validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()is None)@@ -238,7 +238,7 @@ def test_validate_draft_order_voucher(draft_order_with_voucher):with pytest.raises(ValidationError) as e:validate_draft_order(order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)- )+ ).get()error = e.value.error_dict["voucher"][0]assert error.code == OrderErrorCode.INVALID_VOUCHER.valuediff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 29a5435853..69fbb6a697 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1,5 +1,6 @@import loggingfrom decimal import Decimal+from typing import castfrom uuid import UUIDimport graphene@@ -30,13 +31,15 @@ from ...graphql.utils import get_user_or_app_from_contextfrom ...graphql.warehouse.dataloaders import StockByIdLoader, WarehouseByIdLoaderfrom ...order import OrderOrigin, OrderStatus, calculations, modelsfrom ...order.calculations import fetch_order_prices_if_expired-from ...order.models import FulfillmentStatus-from ...order.utils import (+from ...order.delivery_context import (get_external_shipping_id,- get_order_country,get_valid_collection_points_for_order,get_valid_shipping_methods_for_order,)+from ...order.models import FulfillmentStatus+from ...order.utils import (+ get_order_country,+)from ...payment import ChargeStatus, TransactionKindfrom ...payment.dataloaders import PaymentsByOrderIdLoaderfrom ...payment.model_helpers import get_last_payment, get_total_authorized@@ -1984,6 +1987,8 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde@staticmethod@traced_resolverdef resolve_discount(root: SyncWebhookControlContext[models.Order], info):+ order = root.node+def return_voucher_discount(discounts) -> Money | None:if not discounts:return None@@ -1994,15 +1999,24 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde)return None- return (- OrderDiscountsByOrderIDLoader(info.context)- .load(root.node.id)- .then(return_voucher_discount)- )+ def with_manager(manager):+ with allow_writer_in_context(info.context):+ fetch_order_prices_if_expired(+ order, manager, allow_sync_webhooks=root.allow_sync_webhooks+ )+ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(order.id)+ .then(return_voucher_discount)+ )++ return get_plugin_manager_promise(info.context).then(with_manager)@staticmethod@traced_resolverdef resolve_discount_name(root: SyncWebhookControlContext[models.Order], info):+ order = root.node+def return_voucher_name(discounts) -> Money | None:if not discounts:return None@@ -2011,17 +2025,26 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordereturn discount.namereturn None- return (- OrderDiscountsByOrderIDLoader(info.context)- .load(root.node.id)- .then(return_voucher_name)- )+ def with_manager(manager):+ with allow_writer_in_context(info.context):+ fetch_order_prices_if_expired(+ order, manager, allow_sync_webhooks=root.allow_sync_webhooks+ )+ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(order.id)+ .then(return_voucher_name)+ )++ return get_plugin_manager_promise(info.context).then(with_manager)@staticmethod@traced_resolverdef resolve_translated_discount_name(root: SyncWebhookControlContext[models.Order], info):+ order = root.node+def return_voucher_translated_name(discounts) -> Money | None:if not discounts:return None@@ -2030,11 +2053,18 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordereturn discount.translated_namereturn None- return (- OrderDiscountsByOrderIDLoader(info.context)- .load(root.node.id)- .then(return_voucher_translated_name)- )+ def with_manager(manager):+ with allow_writer_in_context(info.context):+ fetch_order_prices_if_expired(+ order, manager, allow_sync_webhooks=root.allow_sync_webhooks+ )+ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(order.id)+ .then(return_voucher_translated_name)+ )++ return get_plugin_manager_promise(info.context).then(with_manager)@staticmethod@traced_resolver@@ -2116,6 +2146,7 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordedef _resolve_undiscounted_shipping_price(data):lines, manager = datadatabase_connection_name = get_database_connection_name(info.context)+return calculations.order_undiscounted_shipping(order,manager,@@ -2504,26 +2535,24 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordeif order.status == OrderStatus.DRAFT:@allow_writer_in_context(info.context)- def _validate_draft_order(data):- lines, manager = data+ def _validate_draft_order(lines):country = get_order_country(order)database_connection_name = get_database_connection_name(info.context)- try:+ return (validate_draft_order(order=order,lines=lines,country=country,- manager=manager,+ requestor=get_user_or_app_from_context(info.context),database_connection_name=database_connection_name,allow_sync_webhooks=root.allow_sync_webhooks,)- except ValidationError:- return False- return True+ .then(lambda _: True)+ .catch(lambda _: False)+ )- lines = OrderLinesByOrderIdLoader(info.context).load(order.id)- manager = get_plugin_manager_promise(info.context)- return Promise.all([lines, manager]).then(_validate_draft_order)+ lines_dataloader = OrderLinesByOrderIdLoader(info.context).load(order.id)+ return lines_dataloader.then(_validate_draft_order)return True@staticmethod@@ -2685,8 +2714,7 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde):order = root.node- def with_channel(data):- channel, manager = data+ def with_channel(channel):database_connection_name = get_database_connection_name(info.context)@allow_writer_in_context(info.context)@@ -2694,7 +2722,7 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordereturn get_valid_shipping_methods_for_order(order,channel_listings,- manager,+ requestor=get_user_or_app_from_context(info.context),database_connection_name=database_connection_name,allow_sync_webhooks=root.allow_sync_webhooks,)@@ -2705,10 +2733,8 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde.then(with_listings))- channel = ChannelByIdLoader(info.context).load(order.channel_id)- manager = get_plugin_manager_promise(info.context)-- return Promise.all([channel, manager]).then(with_channel)+ channel_loader = ChannelByIdLoader(info.context).load(order.channel_id)+ return channel_loader.then(with_channel)@classmethod@traced_resolver@@ -2806,26 +2832,28 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordeif order.status == OrderStatus.DRAFT:@allow_writer_in_context(info.context)- def _validate_order(data):- lines, manager = data+ def _validate_order(lines):country = get_order_country(order)database_connection_name = get_database_connection_name(info.context)- try:+ return (validate_draft_order(order=order,lines=lines,country=country,- manager=manager,+ requestor=get_user_or_app_from_context(info.context),database_connection_name=database_connection_name,allow_sync_webhooks=root.allow_sync_webhooks,)- except ValidationError as e:- return validation_error_to_error_type(e, OrderError)- return []+ .then(lambda _: [])+ .catch(+ lambda e: validation_error_to_error_type(+ cast(ValidationError, e), OrderError+ )+ )+ )- lines = OrderLinesByOrderIdLoader(info.context).load(order.id)- manager = get_plugin_manager_promise(info.context)- return Promise.all([lines, manager]).then(_validate_order)+ lines_dataloader = OrderLinesByOrderIdLoader(info.context).load(order.id)+ return lines_dataloader.then(_validate_order)return []diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex 003197638e..2cf1a456a5 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -1,23 +1,23 @@from collections import defaultdictfrom collections.abc import Iterablefrom decimal import Decimal-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Optional, Unionimport graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationError+from promise import Promisefrom ...core.exceptions import InsufficientStockfrom ...discount.interface import VariantPromotionRuleInfofrom ...discount.models import NotApplicablefrom ...discount.utils.voucher import validate_voucher_in_order-from ...order.error_codes import OrderErrorCode-from ...order.utils import (- get_total_quantity,+from ...order.delivery_context import (get_valid_shipping_methods_for_order,is_shipping_required,)-from ...plugins.manager import PluginsManager+from ...order.error_codes import OrderErrorCode+from ...order.utils import get_total_quantityfrom ...product.models import Product, ProductChannelListing, ProductVariantfrom ...shipping.interface import ShippingMethodDatafrom ...shipping.utils import convert_to_shipping_method_data@@ -25,6 +25,8 @@ from ...warehouse.availability import check_stock_and_preorder_quantityfrom ..core.validators import validate_variants_available_in_channelif TYPE_CHECKING:+ from ...account.models import User+ from ...app.models import Appfrom ...channel.models import Channelfrom ...order.models import Order, OrderLine@@ -57,42 +59,50 @@ def validate_total_quantity(lines: Iterable["OrderLine"], errors: T_ERRORS):def get_shipping_method_availability_error(order: "Order",method: Optional["ShippingMethodData"],- manager: "PluginsManager",+ requestor: Union["App", "User", None],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,allow_sync_webhooks: bool = True,-):+) -> Promise[ValidationError | None]:"""Validate whether shipping method is still available for the order."""- is_valid = False- if method:++ def get_valid_shipping_methods(valid_methods):valid_methods_ids = {- m.id- for m in get_valid_shipping_methods_for_order(- order,- order.channel.shipping_method_listings.all(),- manager,- database_connection_name=database_connection_name,- allow_sync_webhooks=allow_sync_webhooks,- )- if m.active+ valid_method.id for valid_method in valid_methods if valid_method.active}- is_valid = method.id in valid_methods_ids+ is_valid = False+ if method:+ is_valid = method.id in valid_methods_ids- if not is_valid:- return ValidationError(- "Shipping method cannot be used with this order.",- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,+ if not is_valid:+ return ValidationError(+ "Shipping method cannot be used with this order.",+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,+ )+ return None++ promised_valid_methods: Promise[list[ShippingMethodData]] = Promise.resolve([])+ if method:+ promised_valid_methods = get_valid_shipping_methods_for_order(+ order,+ order.channel.shipping_method_listings.all(),+ requestor=requestor,+ database_connection_name=database_connection_name,+ allow_sync_webhooks=allow_sync_webhooks,)- return None+ return promised_valid_methods.then(get_valid_shipping_methods)def validate_shipping_method(order: "Order",channel: "Channel",errors: T_ERRORS,- manager: "PluginsManager",+ requestor: Union["App", "User", None],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,allow_sync_webhooks: bool = True,-):+) -> Promise[None]:+ error = None+ promised_error: Promise[ValidationError | None] = Promise.resolve(None)+if not order.shipping_method:error = ValidationError("Shipping method is required.",@@ -122,10 +132,10 @@ def validate_shipping_method(code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,)else:- error = get_shipping_method_availability_error(+ promised_error = get_shipping_method_availability_error(order,convert_to_shipping_method_data(order.shipping_method, listing),- manager,+ requestor=requestor,database_connection_name=database_connection_name,allow_sync_webhooks=allow_sync_webhooks,)@@ -133,6 +143,12 @@ def validate_shipping_method(if error:errors["shipping"].append(error)+ def append_error(error_from_promise: ValidationError | None):+ if error_from_promise:+ errors["shipping"].append(error_from_promise)++ return promised_error.then(append_error)+def validate_billing_address(order: "Order", errors: T_ERRORS):if not order.billing_address:@@ -346,10 +362,10 @@ def validate_draft_order(order: "Order",lines: Iterable["OrderLine"],country: str,- manager: "PluginsManager",+ requestor: Union["App", "User", None],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,allow_sync_webhooks: bool = True,-):+) -> Promise[None]:"""Check if the given order contains the proper data.- Has proper customer data,@@ -359,19 +375,20 @@ def validate_draft_order(- Product variants are published.- Voucher is properly applied.- Returns a list of errors if any were found.+ Raises ValidationError with a list of errors if any were found."""channel = order.channel+ promised_error = Promise.resolve(None)errors: T_ERRORS = defaultdict(list)validate_billing_address(order, errors)if is_shipping_required(lines):validate_shipping_address(order, errors)- validate_shipping_method(+ promised_error = validate_shipping_method(order,channel,errors,- manager,+ requestor,database_connection_name,allow_sync_webhooks=allow_sync_webhooks,)@@ -387,8 +404,11 @@ def validate_draft_order(validate_variants_is_available(channel, lines, errors, database_connection_name)_validate_voucher(order, lines, channel, errors)- if errors:- raise ValidationError(errors)+ def raise_errors(_):+ if errors:+ raise ValidationError(errors)++ return promised_error.then(raise_errors)def prepare_insufficient_stock_order_validation_errors(exc):diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 82154f043f..1cddbf9b65 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -53,6 +53,7 @@ from . import (utils,)from .calculations import fetch_order_prices_if_expired+from .delivery_context import get_valid_shipping_methods_for_orderfrom .events import (draft_order_created_from_replace_event,fulfillment_refunded_event,@@ -71,7 +72,6 @@ from .notifications import ()from .utils import (clean_order_line_quantities,- get_valid_shipping_methods_for_order,order_line_needs_automatic_fulfillment,restock_fulfillment_lines,update_order_authorize_data,@@ -178,12 +178,15 @@ def _trigger_order_sync_webhooks(shipping_listings = ShippingMethodChannelListing.objects.filter(channel_id=order.channel_id)+ # FIXME: Calling .get() as we need to have all webhooks on Promise+ # to be able to use them here. We can drop this after migrating+ # fetch_order_prices_if_expired to use Promise as well.get_valid_shipping_methods_for_order(order,shipping_listings,- manager,+ manager.requestor_getter,database_connection_name=database_connection_name,- )+ ).get()def _get_extra_for_order_logger(order: "Order") -> dict:diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex f80c2940b2..6bf1d62b60 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -65,7 +65,7 @@ def fetch_order_prices_if_expired(force_update: bool = False,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,allow_sync_webhooks: bool = True,-) -> tuple[Order, Iterable[OrderLine] | None]:+) -> tuple[Order, Iterable[OrderLine]]:"""Fetch order prices with taxes.First applies order level discounts, then calculates taxes.@@ -74,15 +74,14 @@ def fetch_order_prices_if_expired(or if order.should_refresh_prices is True."""if order.status not in ORDER_EDITABLE_STATUS:- return order, lines+ return order, lines or []expired_line_ids = get_expired_line_ids(order, lines)if not force_update and not order.should_refresh_prices and not expired_line_ids:- return order, lines-+ return order, lines or []tax_strategy = get_tax_calculation_strategy_for_order(order)if tax_strategy == TaxCalculationStrategy.TAX_APP and not allow_sync_webhooks:- return order, lines+ return order, lines or []if expired_line_ids:# handle line base price expirationdiff --git a/saleor/order/delivery_context.py b/saleor/order/delivery_context.pynew file mode 100644index 0000000000..89735e9b45--- /dev/null+++ b/saleor/order/delivery_context.py@@ -0,0 +1,136 @@+import logging+from collections.abc import Iterable+from typing import TYPE_CHECKING, Union++from django.conf import settings+from promise import Promise++from ..shipping.interface import ShippingMethodData+from ..shipping.models import ShippingMethod, ShippingMethodChannelListing+from ..shipping.utils import (+ convert_to_shipping_method_data,+ initialize_shipping_method_active_status,+)+from ..warehouse.models import Warehouse+from . import (+ ORDER_EDITABLE_STATUS,+)+from .models import Order, OrderLine++if TYPE_CHECKING:+ from ..account.models import User+ from ..app.models import App++logger = logging.getLogger(__name__)+++PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"+++def get_all_shipping_methods_for_order(+ order: Order,+ shipping_channel_listings: Iterable["ShippingMethodChannelListing"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> list[ShippingMethodData]:+ if not order.is_shipping_required(+ database_connection_name=database_connection_name+ ):+ return []++ shipping_address = order.shipping_address+ if not shipping_address:+ return []++ all_methods = []++ shipping_methods = (+ ShippingMethod.objects.using(database_connection_name)+ .applicable_shipping_methods_for_instance(+ order,+ channel_id=order.channel_id,+ price=order.subtotal.gross,+ shipping_address=shipping_address,+ country_code=shipping_address.country.code,+ database_connection_name=database_connection_name,+ )+ .prefetch_related("channel_listings")+ )++ listing_map = {+ listing.shipping_method_id: listing for listing in shipping_channel_listings+ }++ for method in shipping_methods:+ listing = listing_map.get(method.id)+ if listing:+ shipping_method_data = convert_to_shipping_method_data(method, listing)+ all_methods.append(shipping_method_data)+ return all_methods+++def get_valid_shipping_methods_for_order(+ order: Order,+ shipping_channel_listings: Iterable["ShippingMethodChannelListing"],+ requestor: Union["App", "User", None],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+ allow_sync_webhooks: bool = True,+) -> Promise[list[ShippingMethodData]]:+ """Return a list of shipping methods according to Saleor's own business logic."""++ # Circular import caused by the current definition of subscription payloads+ # and their usage in webhook/transport layer. Until moving them out from the+ # transport, we will have circular imports.+ from .webhooks.exclude_shipping import (+ ExcludedShippingMethod,+ excluded_shipping_methods_for_order,+ )++ valid_methods = get_all_shipping_methods_for_order(+ order, shipping_channel_listings, database_connection_name+ )+ if not valid_methods:+ return Promise.resolve([])++ allow_replica = True+ if database_connection_name == settings.DATABASE_CONNECTION_DEFAULT_NAME:+ allow_replica = False++ promised_excluded_methods: Promise[list[ExcludedShippingMethod]] = Promise.resolve(+ []+ )+ if order.status in ORDER_EDITABLE_STATUS and allow_sync_webhooks:+ promised_excluded_methods = excluded_shipping_methods_for_order(+ order, valid_methods, allow_replica=allow_replica, requestor=requestor+ )++ def handle_excluded_methods(excluded_methods):+ initialize_shipping_method_active_status(valid_methods, excluded_methods)+ return valid_methods++ return promised_excluded_methods.then(handle_excluded_methods)+++def get_external_shipping_id(order: "Order"):+ if not order:+ return None+ return order.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)+++def is_shipping_required(lines: Iterable["OrderLine"]):+ return any(line.is_shipping_required for line in lines)+++def get_valid_collection_points_for_order(+ lines: Iterable["OrderLine"],+ channel_id: int,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ if not is_shipping_required(lines):+ return []++ line_ids = [line.id for line in lines]+ qs = OrderLine.objects.using(database_connection_name).filter(id__in=line_ids)++ return Warehouse.objects.using(+ database_connection_name+ ).applicable_for_click_and_collect(qs, channel_id)diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 9d2c320b02..7a58a0e668 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -25,7 +25,6 @@ from ..utils import (change_order_line_quantity,get_order_country,get_total_order_discount_excluding_shipping,- get_valid_shipping_methods_for_order,match_orders_with_new_user,order_info_for_logs,store_user_addresses_from_draft_order,@@ -179,95 +178,6 @@ def test_match_draft_order_with_new_user(customer_user, channel_USD):assert order.user is None-def test_get_valid_shipping_methods_for_order(order_line_with_one_allocation, address):- # given- order = order_line_with_one_allocation.order- order_line_with_one_allocation.is_shipping_required = True- order_line_with_one_allocation.save(update_fields=["is_shipping_required"])-- order.currency = "USD"- order.shipping_address = address- order.save(update_fields=["shipping_address"])-- # when- valid_shipping_methods = get_valid_shipping_methods_for_order(- order,- order.channel.shipping_method_listings.all(),- get_plugins_manager(allow_replica=False),- )-- # then- assert len(valid_shipping_methods) == 1---def test_get_valid_shipping_methods_for_order_no_channel_shipping_zones(- order_line_with_one_allocation, address-):- # given- order = order_line_with_one_allocation.order- order.channel.shipping_zones.clear()- order_line_with_one_allocation.is_shipping_required = True- order_line_with_one_allocation.save(update_fields=["is_shipping_required"])-- order.currency = "USD"- order.shipping_address = address- order.save(update_fields=["shipping_address"])-- # when- valid_shipping_methods = get_valid_shipping_methods_for_order(- order,- order.channel.shipping_method_listings.all(),- get_plugins_manager(allow_replica=False),- )-- # then- assert len(valid_shipping_methods) == 0---def test_get_valid_shipping_methods_for_order_no_shipping_address(- order_line_with_one_allocation, address-):- # given- order = order_line_with_one_allocation.order- order_line_with_one_allocation.is_shipping_required = True- order_line_with_one_allocation.save(update_fields=["is_shipping_required"])-- order.currency = "USD"-- # when- valid_shipping_methods = get_valid_shipping_methods_for_order(- order,- order.channel.shipping_method_listings.all(),- get_plugins_manager(allow_replica=False),- )-- # then- assert valid_shipping_methods == []---def test_get_valid_shipping_methods_for_order_shipping_not_required(- order_line_with_one_allocation, address-):- # given- order = order_line_with_one_allocation.order- order_line_with_one_allocation.is_shipping_required = False- order_line_with_one_allocation.save(update_fields=["is_shipping_required"])-- order.currency = "USD"- order.shipping_address = address- order.save(update_fields=["shipping_address"])-- # when- valid_shipping_methods = get_valid_shipping_methods_for_order(- order,- order.channel.shipping_method_listings.all(),- get_plugins_manager(allow_replica=False),- )-- # then- assert valid_shipping_methods == []--def test_add_variant_to_order(order,customer_user,diff --git a/saleor/order/tests/test_shipping_context.py b/saleor/order/tests/test_shipping_context.pynew file mode 100644index 0000000000..030b420ffd--- /dev/null+++ b/saleor/order/tests/test_shipping_context.py@@ -0,0 +1,169 @@+from ...shipping.models import ShippingMethod, ShippingMethodType+from ..delivery_context import (+ get_all_shipping_methods_for_order,+ get_valid_shipping_methods_for_order,+)+++def test_get_valid_shipping_methods_for_order(order_line_with_one_allocation, address):+ # given+ order = order_line_with_one_allocation.order+ order_line_with_one_allocation.is_shipping_required = True+ order_line_with_one_allocation.save(update_fields=["is_shipping_required"])++ order.currency = "USD"+ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ # when+ valid_shipping_methods = get_valid_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all(), None+ ).get()++ # then+ assert len(valid_shipping_methods) == 1+++def test_get_valid_shipping_methods_for_order_no_channel_shipping_zones(+ order_line_with_one_allocation, address+):+ # given+ order = order_line_with_one_allocation.order+ order.channel.shipping_zones.clear()+ order_line_with_one_allocation.is_shipping_required = True+ order_line_with_one_allocation.save(update_fields=["is_shipping_required"])++ order.currency = "USD"+ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ # when+ valid_shipping_methods = get_valid_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all(), None+ ).get()+ # then+ assert len(valid_shipping_methods) == 0+++def test_get_valid_shipping_methods_for_order_no_shipping_address(+ order_line_with_one_allocation, address+):+ # given+ order = order_line_with_one_allocation.order+ order_line_with_one_allocation.is_shipping_required = True+ order_line_with_one_allocation.save(update_fields=["is_shipping_required"])++ order.currency = "USD"++ # when+ valid_shipping_methods = get_valid_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all(), None+ ).get()++ # then+ assert valid_shipping_methods == []+++def test_get_valid_shipping_methods_for_order_shipping_not_required(+ order_line_with_one_allocation, address+):+ # given+ order = order_line_with_one_allocation.order+ order_line_with_one_allocation.is_shipping_required = False+ order_line_with_one_allocation.save(update_fields=["is_shipping_required"])++ order.currency = "USD"+ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ # when+ valid_shipping_methods = get_valid_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all(), None+ ).get()++ # then+ assert valid_shipping_methods == []+++def test_get_all_shipping_methods_returns_empty_when_shipping_not_required(+ order_with_lines, address+):+ # given+ order = order_with_lines+ order.lines.update(is_shipping_required=False)++ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ # when+ result = get_all_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all()+ )++ # then+ assert result == []+++def test_get_all_shipping_methods_returns_empty_when_no_shipping_address(+ order_with_lines,+):+ # given+ order = order_with_lines+ order.shipping_address = None+ order.save(update_fields=["shipping_address"])++ # when+ result = get_all_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all()+ )++ # then+ assert result == []+++def test_get_all_shipping_methods_returns_applicable_methods_with_listings(+ order_with_lines, address, shipping_zone+):+ # given+ order = order_with_lines++ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ shipping_method = shipping_zone.shipping_methods.first()++ # when+ result = get_all_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all()+ )++ # then+ assert len(result) == 1+ assert result[0].id == str(shipping_method.id)+++def test_get_all_shipping_methods_excludes_methods_without_channel_listing(+ order_with_lines, address, shipping_zone+):+ # given+ order = order_with_lines++ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ method_without_listing = ShippingMethod.objects.create(+ name="No Listing Method",+ shipping_zone=shipping_zone,+ type=ShippingMethodType.PRICE_BASED,+ )++ # when+ result = get_all_shipping_methods_for_order(+ order, order.channel.shipping_method_listings.all()+ )++ # then+ assert len(result) == 1+ existing_method = shipping_zone.shipping_methods.first()+ assert result[0].id == str(existing_method.id)+ assert method_without_listing.id not in [int(m.id) for m in result]diff --git a/saleor/order/tests/webhooks/__init__.py b/saleor/order/tests/webhooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/order/tests/webhooks/test_exclude_shipping.py b/saleor/order/tests/webhooks/test_exclude_shipping.pynew file mode 100644index 0000000000..80790cadee--- /dev/null+++ b/saleor/order/tests/webhooks/test_exclude_shipping.py@@ -0,0 +1,560 @@+import json+import uuid+from decimal import Decimal+from unittest import mock+from unittest.mock import call++import graphene+import pytest+from measurement.measures import Weight+from prices import Money+from promise import Promise++from ....shipping.interface import ShippingMethodData+from ....webhook.const 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 (+ _get_excluded_shipping_methods_from_response,+ excluded_shipping_methods_for_order,+ generate_excluded_shipping_methods_for_order_payload,+)++ORDER_QUERY_SHIPPING_METHOD = """+query OrderQuery($id: ID) {+ order(id: $id) {+ shippingMethods {+ id+ name+ active+ message+ }+ availableShippingMethods {+ id+ name+ active+ message+ }+ }+}+"""+++def available_shipping_methods():+ methods = []+ for i in range(2):+ methods.append(+ ShippingMethodData(+ id=str(i),+ price=Money(Decimal(10), "usd"),+ name=uuid.uuid4().hex,+ maximum_order_weight=Weight(kg=0),+ minimum_order_weight=Weight(kg=0),+ maximum_delivery_days=0,+ minimum_delivery_days=5,+ )+ )+ return methods++[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")+def test_excluded_shipping_methods_for_order_dont_run_webhook_on_missing_shipping_methods(+ mocked_get_excluded_shipping_data, draft_order+):+ # given+ empty_shipping_methods = []++ # when+ excluded_shipping_methods_for_order(+ order=draft_order,+ available_shipping_methods=empty_shipping_methods,+ allow_replica=False,+ requestor=None,+ ).get()++ # then+ mocked_get_excluded_shipping_data.assert_not_called()++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"+)+ "saleor.order.webhooks.exclude_shipping.generate_excluded_shipping_methods_for_order_payload"+)+def test_excluded_shipping_methods_for_order(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ order_with_lines,+ available_shipping_methods,+ app_exclude_shipping_for_order,+ settings,+):+ # given+ shipping_app = app_exclude_shipping_for_order+ shipping_webhook = shipping_app.webhooks.get()+ webhook_reason = "Order contains dangerous products."++ shipping_method_id_to_exclude = available_shipping_methods[0].id+ webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id(+ "ShippingMethod", shipping_method_id_to_exclude+ ),+ "reason": webhook_reason,+ }+ ]+ }+ mocked_webhook.return_value = Promise.resolve(webhook_response)+ payload_dict = {"order": {"id": 1, "some_field": "12"}}+ payload = json.dumps(payload_dict)+ mocked_payload.return_value = payload++ # when+ excluded_methods = excluded_shipping_methods_for_order(+ order=order_with_lines,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ ).get()++ # then+ assert len(excluded_methods) == 1+ excluded_method = excluded_methods[0]+ assert excluded_method.id == shipping_method_id_to_exclude+ assert webhook_reason in excluded_method.reason++ mocked_webhook.assert_called_once_with(+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ payload,+ shipping_webhook,+ False,+ subscribable_object=(order_with_lines, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ )+ expected_cache_key = generate_cache_key_for_webhook(+ payload_dict,+ shipping_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ shipping_app.id,+ )++ mocked_cache_set.assert_called_once_with(+ expected_cache_key,+ webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ )++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"+)+ "saleor.order.webhooks.exclude_shipping.generate_excluded_shipping_methods_for_order_payload"+)+def test_multiple_app_with_excluded_shipping_methods_for_order(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ order_with_lines,+ available_shipping_methods,+ app_exclude_shipping_for_order,+ second_app_exclude_shipping_for_order,+ settings,+):+ # given+ shipping_app = app_exclude_shipping_for_order+ shipping_webhook = shipping_app.webhooks.get()++ second_shipping_app = second_app_exclude_shipping_for_order+ second_shipping_webhook = second_shipping_app.webhooks.get()+ webhook_reason = "Order contains dangerous products."+ webhook_second_reason = "Shipping is not applicable for this order."++ first_excluded_id = available_shipping_methods[0].id+ second_excluded_id = available_shipping_methods[1].id++ first_webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id(+ "ShippingMethod",+ first_excluded_id,+ ),+ "reason": webhook_reason,+ }+ ]+ }+ second_webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id(+ "ShippingMethod",+ first_excluded_id,+ ),+ "reason": webhook_second_reason,+ },+ {+ "id": graphene.Node.to_global_id(+ "ShippingMethod",+ second_excluded_id,+ ),+ "reason": webhook_second_reason,+ },+ ]+ }++ mocked_webhook.side_effect = [+ Promise.resolve(first_webhook_response),+ Promise.resolve(second_webhook_response),+ ]++ payload_dict = {"order": {"id": 1, "some_field": "12"}}+ payload = json.dumps(payload_dict)+ mocked_payload.return_value = payload++ # when+ excluded_methods = excluded_shipping_methods_for_order(+ order=order_with_lines,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ ).get()++ # then+ assert len(excluded_methods) == 2+ first_excluded_method_data = next(+ em for em in excluded_methods if em.id == first_excluded_id+ )+ assert webhook_reason in first_excluded_method_data.reason+ assert webhook_second_reason in first_excluded_method_data.reason++ event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS+ mocked_webhook.assert_any_call(+ event_type,+ payload,+ shipping_webhook,+ False,+ subscribable_object=(order_with_lines, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ )+ mocked_webhook.assert_any_call(+ event_type,+ payload,+ second_shipping_webhook,+ False,+ subscribable_object=(order_with_lines, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ )+ assert mocked_webhook.call_count == 2+ expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(+ payload_dict,+ shipping_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ shipping_app.id,+ )+ expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(+ payload_dict,+ second_shipping_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ second_shipping_app.id,+ )++ assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key++ mocked_cache_set.assert_has_calls(+ [+ call(+ expected_cache_for_first_webhook_key,+ first_webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ ),+ call(+ expected_cache_for_second_webhook_key,+ second_webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ ),+ ]+ )++[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")+ "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"+)+ "saleor.order.webhooks.exclude_shipping.generate_excluded_shipping_methods_for_order_payload"+)+def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_order(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ order_with_lines,+ available_shipping_methods,+ app_exclude_shipping_for_order,+ settings,+):+ # given+ shipping_app = app_exclude_shipping_for_order+ first_webhook = shipping_app.webhooks.get()+ event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS++ # create the second webhook with the same event+ second_webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=shipping_app,+ target_url="https://shipping-gateway.com/apiv2/",+ )+ second_webhook.events.create(+ event_type=event_type,+ webhook=second_webhook,+ )++ webhook_reason = "Order contains dangerous products."+ webhook_second_reason = "Shipping is not applicable for this order."++ first_webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }+ second_webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_second_reason,+ },+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),+ "reason": webhook_second_reason,+ },+ ]+ }++ mocked_webhook.side_effect = [+ Promise.resolve(first_webhook_response),+ Promise.resolve(second_webhook_response),+ ]++ payload_dict = {"order": {"id": 1, "some_field": "12"}}+ payload = json.dumps(payload_dict)+ mocked_payload.return_value = payload++ # when+ excluded_methods = excluded_shipping_methods_for_order(+ order=order_with_lines,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ ).get()++ # then+ assert len(excluded_methods) == 2+ em_1 = next(em for em in excluded_methods if em.id == "1")+ assert webhook_reason in em_1.reason+ assert webhook_second_reason in em_1.reason++ mocked_webhook.assert_any_call(+ event_type,+ payload,+ first_webhook,+ False,+ subscribable_object=(order_with_lines, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ )+ mocked_webhook.assert_any_call(+ event_type,+ payload,+ second_webhook,+ False,+ subscribable_object=(order_with_lines, available_shipping_methods),+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ request=None,+ requestor=None,+ )+ assert mocked_webhook.call_count == 2++ expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(+ payload_dict,+ first_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ shipping_app.id,+ )+ expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(+ payload_dict,+ second_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ shipping_app.id,+ )+ assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key++ mocked_cache_set.assert_has_calls(+ [+ call(+ expected_cache_for_first_webhook_key,+ first_webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ ),+ call(+ expected_cache_for_second_webhook_key,+ second_webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ ),+ ]+ )+++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,+):+ # given+ methods = available_shipping_methods+ # when+ json_payload = json.loads(+ generate_excluded_shipping_methods_for_order_payload(+ order=order_with_lines, available_shipping_methods=methods+ )+ )+ # then+ assert len(json_payload["shipping_methods"]) == 2+ assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", methods[0].id+ )+ assert json_payload["shipping_methods"][1]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", methods[1].id+ )+ graphql_order_id = graphene.Node.to_global_id("Order", order_with_lines.id)+ assert json_payload["order"]["id"] == graphql_order_id++[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")+def test_generate_excluded_shipping_methods_for_order(mocked_fetch, order):+ shipping_method = ShippingMethodData(+ id="123",+ price=Money(Decimal("10.59"), "USD"),+ name="shipping",+ maximum_order_weight=Weight(kg=10),+ minimum_order_weight=Weight(g=1),+ maximum_delivery_days=10,+ minimum_delivery_days=2,+ )+ response = json.loads(+ generate_excluded_shipping_methods_for_order_payload(order, [shipping_method])+ )++ assert "order" in response+ assert response["shipping_methods"] == [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "123"),+ "price": "10.59",+ "currency": "USD",+ "name": "shipping",+ "maximum_order_weight": "10.0:kg",+ "minimum_order_weight": "1.0:g",+ "maximum_delivery_days": 10,+ "minimum_delivery_days": 2,+ }+ ]+ mocked_fetch.assert_not_called()diff --git a/saleor/order/tests/webhooks/test_exclude_shipping_cache.py b/saleor/order/tests/webhooks/test_exclude_shipping_cache.pynew file mode 100644index 0000000000..bf8d1c087d--- /dev/null+++ b/saleor/order/tests/webhooks/test_exclude_shipping_cache.py@@ -0,0 +1,212 @@+import json+import uuid+from decimal import Decimal+from unittest import mock++import graphene+import pytest+from measurement.measures import Weight+from prices import Money++from ....shipping.interface import ShippingMethodData+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,+)+++def available_shipping_methods_factory():+ def factory(num_methods=1) -> list[ShippingMethodData]:+ methods = []+ for i in range(num_methods):+ methods.append(+ ShippingMethodData(+ id=str(i),+ price=Money(Decimal(10), "usd"),+ name=uuid.uuid4().hex,+ maximum_order_weight=Weight(kg=0),+ minimum_order_weight=Weight(kg=0),+ maximum_delivery_days=0,+ minimum_delivery_days=5,+ )+ )+ return methods++ return factory++[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.order.webhooks.exclude_shipping.generate_excluded_shipping_methods_for_order_payload"+)+def test_excluded_shipping_methods_for_order_use_cache(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ mocked_cache_get,+ order_with_lines,+ available_shipping_methods_factory,+ app_exclude_shipping_for_order,+):+ # given++ webhook_reason = "Order contains dangerous products."++ mocked_webhook.return_value = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }+ payload = json.dumps({"order": {"id": 1, "some_field": "12"}})+ mocked_payload.return_value = payload++ mocked_cache_get.return_value = (payload, [{"id": "1", "reason": webhook_reason}])++ available_shipping_methods = available_shipping_methods_factory(num_methods=2)++ # when+ excluded_shipping_methods_for_order(+ order=order_with_lines,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )++ # then+ assert not mocked_webhook.called++ assert not mocked_cache_set.called++[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.order.webhooks.exclude_shipping.generate_excluded_shipping_methods_for_order_payload"+)+def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ mocked_cache_get,+ order_with_lines,+ available_shipping_methods_factory,+ app_exclude_shipping_for_order,+):+ # given+ shipping_app = app_exclude_shipping_for_order+ shipping_webhook = shipping_app.webhooks.get()+ webhook_reason = "Order contains dangerous products."++ webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }++ mocked_webhook.return_value = webhook_response++ payload_dict = {"order": {"id": 1, "some_field": "12"}}+ payload = json.dumps(payload_dict)+ mocked_payload.return_value = payload++ mocked_cache_get.return_value = None++ available_shipping_methods = available_shipping_methods_factory(num_methods=2)++ # when+ excluded_shipping_methods_for_order(+ order=order_with_lines,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )++ # then+ assert mocked_webhook.called++ expected_cache_key = generate_cache_key_for_webhook(+ payload_dict,+ shipping_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ shipping_app.id,+ )++ mocked_cache_set.assert_called_once_with(+ expected_cache_key,+ webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ )++[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.order.webhooks.exclude_shipping.generate_excluded_shipping_methods_for_order_payload"+)+def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_different(+ mocked_payload,+ mocked_webhook,+ mocked_cache_set,+ mocked_cache_get,+ order_with_lines,+ available_shipping_methods_factory,+ app_exclude_shipping_for_order,+):+ # given+ shipping_app = app_exclude_shipping_for_order+ shipping_webhook = shipping_app.webhooks.get()+ webhook_reason = "Order contains dangerous products."+ webhook_response = {+ "excluded_methods": [+ {+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),+ "reason": webhook_reason,+ }+ ]+ }+ mocked_webhook.return_value = webhook_response++ payload_dict = {"order": {"id": 1, "some_field": "12"}}+ payload = json.dumps(payload_dict)+ mocked_payload.return_value = payload++ mocked_cache_get.return_value = None++ available_shipping_methods = available_shipping_methods_factory(num_methods=2)++ # when+ excluded_shipping_methods_for_order(+ order=order_with_lines,+ available_shipping_methods=available_shipping_methods,+ allow_replica=False,+ requestor=None,+ )+ # then+ assert mocked_webhook.called++ expected_cache_key = generate_cache_key_for_webhook(+ payload_dict,+ shipping_webhook.target_url,+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ shipping_app.id,+ )++ mocked_cache_get.assert_called_once_with(expected_cache_key)+ mocked_cache_set.assert_called_once_with(+ expected_cache_key,+ webhook_response,+ timeout=CACHE_EXCLUDED_SHIPPING_TIME,+ )diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 1ea20413ba..cf749ffa67 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -46,12 +46,6 @@ from ..giftcard.search import mark_gift_cards_search_index_as_dirtyfrom ..payment import TransactionEventTypefrom ..payment.model_helpers import get_total_authorizedfrom ..product.utils.digital_products import get_default_digital_content_settings-from ..shipping.interface import ShippingMethodData-from ..shipping.models import ShippingMethod, ShippingMethodChannelListing-from ..shipping.utils import (- convert_to_shipping_method_data,- initialize_shipping_method_active_status,-)from ..tax.utils import get_display_gross_prices, get_tax_class_kwargs_for_order_linefrom ..warehouse.management import (decrease_allocations,@@ -59,7 +53,6 @@ from ..warehouse.management import (increase_allocations,increase_stock,)-from ..warehouse.models import Warehousefrom . import (ORDER_EDITABLE_STATUS,FulfillmentStatus,@@ -86,9 +79,6 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"--def get_order_country(order: Order) -> str:"""Return country to which order will be shipped."""return get_active_country(@@ -693,94 +683,10 @@ def sum_order_totals(qs, currency_code):)-def get_all_shipping_methods_for_order(- order: Order,- shipping_channel_listings: Iterable["ShippingMethodChannelListing"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-) -> list[ShippingMethodData]:- if not order.is_shipping_required(- database_connection_name=database_connection_name- ):- return []-- shipping_address = order.shipping_address- if not shipping_address:- return []-- all_methods = []-- shipping_methods = (- ShippingMethod.objects.using(database_connection_name)- .applicable_shipping_methods_for_instance(- order,- channel_id=order.channel_id,- price=order.subtotal.gross,- shipping_address=shipping_address,- country_code=shipping_address.country.code,- database_connection_name=database_connection_name,- )- .prefetch_related("channel_listings")- )-- listing_map = {- listing.shipping_method_id: listing for listing in shipping_channel_listings- }-- for method in shipping_methods:- listing = listing_map.get(method.id)- if listing:- shipping_method_data = convert_to_shipping_method_data(method, listing)- all_methods.append(shipping_method_data)- return all_methods---def get_valid_shipping_methods_for_order(- order: Order,- shipping_channel_listings: Iterable["ShippingMethodChannelListing"],- manager: "PluginsManager",- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,- allow_sync_webhooks: bool = True,-) -> list[ShippingMethodData]:- """Return a list of shipping methods according to Saleor's own business logic."""- valid_methods = get_all_shipping_methods_for_order(- order, shipping_channel_listings, database_connection_name- )- if not valid_methods:- return []-- if order.status in ORDER_EDITABLE_STATUS and allow_sync_webhooks:- excluded_methods = manager.excluded_shipping_methods_for_order(- order, valid_methods- )- initialize_shipping_method_active_status(valid_methods, excluded_methods)-- return valid_methods---def is_shipping_required(lines: Iterable["OrderLine"]):- return any(line.is_shipping_required for line in lines)--def get_total_quantity(lines: Iterable["OrderLine"]):return sum([line.quantity for line in lines])-def get_valid_collection_points_for_order(- lines: Iterable["OrderLine"],- channel_id: int,- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- if not is_shipping_required(lines):- return []-- line_ids = [line.id for line in lines]- qs = OrderLine.objects.using(database_connection_name).filter(id__in=line_ids)-- return Warehouse.objects.using(- database_connection_name- ).applicable_for_click_and_collect(qs, channel_id)--def get_discounted_lines(lines, voucher):discounted_products = voucher.products.all()discounted_categories = set(voucher.categories.all())@@ -1418,9 +1324,3 @@ def calculate_draft_order_line_price_expiration_date(now = timezone.now()return now + timedelta(hours=freeze_period)return None---def get_external_shipping_id(order: "Order"):- if not order:- return None- return order.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)diff --git a/saleor/order/webhooks/__init__.py b/saleor/order/webhooks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/order/webhooks/exclude_shipping.py b/saleor/order/webhooks/exclude_shipping.pynew file mode 100644index 0000000000..05b4f8a188--- /dev/null+++ b/saleor/order/webhooks/exclude_shipping.py@@ -0,0 +1,230 @@+import json+import logging+from collections import defaultdict+from collections.abc import Callable+from dataclasses import dataclass+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 ...core.db.connection import allow_writer+from ...core.utils.json_serializer import CustomJsonEncoder+from ...shipping.interface import ShippingMethodData+from ...webhook import traced_payload_generator+from ...webhook.event_types import WebhookEventSyncType+from ...webhook.models import Webhook+from ...webhook.payloads import (+ generate_order_payload,+ generate_payload_for_shipping_method,+)+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:+ 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__)+++@dataclass+class ExcludedShippingMethod:+ id: str+ reason: str | None+++@allow_writer()+@traced_payload_generator+def generate_excluded_shipping_methods_for_order_payload(+ order: "Order",+ available_shipping_methods: list[ShippingMethodData],+):+ order_data = json.loads(generate_order_payload(order))[0]+ payload = {+ "order": order_data,+ "shipping_methods": [+ generate_payload_for_shipping_method(shipping_method)+ for shipping_method in available_shipping_methods+ ],+ }+ return json.dumps(payload, cls=CustomJsonEncoder)+++def excluded_shipping_methods_for_order(+ order: "Order",+ available_shipping_methods: list["ShippingMethodData"],+ allow_replica: bool,+ requestor: Union["App", "User", None],+) -> Promise[list[ExcludedShippingMethod]]:+ if not available_shipping_methods:+ return Promise.resolve([])++ generate_function = generate_excluded_shipping_methods_for_order_payload+ payload_fun = lambda: generate_function( # noqa: E731+ order,+ available_shipping_methods,+ )+ return _get_excluded_shipping_data(+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,+ payload_fun=payload_fun,+ subscribable_object=(order, available_shipping_methods),+ allow_replica=allow_replica,+ requestor=requestor,+ )+++def _get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:+ payload_dict = json.loads(payload)+ source_object = payload_dict.get("checkout", payload_dict.get("order", {}))++ # drop fields that change between requests but are not relevant for cache key+ source_object.pop("last_change", None)+ source_object.pop("meta", None)+ source_object.pop("shipping_method", None)+ return payload_dict+++def _get_excluded_shipping_methods_or_fetch(+ webhooks: QuerySet,+ event_type: str,+ payload: str,+ subscribable_object: (+ tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None+ ),+ allow_replica: bool,+ requestor: 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.+ """+ cache_data = _get_cache_data_for_exclude_shipping_methods(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,+ 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,+ )+ )++ 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,+ payload_fun: Callable[[], str],+ subscribable_object: (+ tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None+ ),+ 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:+ payload = payload_fun()+ promised_excluded_methods_map = _get_excluded_shipping_methods_or_fetch(+ webhooks,+ event_type,+ 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_mapdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 8d4b55d91d..509ce32a64 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -2875,24 +2875,6 @@ class PluginsManager(PaymentInterface):plugin, "external_verify", default_value, data, request)- def excluded_shipping_methods_for_order(- self,- order: "Order",- available_shipping_methods: list["ShippingMethodData"],- ) -> list[ExcludedShippingMethod]:- default_value: list[ExcludedShippingMethod] = []-- if not available_shipping_methods:- return default_value-- return self.__run_method_on_plugins(- "excluded_shipping_methods_for_order",- default_value,- order,- available_shipping_methods,- channel_slug=order.channel.slug,- )-def excluded_shipping_methods_for_checkout(self,checkout: "Checkout",diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex 69b29241c5..ac4778cbbf 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -1705,58 +1705,3 @@ def test_excluded_shipping_methods_for_checkout_dont_run_webhook_on_missing_ship# then webhook should not be emittedmock__run_method_on_plugins.assert_not_called()--- "saleor.plugins.manager.PluginsManager._PluginsManager__run_method_on_plugins"-)-def test_excluded_shipping_methods_for_order_run_webhook_on_existing_shipping_methods(- mock__run_method_on_plugins, draft_order-):- plugins = [- "saleor.plugins.tests.sample_plugins.PluginSample",- ]-- manager = PluginsManager(plugins=plugins)-- # given shipping methods contain at least 1 method-- shipping_method = ShippingMethodData(- id="123",- price=Money(Decimal("10.59"), "USD"),- )-- non_empty_shipping_methods = [shipping_method]-- # when manager executes for shipping methods exclusion-- manager.excluded_shipping_methods_for_order(draft_order, non_empty_shipping_methods)-- # then webhook should be emitted-- mock__run_method_on_plugins.assert_called_once()--- "saleor.plugins.manager.PluginsManager._PluginsManager__run_method_on_plugins"-)-def test_excluded_shipping_methods_for_order_dont_run_webhook_on_missing_shipping_methods(- mock__run_method_on_plugins, draft_order-):- plugins = [- "saleor.plugins.tests.sample_plugins.PluginSample",- ]-- manager = PluginsManager(plugins=plugins)-- # given shipping methods are empty-- empty_shipping_methods = []-- # when manager executes for shipping methods exclusion-- manager.excluded_shipping_methods_for_order(draft_order, empty_shipping_methods)-- # then webhook should not be emitted-- mock__run_method_on_plugins.assert_not_called()diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 4b4ef1386c..31ed1c3348 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -70,7 +70,6 @@ from ...webhook.payloads import (generate_collection_payload,generate_customer_payload,generate_excluded_shipping_methods_for_checkout_payload,- generate_excluded_shipping_methods_for_order_payload,generate_fulfillment_payload,generate_invoice_payload,generate_list_gateways_payload,@@ -3702,26 +3701,6 @@ class WebhookPlugin(BasePlugin):description=description,)- def excluded_shipping_methods_for_order(- self,- order: "Order",- available_shipping_methods: list["ShippingMethodData"],- previous_value: list[ExcludedShippingMethod],- ) -> list[ExcludedShippingMethod]:- generate_function = generate_excluded_shipping_methods_for_order_payload- payload_fun = lambda: generate_function( # noqa: E731- order,- available_shipping_methods,- )- return get_excluded_shipping_data(- event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- previous_value=previous_value,- payload_fun=payload_fun,- subscribable_object=(order, available_shipping_methods),- allow_replica=self.allow_replica,- requestor=self.requestor,- )-def excluded_shipping_methods_for_checkout(self,checkout: "Checkout",diff --git a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.pyindex e9a4e399c3..eae4c7b133 100644--- a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py+++ b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py@@ -9,196 +9,6 @@ from ....webhook.transport.utils import generate_cache_key_for_webhookfrom ...base_plugin import ExcludedShippingMethod[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"-)-def test_excluded_shipping_methods_for_order_use_cache(- mocked_payload,- mocked_webhook,- mocked_cache_set,- mocked_cache_get,- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,- shipping_app_factory,-):- # given- shipping_app_factory()- webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."-- mocked_webhook.return_value = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }- payload = json.dumps({"order": {"id": 1, "some_field": "12"}})- mocked_payload.return_value = payload-- mocked_cache_get.return_value = (payload, [{"id": "1", "reason": webhook_reason}])-- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-- # when- plugin.excluded_shipping_methods_for_order(- order=order_with_lines,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )- # then- assert not mocked_webhook.called-- assert not mocked_cache_set.called--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"-)-def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(- mocked_payload,- mocked_webhook,- mocked_cache_set,- mocked_cache_get,- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,- shipping_app_factory,-):- # given- shipping_app = shipping_app_factory()- shipping_webhook = shipping_app.webhooks.get()- webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."-- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }-- mocked_webhook.return_value = webhook_response-- payload_dict = {"order": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload-- mocked_cache_get.return_value = None-- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-- # when- plugin.excluded_shipping_methods_for_order(- order=order_with_lines,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )- # then- assert mocked_webhook.called-- expected_cache_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- shipping_app.id,- )-- mocked_cache_set.assert_called_once_with(- expected_cache_key,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"-)-def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_different(- mocked_payload,- mocked_webhook,- mocked_cache_set,- mocked_cache_get,- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,- shipping_app_factory,-):- # given- shipping_app = shipping_app_factory()- shipping_webhook = shipping_app.webhooks.get()- webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }- mocked_webhook.return_value = webhook_response-- payload_dict = {"order": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload-- mocked_cache_get.return_value = None-- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-- # when- plugin.excluded_shipping_methods_for_order(- order=order_with_lines,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )- # then- assert mocked_webhook.called-- expected_cache_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- shipping_app.id,- )-- mocked_cache_get.assert_called_once_with(expected_cache_key)- mocked_cache_set.assert_called_once_with(- expected_cache_key,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )--@mock.patch("saleor.webhook.transport.synchronous.transport.cache.get")@mock.patch("saleor.webhook.transport.synchronous.transport.cache.set")@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex fe87718e1e..cf2e55de97 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -3,20 +3,17 @@ from unittest import mockfrom unittest.mock import callimport graphene-import pytestfrom ....core.models import EventDeliveryfrom ....graphql.core.utils import to_global_id_or_nonefrom ....graphql.tests.utils import get_graphql_contentfrom ....graphql.webhook.utils import get_subscription_query_hash-from ....order import OrderStatusfrom ....shipping.models import ShippingMethodfrom ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIMEfrom ....webhook.event_types import WebhookEventSyncTypefrom ....webhook.models import Webhookfrom ....webhook.payloads import (generate_excluded_shipping_methods_for_checkout_payload,- generate_excluded_shipping_methods_for_order_payload,)from ....webhook.response_schemas.shipping import logger as schema_loggerfrom ....webhook.response_schemas.utils.annotations import logger as annotations_logger@@ -30,25 +27,6 @@ from ....webhook.transport.synchronous.transport import trigger_webhook_syncfrom ....webhook.transport.utils import generate_cache_key_for_webhookfrom ...base_plugin import ExcludedShippingMethod-ORDER_QUERY_SHIPPING_METHOD = """-query OrderQuery($id: ID) {- order(id: $id) {- shippingMethods {- id- name- active- message- }- availableShippingMethods {- id- name- active- message- }- }-}-"""-CHECKOUT_QUERY_SHIPPING_METHOD = """query Checkout($id: ID){checkout(id: $id) {@@ -67,336 +45,6 @@ query Checkout($id: ID){"""[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_order_payload"-)-def test_excluded_shipping_methods_for_order(- mocked_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,- shipping_app_factory,- settings,-):- # given- shipping_app = shipping_app_factory()- shipping_webhook = shipping_app.webhooks.get()- webhook_reason = "Order contains dangerous products."- other_reason = "Shipping is not applicable for this order."- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }- mocked_webhook.return_value = webhook_response- payload_dict = {"order": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = [- ExcludedShippingMethod(id="1", reason=other_reason),- ExcludedShippingMethod(id="2", reason=other_reason),- ]-- # when- excluded_methods = plugin.excluded_shipping_methods_for_order(- order=order_with_lines,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert other_reason in em.reason-- mocked_webhook.assert_called_once_with(- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- payload,- shipping_webhook,- False,- subscribable_object=(order_with_lines, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- expected_cache_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- shipping_app.id,- )-- mocked_cache_set.assert_called_once_with(- expected_cache_key,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"-)-def test_multiple_app_with_excluded_shipping_methods_for_order(- mocked_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,- shipping_app_factory,- settings,-):- # given- shipping_app = shipping_app_factory()- shipping_webhook = shipping_app.webhooks.get()-- second_shipping_app = shipping_app_factory(app_name="shipping-app2")- second_shipping_webhook = second_shipping_app.webhooks.get()- webhook_reason = "Order contains dangerous products."- webhook_second_reason = "Shipping is not applicable for this order."- first_webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }- second_webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_second_reason,- },- {- "id": graphene.Node.to_global_id("ShippingMethod", "2"),- "reason": webhook_second_reason,- },- ]- }-- mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]-- payload_dict = {"order": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = []-- # when- excluded_methods = plugin.excluded_shipping_methods_for_order(- order=order_with_lines,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )-- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert webhook_second_reason in em.reason- event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS- mocked_webhook.assert_any_call(- event_type,- payload,- shipping_webhook,- False,- subscribable_object=(order_with_lines, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- mocked_webhook.assert_any_call(- event_type,- payload,- second_shipping_webhook,- False,- subscribable_object=(order_with_lines, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- assert mocked_webhook.call_count == 2- expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- shipping_app.id,- )- expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(- payload_dict,- second_shipping_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- second_shipping_app.id,- )-- assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key-- mocked_cache_set.assert_has_calls(- [- call(- expected_cache_for_first_webhook_key,- first_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- call(- expected_cache_for_second_webhook_key,- second_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- ]- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.trigger_webhook_sync")- "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"-)-def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_order(- mocked_payload,- mocked_webhook,- mocked_cache_set,- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,- shipping_app_factory,- settings,-):- # given- shipping_app = shipping_app_factory()- first_webhook = shipping_app.webhooks.get()- event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS-- # create the second webhook with the same event- second_webhook = Webhook.objects.create(- name="shipping-webhook-1",- app=shipping_app,- target_url="https://shipping-gateway.com/apiv2/",- )- second_webhook.events.create(- event_type=event_type,- webhook=second_webhook,- )-- webhook_reason = "Order contains dangerous products."- webhook_second_reason = "Shipping is not applicable for this order."-- first_webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }- second_webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_second_reason,- },- {- "id": graphene.Node.to_global_id("ShippingMethod", "2"),- "reason": webhook_second_reason,- },- ]- }-- mocked_webhook.side_effect = [first_webhook_response, second_webhook_response]-- payload_dict = {"order": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload- plugin = webhook_plugin()- available_shipping_methods = available_shipping_methods_factory(num_methods=2)- previous_value = []-- # when- excluded_methods = plugin.excluded_shipping_methods_for_order(- order=order_with_lines,- available_shipping_methods=available_shipping_methods,- previous_value=previous_value,- )-- # then- assert len(excluded_methods) == 2- em = excluded_methods[0]- assert em.id == "1"- assert webhook_reason in em.reason- assert webhook_second_reason in em.reason-- mocked_webhook.assert_any_call(- event_type,- payload,- first_webhook,- False,- subscribable_object=(order_with_lines, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- mocked_webhook.assert_any_call(- event_type,- payload,- second_webhook,- False,- subscribable_object=(order_with_lines, available_shipping_methods),- timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,- requestor=None,- pregenerated_subscription_payload=None,- )- assert mocked_webhook.call_count == 2-- expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(- payload_dict,- first_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- shipping_app.id,- )- expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(- payload_dict,- second_webhook.target_url,- WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,- shipping_app.id,- )- assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key-- mocked_cache_set.assert_has_calls(- [- call(- expected_cache_for_first_webhook_key,- first_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- call(- expected_cache_for_second_webhook_key,- second_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- ]- )--@mock.patch.object(annotations_logger, "warning")@mock.patch.object(schema_logger, "warning")def test_parse_excluded_shipping_methods_response(@@ -477,162 +125,6 @@ def test_parse_excluded_shipping_methods_response_invalid(assert "Skipping invalid shipping method (FilterShippingMethodsSchema)" in error_msg- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_order"-)-def test_order_shipping_methods(- mocked_webhook,- staff_api_client,- order_with_lines,- permission_group_manage_orders,- settings,-):- # given- order_with_lines.status = OrderStatus.UNCONFIRMED- order_with_lines.save(update_fields=["status"])- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- webhook_reason = "spanish-inquisition"- excluded_shipping_method_id = order_with_lines.shipping_method.id- mocked_webhook.return_value = [- ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)- ]- permission_group_manage_orders.user_set.add(staff_api_client.user)- # when- response = staff_api_client.post_graphql(- ORDER_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(order_with_lines)},- )- content = get_graphql_content(response)- order_data = content["data"]["order"]-- shipping_methods = order_data["shippingMethods"]- # then- assert len(shipping_methods) == 1- assert not shipping_methods[0]["active"]- assert shipping_methods[0]["message"] == webhook_reason--- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_order"-)-def test_draft_order_shipping_methods(- mocked_webhook,- staff_api_client,- order_with_lines,- permission_group_manage_orders,- settings,-):- # given- order_with_lines.status = OrderStatus.DRAFT- order_with_lines.save(update_fields=["status"])- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- webhook_reason = "spanish-inquisition"- excluded_shipping_method_id = order_with_lines.shipping_method.id- mocked_webhook.return_value = [- ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)- ]- permission_group_manage_orders.user_set.add(staff_api_client.user)-- # when- response = staff_api_client.post_graphql(- ORDER_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(order_with_lines)},- )- content = get_graphql_content(response)- order_data = content["data"]["order"]-- shipping_methods = order_data["shippingMethods"]- # then- assert len(shipping_methods) == 1- assert not shipping_methods[0]["active"]- assert shipping_methods[0]["message"] == webhook_reason--- "order_status",- [- OrderStatus.UNFULFILLED,- OrderStatus.PARTIALLY_FULFILLED,- OrderStatus.FULFILLED,- OrderStatus.CANCELED,- OrderStatus.EXPIRED,- OrderStatus.RETURNED,- OrderStatus.PARTIALLY_RETURNED,- ],-)- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_order"-)-def test_order_shipping_methods_skips_sync_webhook_for_non_editable_statuses(- mocked_webhook,- order_status,- staff_api_client,- order_with_lines,- permission_group_manage_orders,- settings,-):- # given- order_with_lines.status = order_status- order_with_lines.save(update_fields=["status"])- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]-- permission_group_manage_orders.user_set.add(staff_api_client.user)-- # when- response = staff_api_client.post_graphql(- ORDER_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(order_with_lines)},- )- content = get_graphql_content(response)- order_data = content["data"]["order"]-- shipping_methods = order_data["shippingMethods"]-- # then- assert not mocked_webhook.called- assert len(shipping_methods) == 1- assert shipping_methods[0]["active"]--- ("webhook_response", "expected_count"),- [(lambda s: [ExcludedShippingMethod(s.id, "")], 0), (lambda s: [], 1)],-)- "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_order"-)-def test_order_available_shipping_methods(- mocked_webhook,- staff_api_client,- order_with_lines,- permission_group_manage_orders,- settings,- webhook_response,- expected_count,-):- # given- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- order_with_lines.status = OrderStatus.UNCONFIRMED- order_with_lines.save(update_fields=["status"])- shipping_method = order_with_lines.shipping_method-- def respond(*args, **kwargs):- return webhook_response(shipping_method)-- mocked_webhook.side_effect = respond- permission_group_manage_orders.user_set.add(staff_api_client.user)- # when- response = staff_api_client.post_graphql(- ORDER_QUERY_SHIPPING_METHOD,- variables={"id": to_global_id_or_none(order_with_lines)},- )- content = get_graphql_content(response)- order_data = content["data"]["order"]-- # then- assert len(order_data["availableShippingMethods"]) == expected_count--@mock.patch("saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_checkout")@@ -1215,34 +707,6 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch)-def test_generate_excluded_shipping_methods_for_order_payload(- webhook_plugin,- order_with_lines,- available_shipping_methods_factory,-):- # given- methods = available_shipping_methods_factory(num_methods=3)- # when- json_payload = json.loads(- generate_excluded_shipping_methods_for_order_payload(- order=order_with_lines, available_shipping_methods=methods- )- )- # then- assert len(json_payload["shipping_methods"]) == 3- assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(- "ShippingMethod", methods[0].id- )- assert json_payload["shipping_methods"][1]["id"] == graphene.Node.to_global_id(- "ShippingMethod", methods[1].id- )- assert json_payload["shipping_methods"][2]["id"] == graphene.Node.to_global_id(- "ShippingMethod", methods[2].id- )- graphql_order_id = graphene.Node.to_global_id("Order", order_with_lines.id)- assert json_payload["order"]["id"] == graphql_order_id--def test_generate_excluded_shipping_methods_for_checkout_payload(webhook_plugin,checkout_with_items,diff --git a/saleor/tests/e2e/orders/discounts/test_gift_promotion_applied_on_draft_order.py b/saleor/tests/e2e/orders/discounts/test_gift_promotion_applied_on_draft_order.pyindex 55dd1ffcfd..10b74a5f6b 100644--- a/saleor/tests/e2e/orders/discounts/test_gift_promotion_applied_on_draft_order.py+++ b/saleor/tests/e2e/orders/discounts/test_gift_promotion_applied_on_draft_order.py@@ -10,6 +10,7 @@ from ..utils import (draft_order_complete,draft_order_create,order_lines_create,+ order_query,order_update_shipping,)@@ -194,7 +195,12 @@ def test_order_promotion_with_gift_reward_should_be_applied_to_draft_order_with_assert order["total"]["tax"]["amount"] == expected_total_tax# Assert gift line- order_lines = order["lines"]+ # Making separate request, as due to current approach of creating the gift line,+ # gift line could be visible in second request. It depends on the sequence of calling+ # dataloaders. If dataloader will have a cache without gift line then it won't be visible in response+ # for the mutation. This needs to be addressed in separate task: ENG-1227.+ order_data = order_query(e2e_staff_api_client, order_id)+ order_lines = order_data["lines"]assert len(order_lines) == 2gift_line = order_lines[1]assert gift_line["totalPrice"]["gross"]["amount"] == 0diff --git a/saleor/tests/e2e/orders/utils/fragments.py b/saleor/tests/e2e/orders/utils/fragments.pyindex b92cfd554c..c2588cb1af 100644--- a/saleor/tests/e2e/orders/utils/fragments.py+++ b/saleor/tests/e2e/orders/utils/fragments.py@@ -11,6 +11,7 @@ fragment OrderLine on OrderLine {translatedProductNameproductVariantIdisShippingRequired+ isGiftquantityquantityFulfilledunitPrice {diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 453a0205f1..3b3821fc35 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -323,6 +323,8 @@ def generate_order_payload("created": lambda f: f.created_at,},)+ shipping_tax_rate = order.shipping_tax_rate or Decimal(0)+ shipping_tax_rate = shipping_tax_rate.quantize(Decimal("0.0001"))extra_dict_data = {"id": graphene.Node.to_global_id("Order", order.id),@@ -342,6 +344,7 @@ def generate_order_payload("shipping_method": _generate_shipping_method_payload(order.shipping_method, order.channel),+ "shipping_tax_rate": shipping_tax_rate,}if with_meta:extra_dict_data["meta"] = generate_meta(@@ -1242,7 +1245,7 @@ def generate_translation_payload(return json.dumps(translation_data)-def _generate_payload_for_shipping_method(method: ShippingMethodData):+def generate_payload_for_shipping_method(method: ShippingMethodData):payload = {"id": method.graphql_id,"price": method.price.amount,@@ -1256,23 +1259,6 @@ def _generate_payload_for_shipping_method(method: ShippingMethodData):return payload-@allow_writer()-@traced_payload_generator-def generate_excluded_shipping_methods_for_order_payload(- order: "Order",- available_shipping_methods: list[ShippingMethodData],-):- order_data = json.loads(generate_order_payload(order))[0]- payload = {- "order": order_data,- "shipping_methods": [- _generate_payload_for_shipping_method(shipping_method)- for shipping_method in available_shipping_methods- ],- }- return json.dumps(payload, cls=CustomJsonEncoder)--@allow_writer()@traced_payload_generatordef generate_excluded_shipping_methods_for_checkout_payload(@@ -1283,7 +1269,7 @@ 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],}diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex 7b2c130bcf..a4487dce34 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -11,7 +11,7 @@ from ....channel.models import Channelfrom ....giftcard.models import GiftCardfrom ....graphql.webhook.subscription_query import SubscriptionQueryfrom ....menu.models import Menu, MenuItem-from ....order.utils import get_all_shipping_methods_for_order+from ....order.delivery_context import get_all_shipping_methods_for_orderfrom ....product.models import Categoryfrom ....shipping.interface import ShippingMethodDatafrom ....shipping.models import (diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 67d6da0316..58e7885a04 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -43,7 +43,6 @@ from ..payloads import (generate_collection_payload,generate_customer_payload,generate_excluded_shipping_methods_for_checkout_payload,- generate_excluded_shipping_methods_for_order_payload,generate_fulfillment_lines_payload,generate_invoice_payload,generate_list_gateways_payload,@@ -2547,37 +2546,6 @@ def test_generate_checkout_payload(}-@patch("saleor.order.calculations.fetch_order_prices_if_expired")-def test_generate_excluded_shipping_methods_for_order(mocked_fetch, order):- shipping_method = ShippingMethodData(- id="123",- price=Money(Decimal("10.59"), "USD"),- name="shipping",- maximum_order_weight=Weight(kg=10),- minimum_order_weight=Weight(g=1),- maximum_delivery_days=10,- minimum_delivery_days=2,- )- response = json.loads(- generate_excluded_shipping_methods_for_order_payload(order, [shipping_method])- )-- assert "order" in response- assert response["shipping_methods"] == [- {- "id": graphene.Node.to_global_id("ShippingMethod", "123"),- "price": "10.59",- "currency": "USD",- "name": "shipping",- "maximum_order_weight": "10.0:kg",- "minimum_order_weight": "1.0:g",- "maximum_delivery_days": 10,- "minimum_delivery_days": 2,- }- ]- mocked_fetch.assert_not_called()--def test_generate_excluded_shipping_methods_for_checkout(checkout):shipping_method = ShippingMethodData(id="123",diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex bc163de300..00358a8dd8 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -2,13 +2,14 @@ import jsonimport loggingfrom collections.abc import Callablefrom json import JSONDecodeError-from typing import TYPE_CHECKING, Any, TypeVar+from typing import TYPE_CHECKING, Any, TypeVar, Unionfrom urllib.parse import urlparsefrom django.conf import settingsfrom django.core.cache import cachefrom django.db import transactionfrom opentelemetry.trace import StatusCode+from promise import Promisefrom pydantic import ValidationErrorfrom ....celeryconf import app@@ -22,6 +23,7 @@ from ....core.utils.events import call_eventfrom ....core.utils.url import sanitize_url_for_loggingfrom ....graphql.webhook.subscription_payload import (generate_payload_from_subscription,+ generate_payload_promise_from_subscription,initialize_request,)from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP@@ -59,6 +61,8 @@ from ..utils import ()if TYPE_CHECKING:+ from ....account.models import User+ from ....app.models import Appfrom ....graphql.core.context import SaleorContextfrom ....graphql.core.dataloaders import DataLoaderfrom ....webhook.models import Webhook@@ -202,6 +206,68 @@ def send_webhook_request_sync(return response_data if response.status == EventDeliveryStatus.SUCCESS else None+def trigger_webhook_sync_promise_if_not_cached(+ event_type: str,+ payload: str,+ webhook: "Webhook",+ cache_data: dict,+ allow_replica: bool,+ subscribable_object=None,+ request_timeout=None,+ cache_timeout=None,+ request=None,+ requestor: Union["App", "User", None] = None,+) -> Promise[dict | None]:+ """Get response for synchronous webhook.++ - Send a synchronous webhook request if cache is expired.+ - Fetch response from cache if it is still valid.+ """++ cache_key = generate_cache_key_for_webhook(+ cache_data, webhook.target_url, event_type, webhook.app_id+ )++ response_data = cache.get(cache_key)+ if response_data == const.SYNC_WEBHOOK_FAILURE_SENTINEL:+ # Prevent sending webhook if the previous one failed recently.+ logger.warning(+ "[Webhook] Skipping request to %s for event %s due to previous failure.",+ sanitize_url_for_logging(webhook.target_url),+ event_type,+ )+ return Promise.resolve(None)++ if response_data is not None:+ return Promise.resolve(response_data)++ def process_response_data(response_data: dict | None) -> dict | None:+ if response_data is not None:+ cache.set(+ cache_key,+ response_data,+ timeout=cache_timeout or const.WEBHOOK_CACHE_DEFAULT_TTL,+ )+ else:+ cache.set(+ cache_key,+ const.SYNC_WEBHOOK_FAILURE_SENTINEL,+ timeout=const.SYNC_WEBHOOK_FAILURE_CACHE_TTL,+ )+ return response_data++ return trigger_webhook_sync_promise(+ event_type,+ payload,+ webhook,+ allow_replica,+ subscribable_object=subscribable_object,+ timeout=request_timeout,+ request=request,+ requestor=requestor,+ ).then(process_response_data)++def trigger_webhook_sync_if_not_cached(event_type: str,payload: str,@@ -331,6 +397,75 @@ def create_delivery_for_subscription_sync_event(return event_delivery+def create_promise_delivery_for_subscription_sync_event(+ event_type,+ subscribable_object,+ webhook,+ requestor: Union["App", "User", None] = None,+ request=None,+ allow_replica=False,+ with_save=True,+) -> Promise[EventDelivery | None]:+ """Generate webhook payload based on subscription query and create delivery object.++ It uses a defined subscription query, defined for webhook to explicitly determine+ what fields should be included in the payload.++ :param event_type: event type which should be triggered.+ :param subscribable_object: subscribable object to process via subscription query.+ :param webhook: webhook object for which delivery will be created.+ :param requestor: used in subscription webhooks to generate meta data for payload.+ :param request: used to share context between sync event calls+ :param allow_replica: use replica database.+ :return: List of event deliveries to send via webhook tasks.+ """+ if event_type not in WEBHOOK_TYPES_MAP:+ logger.info(+ "Skipping subscription webhook. Event %s is not subscribable.", event_type+ )+ return Promise.resolve(None)++ if not request:+ request = initialize_request(+ app=webhook.app,+ requestor=requestor,+ sync_event=event_type in WebhookEventSyncType.ALL,+ event_type=event_type,+ allow_replica=allow_replica,+ )++ def create_delivery(data: dict | None) -> EventDelivery | None:+ if not data:+ logger.info(+ "No payload was generated with subscription for event: %s", event_type+ )+ # Return None so if subscription query returns no data Saleor will not crash but+ # log the issue and continue without creating a delivery.+ return None+ with allow_writer():+ # Use transaction to ensure EventPayload and EventDelivery are+ # created together, preventing inconsistent DB state.+ with transaction.atomic():+ event_payload = EventPayload(payload=json.dumps({**data}))+ event_delivery = EventDelivery(+ status=EventDeliveryStatus.PENDING,+ event_type=event_type,+ payload=event_payload,+ webhook=webhook,+ )+ if with_save:+ event_payload.save_as_file()+ event_delivery.save()+ return event_delivery++ return generate_payload_promise_from_subscription(+ event_type=event_type,+ subscribable_object=subscribable_object,+ subscription_query=webhook.subscription_query,+ request=request,+ ).then(create_delivery)++def trigger_webhook_sync(event_type: str,payload: str,@@ -371,8 +506,55 @@ def trigger_webhook_sync(return send_webhook_request_sync(delivery, **kwargs)+def trigger_webhook_sync_promise(+ event_type: str,+ payload: str,+ webhook: "Webhook",+ allow_replica,+ subscribable_object=None,+ timeout=None,+ request=None,+ requestor: Union["App", "User", None] = None,+) -> Promise[dict[Any, Any] | None]:+ """Send a synchronous webhook request."""++ def trigger_sync_for_delivery(+ delivery: EventDelivery | None,+ ) -> dict[Any, Any] | None:+ if not delivery:+ return None++ kwargs = {}+ if timeout:+ kwargs = {"timeout": timeout}++ return send_webhook_request_sync(delivery, **kwargs)++ if webhook.subscription_query:+ delivery_promise = create_promise_delivery_for_subscription_sync_event(+ event_type=event_type,+ subscribable_object=subscribable_object,+ webhook=webhook,+ requestor=requestor,+ request=request,+ allow_replica=allow_replica,+ with_save=False,+ )+ else:+ delivery_promise = Promise.resolve(+ EventDelivery(+ status=EventDeliveryStatus.PENDING,+ event_type=event_type,+ payload=EventPayload(payload=payload),+ webhook=webhook,+ )+ )+ return delivery_promise.then(trigger_sync_for_delivery)++if breaker_board := initialize_breaker_board():trigger_webhook_sync = breaker_board(trigger_webhook_sync)+ trigger_webhook_sync_promise = breaker_board(trigger_webhook_sync_promise)def trigger_taxes_all_webhooks_sync(