Skip to content

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

Block shipping webhooks for bulk checkouts queries (#17387)

Maciej Korycinski4da98aa85df1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2910c6c4e..f4e3e67071 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ All notable, unreleased changes to this project will be documented in this file.
- The provided data in the input field are merged with the existing one (previously the existing data was overridden by the new one).
- Fixed `invoiceRequest` no longer throws an error, when only app with webhook `INVOICE_REQUESTED` is installed, without invoice plugin - #17355 by @witoszekdev
- Queries: `checkouts`, `checkoutLines`, and `me.checkouts` will no longer trigger external calls to calculate taxes: the `CHECKOUT_CALCULATE_TAXES` webhooks and plugins (including AvataxPlugin) - #17268 by @korycins
+- Queries `checkouts`, `checkoutLines`, and `me.checkouts` will no longer trigger external calls to fetch shipping methods (`SHIPPING_LIST_METHODS_FOR_CHECKOUT`) or to filter the available shipping methods (`CHECKOUT_FILTER_SHIPPING_METHODS`) - #17387 by @korycins
### GraphQL API
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 7e465f7341..c9dd7f8366 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -84,7 +84,7 @@ def _trigger_checkout_sync_webhooks(
webhook_event_map: dict[str, set["Webhook"]],
address: Optional["Address"] = None,
):
- _ = checkout_info.all_shipping_methods
+ _ = checkout_info.get_all_shipping_methods()
# + timedelta(seconds=10) to confirm that triggered webhooks will still have
# valid prices. Triggered only when we have active sync tax webhook.
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index dbbe8a68db..e18f6de2d5 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -118,7 +118,7 @@ def base_checkout_undiscounted_delivery_price(
"""Calculate base (untaxed) undiscounted price for any kind of delivery method."""
from .fetch import ShippingMethodInfo
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
currency = checkout_info.checkout.currency
if not isinstance(delivery_method_info, ShippingMethodInfo):
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 3399f3aaf9..4b7760b214 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -32,7 +32,7 @@ from ..tax.utils import (
normalize_tax_rate_for_db,
validate_tax_data,
)
-from .fetch import ShippingMethodInfo, find_checkout_line_info
+from .fetch import find_checkout_line_info
from .models import Checkout
from .payment_utils import update_checkout_payment_statuses
@@ -302,22 +302,7 @@ def checkout_line_undiscounted_total_price(
return quantize_price(total_price, total_price.currency)
-def update_undiscounted_prices(
- checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]
-):
- delivery_method_info = checkout_info.delivery_method_info
- if isinstance(delivery_method_info, ShippingMethodInfo):
- shipping_method_data = delivery_method_info.delivery_method
- checkout_info.checkout.undiscounted_base_shipping_price_amount = (
- shipping_method_data.price.amount
- )
- else:
- checkout_info.checkout.undiscounted_base_shipping_price_amount = Decimal(0)
-
- _update_undiscounted_unit_price_for_lines(lines)
-
-
-def _update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):
+def update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):
"""Update line undiscounted unit price amount.
Undiscounted unit price stores the denormalized price of the variant.
@@ -395,7 +380,7 @@ def _fetch_checkout_prices_if_expired(
)
lines = cast(list, lines)
- update_undiscounted_prices(checkout_info, lines)
+ update_undiscounted_unit_price_for_lines(lines)
update_prior_unit_price_for_lines(lines)
create_or_update_discount_objects_from_promotion_for_checkout(
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index 5ed345ca5d..0ffd86055b 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -24,11 +24,13 @@ if TYPE_CHECKING:
def clean_checkout_shipping(
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- error_code: type[CheckoutErrorCode]
- | type[PaymentErrorCode]
- | type[OrderCreateFromCheckoutErrorCode],
+ error_code: (
+ type[CheckoutErrorCode]
+ | type[PaymentErrorCode]
+ | type[OrderCreateFromCheckoutErrorCode]
+ ),
):
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
if is_shipping_required(lines):
if not delivery_method_info.delivery_method:
@@ -63,9 +65,11 @@ def clean_checkout_shipping(
def clean_billing_address(
checkout_info: "CheckoutInfo",
- error_code: type[CheckoutErrorCode]
- | type[PaymentErrorCode]
- | type[OrderCreateFromCheckoutErrorCode],
+ error_code: (
+ type[CheckoutErrorCode]
+ | type[PaymentErrorCode]
+ | type[OrderCreateFromCheckoutErrorCode]
+ ),
):
if not checkout_info.billing_address:
raise ValidationError(
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index f4b871e18a..81ad7a6c56 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -178,7 +178,7 @@ def _process_shipping_data_for_order(
lines: list["CheckoutLineInfo"],
) -> dict[str, Any]:
"""Fetch, process and return shipping data from checkout."""
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
shipping_address = delivery_method_info.shipping_address
if (
@@ -387,7 +387,7 @@ def _create_line_for_order(
is_digital=is_digital,
variant=variant,
digital_content=variant.digital_content if is_digital and variant else None,
- warehouse_pk=checkout_info.delivery_method_info.warehouse_pk,
+ warehouse_pk=checkout_info.get_delivery_method_info().warehouse_pk,
line_discounts=line_discounts,
)
@@ -469,7 +469,7 @@ def _create_lines_for_order(
}
additional_warehouse_lookup = (
- checkout_info.delivery_method_info.get_warehouse_filter_lookup()
+ checkout_info.get_delivery_method_info().get_warehouse_filter_lookup()
)
check_stock_and_preorder_quantity_bulk(
variants,
@@ -477,7 +477,7 @@ def _create_lines_for_order(
quantities,
checkout_info.channel.slug,
global_quantity_limit=None,
- delivery_method_info=checkout_info.delivery_method_info,
+ delivery_method_info=checkout_info.get_delivery_method_info(),
additional_filter_lookup=additional_warehouse_lookup,
existing_lines=lines,
replace=True,
@@ -688,14 +688,14 @@ def _create_order(
country_code = checkout_info.get_country()
additional_warehouse_lookup = (
- checkout_info.delivery_method_info.get_warehouse_filter_lookup()
+ checkout_info.get_delivery_method_info().get_warehouse_filter_lookup()
)
allocate_stocks(
order_lines_info,
country_code,
checkout_info.channel,
manager,
- checkout_info.delivery_method_info.warehouse_pk,
+ checkout_info.get_delivery_method_info().warehouse_pk,
additional_warehouse_lookup,
check_reservations=True,
checkout_lines=[line.line for line in checkout_lines],
@@ -1139,14 +1139,14 @@ def _handle_allocations_of_order_lines(
):
country_code = checkout_info.get_country()
additional_warehouse_lookup = (
- checkout_info.delivery_method_info.get_warehouse_filter_lookup()
+ checkout_info.get_delivery_method_info().get_warehouse_filter_lookup()
)
allocate_stocks(
order_lines_info,
country_code,
checkout_info.channel,
manager,
- checkout_info.delivery_method_info.warehouse_pk,
+ checkout_info.get_delivery_method_info().warehouse_pk,
additional_warehouse_lookup,
check_reservations=True,
checkout_lines=[line.line for line in checkout_lines],
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 64aa94247f..e5f134f036 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -117,23 +117,60 @@ class CheckoutInfo:
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME
pregenerated_payloads_for_excluded_shipping_method: dict | None = None
- @cached_property
- def all_shipping_methods(self) -> list["ShippingMethodData"]:
- all_methods = get_all_shipping_methods_list(
- self,
- self.shipping_address,
- self.lines,
- self.shipping_channel_listings,
- self.manager,
- self.database_connection_name,
- )
- # Filter shipping methods using sync webhooks
- excluded_methods = self.manager.excluded_shipping_methods_for_checkout(
- self.checkout,
- self.channel,
- all_methods,
- self.pregenerated_payloads_for_excluded_shipping_method,
- )
+ allow_sync_webhooks: bool = True
+ _cached_built_in_shipping_methods: list[ShippingMethodData] | None = None
+ _cached_external_shipping_methods: list[ShippingMethodData] | None = None
+
+ def get_all_shipping_methods(
+ self,
+ ) -> list["ShippingMethodData"]:
+ """Return list of all available shipping methods.
+
+ If self.allow_sync_webhooks is set to False, any external calls will be skipped.
+ If self.allow_sync_webhooks is set to True, the external calls like: external
+ shipping methods or exclude shipping methods will be called.
+
+ The fetched values are stored in self object to remove any additional
+ external/DB calls.
+ """
+ if (
+ self._cached_external_shipping_methods is not None
+ and self._cached_built_in_shipping_methods is not None
+ ):
+ return (
+ self._cached_built_in_shipping_methods
+ + self._cached_external_shipping_methods
+ )
+
+ if (
+ not self.allow_sync_webhooks
+ and self._cached_built_in_shipping_methods is not None
+ ):
+ return self._cached_built_in_shipping_methods
+
+ if self._cached_built_in_shipping_methods is None:
+ self._cached_built_in_shipping_methods = (
+ get_available_built_in_shipping_methods_for_checkout_info(self)
+ )
+
+ if not self.allow_sync_webhooks:
+ excluded_methods = []
+ all_methods = self._cached_built_in_shipping_methods
+ else:
+ self._cached_external_shipping_methods = (
+ get_external_shipping_methods_for_checkout_info(self)
+ )
+ all_methods = (
+ self._cached_built_in_shipping_methods
+ + self._cached_external_shipping_methods
+ )
+ # Filter shipping methods using sync webhooks
+ excluded_methods = self.manager.excluded_shipping_methods_for_checkout(
+ self.checkout,
+ self.channel,
+ all_methods,
+ self.pregenerated_payloads_for_excluded_shipping_method,
+ )
initialize_shipping_method_active_status(all_methods, excluded_methods)
return all_methods
@@ -147,8 +184,34 @@ class CheckoutInfo:
)
)
- @property
- def delivery_method_info(self) -> "DeliveryMethodBase":
+ def _update_denormalized_shipping_method_fields(
+ self, delivery_method: ShippingMethodData | Warehouse
+ ):
+ checkout = self.checkout
+ fields_to_update = []
+ if isinstance(delivery_method, ShippingMethodData):
+ new_shipping_method_name = delivery_method.name
+ new_shipping_price = delivery_method.price
+ else:
+ new_shipping_method_name = None
+ new_shipping_price = zero_money(checkout.currency)
+
+ if checkout.shipping_method_name != new_shipping_method_name:
+ checkout.shipping_method_name = new_shipping_method_name
+ fields_to_update.append("shipping_method_name")
+ current_shipping_price = quantize_price(
+ checkout.undiscounted_base_shipping_price, checkout.currency
+ )
+ new_shipping_price = quantize_price(new_shipping_price, checkout.currency)
+ if current_shipping_price != new_shipping_price:
+ checkout.undiscounted_base_shipping_price_amount = new_shipping_price.amount
+ fields_to_update.append("undiscounted_base_shipping_price_amount")
+
+ if fields_to_update:
+ with allow_writer():
+ checkout.save(update_fields=fields_to_update)
+
+ def get_delivery_method_info(self) -> "DeliveryMethodBase":
from ..webhook.transport.shipping import convert_to_app_id_with_identifier
from .utils import get_external_shipping_id
@@ -168,26 +231,38 @@ class CheckoutInfo:
)
elif external_shipping_method_id := get_external_shipping_id(self.checkout):
- methods = {method.id: method for method in self.all_shipping_methods}
- if method := methods.get(external_shipping_method_id):
- delivery_method = method
+ if self.allow_sync_webhooks:
+ methods = {
+ method.id: method for method in self.get_all_shipping_methods()
+ }
+ if method := methods.get(external_shipping_method_id):
+ delivery_method = method
+ else:
+ new_shipping_method_id = convert_to_app_id_with_identifier(
+ external_shipping_method_id
+ )
+ if new_shipping_method_id is None:
+ delivery_method = None
+ else:
+ delivery_method = methods.get(new_shipping_method_id)
else:
- new_shipping_method_id = convert_to_app_id_with_identifier(
- external_shipping_method_id
+ delivery_method = ShippingMethodData(
+ id=get_external_shipping_id(self.checkout),
+ name=self.checkout.shipping_method_name or "",
+ price=self.checkout.undiscounted_base_shipping_price,
)
- if new_shipping_method_id is None:
- delivery_method = None
- else:
- delivery_method = methods.get(new_shipping_method_id)
else:
delivery_method = self.collection_point
+ if isinstance(delivery_method, ShippingMethodData):
+ self._update_denormalized_shipping_method_fields(delivery_method)
+
return get_delivery_method_info(delivery_method, self.shipping_address)
@property
def valid_shipping_methods(self) -> list["ShippingMethodData"]:
- return [method for method in self.all_shipping_methods if method.active]
+ return [method for method in self.get_all_shipping_methods() if method.active]
@property
def valid_delivery_methods(
@@ -544,17 +619,13 @@ def fetch_checkout_info(
return checkout_info
-def get_valid_internal_shipping_method_list_for_checkout_info(
+def get_available_built_in_shipping_methods_for_checkout_info(
checkout_info: "CheckoutInfo",
- shipping_address: Optional["Address"],
- lines: list[CheckoutLineInfo],
- shipping_channel_listings: Iterable[ShippingMethodChannelListing],
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> list["ShippingMethodData"]:
from . import base_calculations
- from .utils import get_valid_internal_shipping_methods_for_checkout
+ from .utils import get_valid_internal_shipping_methods_for_checkout_info
- country_code = shipping_address.country.code if shipping_address else None
+ lines = checkout_info.lines
subtotal = base_calculations.base_checkout_subtotal(
lines,
@@ -577,38 +648,32 @@ def get_valid_internal_shipping_method_list_for_checkout_info(
if not is_shipping_voucher and not is_voucher_for_specific_product:
subtotal -= checkout_info.checkout.discount
- valid_shipping_methods = get_valid_internal_shipping_methods_for_checkout(
+ valid_shipping_methods = get_valid_internal_shipping_methods_for_checkout_info(
checkout_info,
- lines,
subtotal,
- shipping_channel_listings,
- country_code=country_code,
- database_connection_name=database_connection_name,
)
return valid_shipping_methods
+def get_external_shipping_methods_for_checkout_info(
+ checkout_info,
+) -> list[ShippingMethodData]:
+ manager = checkout_info.manager
+ return manager.list_shipping_methods_for_checkout(
+ checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug
+ )
+
+
def get_all_shipping_methods_list(
checkout_info,
- shipping_address,
- lines,
- shipping_channel_listings,
- manager,
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
return list(
itertools.chain(
- get_valid_internal_shipping_method_list_for_checkout_info(
+ get_available_built_in_shipping_methods_for_checkout_info(
checkout_info,
- shipping_address,
- lines,
- shipping_channel_listings,
- database_connection_name=database_connection_name,
- ),
- manager.list_shipping_methods_for_checkout(
- checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug
),
+ get_external_shipping_methods_for_checkout_info(checkout_info),
)
)
@@ -632,7 +697,8 @@ def update_delivery_method_lists_for_checkout_info(
# Clear cached properties if they were already calculated, so they can be
# recalculated.
try:
- del checkout_info.all_shipping_methods
+ del checkout_info._cached_built_in_shipping_methods
+ del checkout_info._cached_external_shipping_methods
except AttributeError:
pass
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 0297b6e195..071e0ae55f 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -31,6 +31,7 @@ from ...plugins.manager import get_plugins_manager
from ...product.models import VariantChannelListingPromotionRule
from ...shipping.interface import ShippingMethodData
from ...shipping.models import ShippingZone
+from ...webhook.event_types import WebhookEventSyncType
from .. import base_calculations, calculations
from ..fetch import (
CheckoutInfo,
@@ -65,14 +66,14 @@ def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
# no shipping method assigned
assert not delivery_method_info.is_valid_delivery_method()
shipping_method = shipping_zone.shipping_methods.first()
checkout.shipping_method = shipping_method
checkout.save()
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert delivery_method_info.is_valid_delivery_method()
@@ -80,7 +81,7 @@ def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):
shipping_method.shipping_zone = zone
shipping_method.save()
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
@@ -117,7 +118,7 @@ def test_is_valid_delivery_method_external_method(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
@@ -162,7 +163,7 @@ def test_is_valid_delivery_method_external_method_with_metadata_and_description(
# when
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
# then
assert delivery_method_info.delivery_method.metadata == metadata
@@ -170,6 +171,134 @@ def test_is_valid_delivery_method_external_method_with_metadata_and_description(
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_delivery_method_external_method_with_not_allowed_webhooks(
+ mocked_request, checkout_with_item, shipping_app, settings
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ shipping_method_id = "abcd"
+ shipping_method_name = "Default shipping"
+ graphql_shipping_method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{shipping_method_id}"
+ )
+
+ checkout = checkout_with_item
+ shipping_price = Money(Decimal(10), currency=checkout.currency)
+
+ checkout.external_shipping_method_id = graphql_shipping_method_id
+ checkout.undiscounted_base_shipping_price = shipping_price
+ checkout.shipping_method_name = shipping_method_name
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_info.allow_sync_webhooks = False
+
+ # when
+ delivery_method_info = checkout_info.get_delivery_method_info()
+
+ # then
+ delivery_method = delivery_method_info.delivery_method
+ assert isinstance(delivery_method, ShippingMethodData)
+ assert delivery_method.name == shipping_method_name
+ assert delivery_method.price == shipping_price
+ assert delivery_method.id == graphql_shipping_method_id
+ mocked_request.assert_not_called()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_delivery_method_exclude_shipping_methods_with_not_allowed_webhooks(
+ mocked_request, checkout_with_item, shipping_app, settings
+):
+ # given
+ webhook = shipping_app.webhooks.get()
+ webhook.events.create(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ )
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ shipping_method_id = "abcd"
+ shipping_method_name = "Default shipping"
+ graphql_shipping_method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{shipping_method_id}"
+ )
+
+ checkout = checkout_with_item
+ shipping_price = Money(Decimal(10), currency=checkout.currency)
+
+ checkout.external_shipping_method_id = graphql_shipping_method_id
+ checkout.undiscounted_base_shipping_price = shipping_price
+ checkout.shipping_method_name = shipping_method_name
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_info.allow_sync_webhooks = False
+
+ # when
+ delivery_method_info = checkout_info.get_delivery_method_info()
+
+ # then
+ delivery_method = delivery_method_info.delivery_method
+ assert isinstance(delivery_method, ShippingMethodData)
+ assert delivery_method.name == shipping_method_name
+ assert delivery_method.price == shipping_price
+ assert delivery_method.id == graphql_shipping_method_id
+ mocked_request.assert_not_called()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_all_shipping_methods_with_external_methods_and_not_allowed_webhooks(
+ mocked_request, checkout_with_shipping_method, shipping_app, settings
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ checkout = checkout_with_shipping_method
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_info.allow_sync_webhooks = False
+
+ # when
+ shipping_methods = checkout_info.get_all_shipping_methods()
+
+ # then
+ assert all(not shipping_method.is_external for shipping_method in shipping_methods)
+ mocked_request.assert_not_called()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_all_shipping_methods_with_exclude_shipping_methods_with_not_allowed_webhooks(
+ mocked_request, checkout_with_shipping_method, shipping_app, settings
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ webhook = shipping_app.webhooks.get()
+ webhook.events.create(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ )
+
+ checkout = checkout_with_shipping_method
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_info.allow_sync_webhooks = False
+
+ # when
+ shipping_methods = checkout_info.get_all_shipping_methods()
+
+ # then
+ assert all(shipping_method.active for shipping_method in shipping_methods)
+ mocked_request.assert_not_called()
+
+
@pytest.mark.parametrize(
"invalid_metadata",
[
@@ -224,7 +353,7 @@ def test_is_valid_delivery_method_external_method_with_invalid_metadata(
# when
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
# then
assert delivery_method_info.delivery_method.metadata == {}
@@ -267,7 +396,7 @@ def test_is_valid_delivery_method_external_method_shipping_app_id_with_identifie
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
@@ -307,7 +436,7 @@ def test_is_valid_delivery_method_external_method_old_shipping_app_id(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
@@ -340,7 +469,7 @@ def test_is_valid_delivery_method_external_method_no_longer_available(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert delivery_method_info.is_method_in_valid_methods(checkout_info) is False
@@ -353,7 +482,7 @@ def test_clear_delivery_method(checkout, shipping_method):
clear_delivery_method(checkout_info)
checkout.refresh_from_db()
assert not checkout.shipping_method
- assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
+ assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
@patch.object(CheckoutMetadata, "save")
@@ -373,7 +502,7 @@ def test_clear_delivery_method_do_not_update_metadata_when_no_external_shipping(
checkout.refresh_from_db()
assert not mocked_metadata_save.called
assert not checkout.shipping_method
- assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
+ assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
@patch.object(CheckoutMetadata, "save")
@@ -396,7 +525,7 @@ def test_clear_delivery_method_update_metadata_when_external_shipping(
checkout.metadata_storage.refresh_from_db()
assert mocked_metadata_save.called
assert not checkout.shipping_method
- assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
+ assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
assert (
PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
)
@@ -1960,7 +2089,7 @@ def test_change_address_in_checkout_invalidates_shipping_methods(
shipping_channel_listings=shipping_method.channel_listings.all(),
)
- all_shipping_methods = checkout_info.all_shipping_methods
+ all_shipping_methods = checkout_info.get_all_shipping_methods()
assert all_shipping_methods == []
# when
@@ -1979,7 +2108,7 @@ def test_change_address_in_checkout_invalidates_shipping_methods(
assert checkout.shipping_address == address
assert checkout.billing_address == address
assert checkout_info.shipping_address == address
- assert checkout_info.all_shipping_methods
+ assert checkout_info.get_all_shipping_methods()
def test_add_voucher_to_checkout(checkout_with_item, voucher):
@@ -2225,7 +2354,7 @@ def test_checkout_without_delivery_method_creates_empty_delivery_method(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.delivery_method_info
+ delivery_method_info = checkout_info.get_delivery_method_info()
assert isinstance(delivery_method_info, DeliveryMethodBase)
assert not delivery_method_info.is_valid_delivery_method()
diff --git a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
index 02c61b0d78..3a01167b89 100644
--- a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
+++ b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
@@ -232,7 +232,11 @@ def test_assign_built_in_shipping_to_checkout_without_delivery_method(
checkout, shipping_method
):
# given
- expected_updated_fields = {"shipping_method_id", "shipping_method_name"}
+ expected_updated_fields = {
+ "shipping_method_id",
+ "shipping_method_name",
+ "undiscounted_base_shipping_price_amount",
+ }
shipping_method_data = ShippingMethodData(
id=str(shipping_method.id),
name=shipping_method.name,
@@ -259,6 +263,7 @@ def test_assign_built_in_shipping_to_checkout_with_cc(
"shipping_method_name",
"collection_point_id",
"shipping_address_id",
+ "undiscounted_base_shipping_price_amount",
}
shipping_method_data = ShippingMethodData(
id=str(shipping_method.id),
@@ -287,6 +292,7 @@ def test_assign_built_in_shipping_to_checkout_with_external_shipping_method(
"shipping_method_id",
"shipping_method_name",
"external_shipping_method_id",
+ "undiscounted_base_shipping_price_amount",
}
shipping_method_data = ShippingMethodData(
id=str(shipping_method.id),
@@ -320,6 +326,7 @@ def test_assign_built_in_shipping_to_checkout_with_different_shipping_method(
expected_updated_fields = {
"shipping_method_id",
"shipping_method_name",
+ "undiscounted_base_shipping_price_amount",
}
# when
@@ -337,13 +344,15 @@ def test_assign_built_in_shipping_to_checkout_with_the_same_shipping_method(
checkout, shipping_method
):
# given
+ shipping_price_amount = Decimal(10)
checkout.shipping_method = shipping_method
checkout.shipping_method_name = shipping_method.name
+ checkout.undiscounted_base_shipping_price_amount = shipping_price_amount
shipping_method_data = ShippingMethodData(
id=str(shipping_method.id),
name=shipping_method.name,
- price=Money(10, checkout.currency),
+ price=Money(shipping_price_amount, checkout.currency),
)
# when
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 27a95bcb5c..6a3bbe5abe 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -17,6 +17,7 @@ from ..account.models import User
from ..checkout.fetch import update_delivery_method_lists_for_checkout_info
from ..core.db.connection import allow_writer
from ..core.exceptions import NonExistingCheckoutLines, ProductNotPublished
+from ..core.prices import quantize_price
from ..core.taxes import zero_taxed_money
from ..core.utils.promo_code import (
InvalidPromoCode,
@@ -529,7 +530,7 @@ def _get_shipping_voucher_discount_for_checkout(
if not is_shipping_required(lines):
msg = "Your order does not require shipping."
raise NotApplicable(msg)
- shipping_method = checkout_info.delivery_method_info.delivery_method
+ shipping_method = checkout_info.get_delivery_method_info().delivery_method
if not shipping_method:
msg = "Please select a delivery method first."
raise NotApplicable(msg)
@@ -936,32 +937,35 @@ def remove_voucher_from_checkout(checkout: Checkout):
)
-def get_valid_internal_shipping_methods_for_checkout(
+def get_valid_internal_shipping_methods_for_checkout_info(
checkout_info: "CheckoutInfo",
- lines: list["CheckoutLineInfo"],
subtotal: "Money",
- shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
- country_code: str | None = None,
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> list[ShippingMethodData]:
- if not is_shipping_required(lines):
+ if not is_shipping_required(checkout_info.lines):
return []
if not checkout_info.shipping_address:
return []
+ country_code = (
+ checkout_info.shipping_address.country.code
+ if checkout_info.shipping_address
+ else None
+ )
+
shipping_methods = ShippingMethod.objects.using(
- database_connection_name
+ checkout_info.database_connection_name
).applicable_shipping_methods_for_instance(
checkout_info.checkout,
channel_id=checkout_info.checkout.channel_id,
price=subtotal,
shipping_address=checkout_info.shipping_address,
country_code=country_code,
- lines=lines,
+ lines=checkout_info.lines,
)
channel_listings_map = {
- listing.shipping_method_id: listing for listing in shipping_channel_listings
+ listing.shipping_method_id: listing
+ for listing in checkout_info.shipping_channel_listings
}
internal_methods: list[ShippingMethodData] = []
@@ -1107,6 +1111,13 @@ def _remove_external_shipping_from_metadata(checkout: Checkout):
metadata.save(update_fields=["private_metadata"])
+def _remove_undiscounted_base_shipping_price(checkout: Checkout):
+ if checkout.undiscounted_base_shipping_price_amount:
+ checkout.undiscounted_base_shipping_price_amount = Decimal(0)
+ return ["undiscounted_base_shipping_price_amount"]
+ return []
+
+
def remove_external_shipping_from_checkout(
checkout: Checkout, save: bool = False
) -> list[str]:
@@ -1150,18 +1161,35 @@ def remove_click_and_collect_from_checkout(checkout: Checkout) -> list[str]:
def remove_delivery_method_from_checkout(checkout: Checkout) -> list[str]:
fields_to_update = []
+ fields_to_update += _remove_undiscounted_base_shipping_price(checkout)
fields_to_update += remove_built_in_shipping_from_checkout(checkout)
fields_to_update += remove_click_and_collect_from_checkout(checkout)
fields_to_update += remove_external_shipping_from_checkout(checkout)
return fields_to_update
+def _assign_undiscounted_base_shipping_price_to_checkout(
+ checkout, shipping_method_data: ShippingMethodData
+):
+ current_shipping_price = quantize_price(
+ checkout.undiscounted_base_shipping_price, checkout.currency
+ )
+ new_shipping_price = quantize_price(shipping_method_data.price, checkout.currency)
+ if current_shipping_price != new_shipping_price:
+ checkout.undiscounted_base_shipping_price_amount = new_shipping_price.amount
+ return ["undiscounted_base_shipping_price_amount"]
+ return []
+
+
def assign_external_shipping_to_checkout(
checkout: Checkout, external_shipping_method_data: ShippingMethodData
) -> list[str]:
fields_to_update = []
fields_to_update += remove_built_in_shipping_from_checkout(checkout)
fields_to_update += remove_click_and_collect_from_checkout(checkout)
+ fields_to_update += _assign_undiscounted_base_shipping_price_to_checkout(
+ checkout, external_shipping_method_data
+ )
# make sure that we don't have obsolete data for shipping methods stored in
# private metadata
@@ -1183,6 +1211,9 @@ def assign_built_in_shipping_to_checkout(
fields_to_update = []
fields_to_update += remove_external_shipping_from_checkout(checkout)
fields_to_update += remove_click_and_collect_from_checkout(checkout)
+ fields_to_update += _assign_undiscounted_base_shipping_price_to_checkout(
+ checkout, shipping_method_data
+ )
if checkout.shipping_method_id != int(shipping_method_data.id):
checkout.shipping_method_id = shipping_method_data.id
@@ -1197,6 +1228,7 @@ def assign_collection_point_to_checkout(
checkout, collection_point: Warehouse
) -> list[str]:
fields_to_update = []
+ fields_to_update += _remove_undiscounted_base_shipping_price(checkout)
fields_to_update += remove_external_shipping_from_checkout(checkout)
fields_to_update += remove_built_in_shipping_from_checkout(checkout)
if checkout.collection_point_id != collection_point.id:
@@ -1282,7 +1314,7 @@ def log_address_if_validation_skipped_for_checkout(
def get_address_for_checkout_taxes(
checkout_info: "CheckoutInfo",
) -> Optional["Address"]:
- shipping_address = checkout_info.delivery_method_info.shipping_address
+ shipping_address = checkout_info.get_delivery_method_info().shipping_address
return shipping_address or checkout_info.billing_address
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index 0ab86ee18d..f50cd3f44d 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -162,7 +162,7 @@ class CheckoutLinesAdd(BaseMutation):
checkout_lines_data,
checkout.get_country(),
channel_slug,
- checkout_info.delivery_method_info,
+ checkout_info.get_delivery_method_info(),
lines=lines,
)
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
index 33ca98e32a..4ba8130d3e 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
@@ -181,7 +181,7 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixi
lines,
country,
checkout_info.channel.slug,
- checkout_info.delivery_method_info,
+ checkout_info.get_delivery_method_info(),
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index cd70dd5aa7..e204b48d34 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -121,7 +121,7 @@ def update_checkout_shipping_method_if_invalid(
is_valid = clean_delivery_method(
checkout_info=checkout_info,
- method=checkout_info.delivery_method_info.delivery_method,
+ method=checkout_info.get_delivery_method_info().delivery_method,
)
if not is_valid:
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 1ec6ebcc7f..9fed517000 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -3861,7 +3861,7 @@ def test_checkout_complete_raises_InvalidShippingMethod_when_warehouse_disabled(
)
assert not checkout_info.valid_pick_up_points
- assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ assert not checkout_info.get_delivery_method_info().is_method_in_valid_methods(
checkout_info
)
@@ -4022,7 +4022,7 @@ def test_checkout_complete_with_click_collect_preorder_fails_for_disabled_wareho
)
assert not checkout_info.valid_pick_up_points
- assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ assert not checkout_info.get_delivery_method_info().is_method_in_valid_methods(
checkout_info
)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 840a820f6c..375d6f0ba5 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -3839,7 +3839,7 @@ def test_checkout_complete_raises_InvalidShippingMethod_when_warehouse_disabled(
checkout_info = fetch_checkout_info(checkout, lines, manager)
assert not checkout_info.valid_pick_up_points
- assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ assert not checkout_info.get_delivery_method_info().is_method_in_valid_methods(
checkout_info
)
# when
@@ -3979,7 +3979,7 @@ def test_checkout_complete_with_click_collect_preorder_fails_for_disabled_wareho
checkout_info = fetch_checkout_info(checkout, lines, manager)
assert not checkout_info.valid_pick_up_points
- assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ assert not checkout_info.get_delivery_method_info().is_method_in_valid_methods(
checkout_info
)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index 20c10e4943..6e9dcc0cd6 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -2013,6 +2013,7 @@ def test_checkout_delivery_method_update_from_external_shipping_to_the_same_exte
checkout.shipping_address = address
checkout.external_shipping_method_id = method_id
checkout.shipping_method_name = response_shipping_name
+ checkout.undiscounted_base_shipping_price_amount = Decimal(response_shipping_price)
checkout.save()
# when
@@ -2215,8 +2216,10 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_the_same_ship
):
# given
checkout = checkout_with_shipping_method
-
shipping_method = checkout.shipping_method
+ price = shipping_method.channel_listings.get().price
+ checkout.undiscounted_base_shipping_price_amount = price.amount
+ checkout.save()
# when
response = api_client.post_graphql(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 19f56af23f..f70f5cfe1f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -1045,6 +1045,7 @@ def test_checkout_shipping_method_update_from_external_shipping_to_the_same_exte
checkout.shipping_address = address
checkout.external_shipping_method_id = method_id
checkout.shipping_method_name = response_shipping_name
+ checkout.undiscounted_base_shipping_price_amount = Decimal(response_shipping_price)
checkout.save()
# when
@@ -1286,6 +1287,9 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_the_same_buil
checkout = checkout_with_shipping_method
shipping_method = checkout.shipping_method
+ price = shipping_method.channel_listings.get().price
+ checkout.undiscounted_base_shipping_price_amount = price.amount
+ checkout.save()
# when
response = api_client.post_graphql(
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index af72129aa5..22cbe1aade 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -2040,7 +2040,7 @@ def test_order_from_checkout_raises_invalid_shipping_method_when_warehouse_disab
checkout_info = fetch_checkout_info(checkout, lines, manager)
assert not checkout_info.valid_pick_up_points
- assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ assert not checkout_info.get_delivery_method_info().is_method_in_valid_methods(
checkout_info
)
@@ -2170,7 +2170,7 @@ def test_order_from_draft_create_click_collect_preorder_fails_for_disabled_wareh
checkout_info = fetch_checkout_info(checkout, lines, manager)
assert not checkout_info.valid_pick_up_points
- assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ assert not checkout_info.get_delivery_method_info().is_method_in_valid_methods(
checkout_info
)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index fb6a05fc1f..91793d80d2 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -130,7 +130,7 @@ def test_update_checkout_shipping_method_if_invalid(
update_checkout_shipping_method_if_invalid(checkout_info, lines)
assert checkout.shipping_method is None
- assert checkout_info.delivery_method_info.delivery_method is None
+ assert checkout_info.get_delivery_method_info().delivery_method is None
# Ensure the checkout's shipping method was saved
checkout.refresh_from_db(fields=["shipping_method"])
@@ -164,7 +164,7 @@ def test_update_checkout_shipping_method_if_invalid_no_checkout_metadata(
# then
assert checkout.shipping_method is None
- assert checkout_info.delivery_method_info.delivery_method is None
+ assert checkout_info.get_delivery_method_info().delivery_method is None
# Ensure the checkout's shipping method was saved
checkout.refresh_from_db(fields=["shipping_method"])
diff --git a/saleor/graphql/checkout/tests/test_checkouts_query.py b/saleor/graphql/checkout/tests/test_checkouts_query.py
new file mode 100644
index 0000000000..ddf519c23d
--- /dev/null
+++ b/saleor/graphql/checkout/tests/test_checkouts_query.py
@@ -0,0 +1,289 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from ....shipping.models import ShippingMethod
+from ....webhook.event_types import WebhookEventSyncType
+from ...core.utils import to_global_id_or_none
+from ...tests.utils import get_graphql_content
+
+CHECKOUTS_QUERY = """
+query CheckoutsQuery {
+ checkouts(first: 1) {
+ edges {
+ node {
+ deliveryMethod {
+ __typename
+ ... on ShippingMethod {
+ id
+ name
+ price {
+ amount
+ }
+ }
+ }
+ shippingPrice {
+ gross {
+ amount
+ }
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
+ lines {
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ unitPrice {
+ gross {
+ amount
+ }
+ }
+ }
+ shippingMethods {
+ id
+ name
+ active
+ }
+ availableShippingMethods {
+ id
+ name
+ active
+ }
+ }
+ }
+ }
+}
+"""
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_query_checkouts_do_not_trigger_external_shipping_webhook_with_flat_rates(
+ mocked_request,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkout_with_delivery_method_for_external_shipping,
+ settings,
+ tax_configuration_flat_rates,
+ shipping_app,
+):
+ # given
+ webhook = shipping_app.webhooks.get()
+ assert (
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
+ in webhook.events.all().values_list("event_type", flat=True)
+ )
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ checkout = checkout_with_delivery_method_for_external_shipping
+ checkout.price_expiration = timezone.now()
+ checkout.undiscounted_base_shipping_price_amount = Decimal("100")
+ checkout.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHECKOUTS_QUERY,
+ permissions=[permission_manage_checkouts],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkouts"]["edges"]
+ assert len(data) == 1
+ checkout_data = data[0]["node"]
+
+ shipping_method = ShippingMethod.objects.get()
+ assert len(checkout_data["shippingMethods"]) == 1
+ assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ assert len(checkout_data["availableShippingMethods"]) == 1
+ assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ delivery_method = checkout_data["deliveryMethod"]
+ assert delivery_method
+ assert delivery_method["id"] == checkout.external_shipping_method_id
+ assert delivery_method["name"] == checkout.shipping_method_name
+ assert (
+ delivery_method["price"]["amount"]
+ == checkout.undiscounted_base_shipping_price_amount
+ )
+ mocked_request.assert_not_called()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_query_checkouts_do_not_trigger_external_shipping_webhook_with_tax_app(
+ mocked_request,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkout_with_delivery_method_for_external_shipping,
+ settings,
+ tax_configuration_tax_app,
+ shipping_app,
+):
+ # given
+ webhook = shipping_app.webhooks.get()
+ assert (
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
+ in webhook.events.all().values_list("event_type", flat=True)
+ )
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ checkout = checkout_with_delivery_method_for_external_shipping
+ checkout.price_expiration = timezone.now()
+ checkout.undiscounted_base_shipping_price_amount = Decimal("100")
+ checkout.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHECKOUTS_QUERY,
+ permissions=[permission_manage_checkouts],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkouts"]["edges"]
+ assert len(data) == 1
+ checkout_data = data[0]["node"]
+
+ shipping_method = ShippingMethod.objects.get()
+ assert len(checkout_data["shippingMethods"]) == 1
+ assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ assert len(checkout_data["availableShippingMethods"]) == 1
+ assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ delivery_method = checkout_data["deliveryMethod"]
+ assert delivery_method
+ assert delivery_method["id"] == checkout.external_shipping_method_id
+ assert delivery_method["name"] == checkout.shipping_method_name
+ assert (
+ delivery_method["price"]["amount"]
+ == checkout.undiscounted_base_shipping_price_amount
+ )
+ mocked_request.assert_not_called()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_query_checkouts_do_not_trigger_exclude_shipping_webhooks_with_flat_rates(
+ mocked_request,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkout_with_delivery_method_for_external_shipping,
+ settings,
+ tax_configuration_flat_rates,
+ shipping_app,
+):
+ # given
+ webhook = shipping_app.webhooks.get()
+ webhook.events.create(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ )
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ checkout = checkout_with_delivery_method_for_external_shipping
+ checkout.price_expiration = timezone.now()
+ checkout.undiscounted_base_shipping_price_amount = Decimal("100")
+ checkout.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHECKOUTS_QUERY,
+ permissions=[permission_manage_checkouts],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkouts"]["edges"]
+ assert len(data) == 1
+ checkout_data = data[0]["node"]
+
+ shipping_method = ShippingMethod.objects.get()
+ assert len(checkout_data["shippingMethods"]) == 1
+ assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ assert len(checkout_data["availableShippingMethods"]) == 1
+ assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ delivery_method = checkout_data["deliveryMethod"]
+ assert delivery_method
+ assert delivery_method["id"] == checkout.external_shipping_method_id
+ assert delivery_method["name"] == checkout.shipping_method_name
+ assert (
+ delivery_method["price"]["amount"]
+ == checkout.undiscounted_base_shipping_price_amount
+ )
+ mocked_request.assert_not_called()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_query_checkouts_do_not_trigger_exclude_shipping_webhooks_with_tax_app(
+ mocked_request,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkout_with_delivery_method_for_external_shipping,
+ settings,
+ tax_configuration_tax_app,
+ shipping_app,
+):
+ # given
+ webhook = shipping_app.webhooks.get()
+ webhook.events.create(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ )
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ checkout = checkout_with_delivery_method_for_external_shipping
+ checkout.price_expiration = timezone.now()
+ checkout.undiscounted_base_shipping_price_amount = Decimal("100")
+ checkout.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHECKOUTS_QUERY,
+ permissions=[permission_manage_checkouts],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkouts"]["edges"]
+ assert len(data) == 1
+ checkout_data = data[0]["node"]
+
+ shipping_method = ShippingMethod.objects.get()
+ assert len(checkout_data["shippingMethods"]) == 1
+ assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ assert len(checkout_data["availableShippingMethods"]) == 1
+ assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+ delivery_method = checkout_data["deliveryMethod"]
+ assert delivery_method
+ assert delivery_method["id"] == checkout.external_shipping_method_id
+ assert delivery_method["name"] == checkout.shipping_method_name
+ assert (
+ delivery_method["price"]["amount"]
+ == checkout.undiscounted_base_shipping_price_amount
+ )
+ mocked_request.assert_not_called()
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 5acdb0a7bd..fff3bab212 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -347,6 +347,7 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]
@allow_writer_in_context(info.context)
def calculate_line_unit_price(data):
checkout_info, lines, payloads = data
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
database_connection_name = get_database_connection_name(info.context)
for line_info in lines:
if line_info.line.pk == root.node.pk:
@@ -384,6 +385,7 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]
checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
+
lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
@@ -426,6 +428,7 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]
checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
+
lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
@@ -438,6 +441,7 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]
@allow_writer_in_context(info.context)
def calculate_line_total_price(data):
checkout_info, lines, payloads = data
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
database_connection_name = get_database_connection_name(info.context)
for line_info in lines:
if line_info.line.pk == root.node.pk:
@@ -954,7 +958,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
@staticmethod
def resolve_shipping_method(root: SyncWebhookControlContext[models.Checkout], info):
def with_checkout_info(checkout_info):
- delivery_method = checkout_info.delivery_method_info.delivery_method
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ delivery_method = checkout_info.get_delivery_method_info().delivery_method
if not delivery_method or not isinstance(
delivery_method, ShippingMethodData
):
@@ -975,7 +980,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
):
@allow_writer_in_context(info.context)
def with_checkout_info(checkout_info):
- return checkout_info.all_shipping_methods
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ return checkout_info.get_all_shipping_methods()
return (
CheckoutInfoByCheckoutTokenLoader(info.context)
@@ -989,7 +995,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
):
@allow_writer_in_context(info.context)
def with_checkout_info(checkout_info):
- return checkout_info.delivery_method_info.delivery_method
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ return checkout_info.get_delivery_method_info().delivery_method
return (
CheckoutInfoByCheckoutTokenLoader(info.context)
@@ -1020,6 +1027,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def calculate_total_price(data):
address, lines, checkout_info, manager, payloads = data
database_connection_name = get_database_connection_name(info.context)
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+
taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
@@ -1044,6 +1053,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def calculate_subtotal_price(data):
address, lines, checkout_info, manager, payloads = data
database_connection_name = get_database_connection_name(info.context)
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+
return calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
@@ -1067,6 +1078,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def calculate_shipping_price(data):
address, lines, checkout_info, manager, payloads = data
database_connection_name = get_database_connection_name(info.context)
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+
return calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
@@ -1106,6 +1119,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
):
@allow_writer_in_context(info.context)
def with_checkout_info(checkout_info):
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+
return checkout_info.valid_shipping_methods
return (
@@ -1149,7 +1164,7 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
@allow_writer_in_context(info.context)
def get_available_payment_gateways(results):
- (checkout_info, lines_info) = results
+ checkout_info, lines_info = results
return manager.list_payment_gateways(
currency=root.node.currency,
checkout_info=checkout_info,
@@ -1392,6 +1407,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def _resolve_charge_status(data):
address, lines, checkout_info, manager, payloads, transactions = data
database_connection_name = get_database_connection_name(info.context)
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+
fetch_checkout_data(
checkout_info=checkout_info,
manager=manager,
@@ -1417,6 +1434,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def _calculate_total_balance_for_transactions(data):
address, lines, checkout_info, manager, payloads, transactions = data
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+
taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.py
index 6af3a8bd05..70a367e8ab 100644
--- a/saleor/graphql/webhook/resolvers.py
+++ b/saleor/graphql/webhook/resolvers.py
@@ -80,10 +80,5 @@ def resolve_shipping_methods_for_checkout(
)
all_shipping_methods = get_all_shipping_methods_list(
checkout_info,
- checkout.shipping_address,
- lines,
- shipping_channel_listings,
- manager,
- database_connection_name=database_connection_name,
)
return all_shipping_methods
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index d7518d1614..7e64c6988c 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -245,9 +245,9 @@ def get_shipping_data(manager, checkout_info, lines):
"amountExcludingTax": price_to_minor_unit(total_net, currency),
"taxPercentage": tax_percentage_in_adyen_format,
"description": (
- f"Shipping - {checkout_info.delivery_method_info.delivery_method.name}"
+ f"Shipping - {checkout_info.get_delivery_method_info().delivery_method.name}"
),
- "id": f"Shipping:{checkout_info.delivery_method_info.delivery_method.id}",
+ "id": f"Shipping:{checkout_info.get_delivery_method_info().delivery_method.id}",
"taxAmount": price_to_minor_unit(tax_amount, currency),
"amountIncludingTax": price_to_minor_unit(total_gross, currency),
}
@@ -302,8 +302,9 @@ def append_checkout_details(payment_information: "PaymentData", payment_data: di
}
line_items.append(line_data)
- if checkout_info.delivery_method_info.delivery_method and is_shipping_required(
- lines
+ if (
+ checkout_info.get_delivery_method_info().delivery_method
+ and is_shipping_required(lines)
):
line_items.append(get_shipping_data(manager, checkout_info, lines))
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 042cba2f63..55acf718f0 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -205,13 +205,13 @@ def _validate_checkout(
return False
shipping_required = is_shipping_required(lines)
- shipping_address = checkout_info.delivery_method_info.shipping_address
+ shipping_address = checkout_info.get_delivery_method_info().shipping_address
address = shipping_address or checkout_info.billing_address
return _validate_address_details(
shipping_address,
shipping_required,
address,
- checkout_info.delivery_method_info.delivery_method,
+ checkout_info.get_delivery_method_info().delivery_method,
)
@@ -350,7 +350,7 @@ def generate_request_data_from_checkout_lines(
ref1=line_info.variant.sku,
)
- delivery_method = checkout_info.delivery_method_info.delivery_method
+ delivery_method = checkout_info.get_delivery_method_info().delivery_method
if delivery_method:
price = getattr(delivery_method, "price", None)
is_shipping_discount = (
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 00216a3f69..a18ba21784 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -123,7 +123,7 @@ class PluginSample(BasePlugin):
previous_value: TaxedMoney,
):
# See if delivery method doesn't trigger infinite recursion
- bool(checkout_info.delivery_method_info.delivery_method)
+ bool(checkout_info.get_delivery_method_info().delivery_method)
price = Money("1.0", currency=checkout_info.checkout.currency)
return TaxedMoney(price, price)
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index 41b2fb520d..6b123a3ca5 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -6,6 +6,7 @@ import graphene
import pytest
from ....core.models import EventDelivery
+from ....graphql.core.utils import to_global_id_or_none
from ....graphql.tests.utils import get_graphql_content
from ....graphql.webhook.utils import get_subscription_query_hash
from ....order import OrderStatus
@@ -50,23 +51,19 @@ ORDER_QUERY_SHIPPING_METHOD = """
"""
CHECKOUT_QUERY_SHIPPING_METHOD = """
- query CheckoutsQuery {
- checkouts(first: 1) {
- edges {
- node {
- shippingMethods {
- id
- name
- active
- }
- availableShippingMethods {
- id
- name
- active
- }
- }
- }
+ query Checkout($id: ID){
+ checkout(id: $id) {
+ shippingMethods {
+ id
+ name
+ active
+ }
+ availableShippingMethods {
+ id
+ name
+ active
}
+ }
}
"""
@@ -611,9 +608,12 @@ def test_checkout_shipping_methods(
]
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
# when
- response = staff_api_client.post_graphql(CHECKOUT_QUERY_SHIPPING_METHOD)
+ response = staff_api_client.post_graphql(
+ CHECKOUT_QUERY_SHIPPING_METHOD,
+ variables={"id": to_global_id_or_none(checkout_ready_to_complete)},
+ )
content = get_graphql_content(response)
- checkout_data = content["data"]["checkouts"]["edges"][0]["node"]
+ checkout_data = content["data"]["checkout"]
shipping_methods = checkout_data["shippingMethods"]
# then
@@ -651,11 +651,12 @@ def test_checkout_available_shipping_methods(
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
# when
- response = staff_api_client.post_graphql(CHECKOUT_QUERY_SHIPPING_METHOD)
+ response = staff_api_client.post_graphql(
+ CHECKOUT_QUERY_SHIPPING_METHOD,
+ variables={"id": to_global_id_or_none(checkout_ready_to_complete)},
+ )
content = get_graphql_content(response)
- shipping_methods = content["data"]["checkouts"]["edges"][0]["node"][
- "availableShippingMethods"
- ]
+ shipping_methods = content["data"]["checkout"]["availableShippingMethods"]
# then
assert len(shipping_methods) == 1
assert shipping_methods[0]["active"]
@@ -674,9 +675,12 @@ def test_checkout_shipping_methods_webhook_called_once(
mocked_webhook.side_effect = [[], AssertionError("called twice.")]
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
# when
- response = staff_api_client.post_graphql(CHECKOUT_QUERY_SHIPPING_METHOD)
+ response = staff_api_client.post_graphql(
+ CHECKOUT_QUERY_SHIPPING_METHOD,
+ variables={"id": to_global_id_or_none(checkout_ready_to_complete)},
+ )
content = get_graphql_content(response)
- checkout_data = content["data"]["checkouts"]["edges"][0]["node"]
+ checkout_data = content["data"]["checkout"]
# then
assert len(checkout_data["availableShippingMethods"]) == 2
assert len(checkout_data["shippingMethods"]) == 2
diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.py
index 4da3e0defb..1ddab3e8bf 100644
--- a/saleor/tax/calculations/checkout.py
+++ b/saleor/tax/calculations/checkout.py
@@ -58,7 +58,7 @@ def update_checkout_prices_with_flat_rates(
line.tax_rate = normalize_tax_rate_for_db(tax_rate)
# Calculate shipping price.
- shipping_method = checkout_info.delivery_method_info.delivery_method
+ shipping_method = checkout_info.get_delivery_method_info().delivery_method
tax_class = getattr(shipping_method, "tax_class", None)
shipping_tax_rate = get_tax_rate_for_tax_class(
tax_class,