Skip to content

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

Use promise on Checkout's delivery resolvers (#18867)

Maciej Korycinski85bca2a78240
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 3d316a7827..62222f28ec 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -51,13 +51,13 @@ def call_checkout_event(
raise ValueError(f"Event {event_name} not found in CHECKOUT_WEBHOOK_EVENT_MAP.")
webhook_event_map = get_webhooks_for_multiple_events(
- [event_name, *WebhookEventSyncType.CHECKOUT_EVENTS]
+ [event_name, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
webhooks = webhook_event_map.get(event_name, set())
if not webhook_async_event_requires_sync_webhooks_to_trigger(
event_name,
webhook_event_map,
- possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,
+ possible_sync_events=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
):
plugin_manager_method_name = CHECKOUT_WEBHOOK_EVENT_MAP[event_name]
event_func = getattr(manager, plugin_manager_method_name)
@@ -89,9 +89,6 @@ def _trigger_checkout_sync_webhooks(
webhook_event_map: dict[str, set["Webhook"]],
address: Optional["Address"] = None,
):
- from .delivery_context import get_or_fetch_checkout_deliveries
-
- get_or_fetch_checkout_deliveries(checkout_info)
# + timedelta(seconds=10) to confirm that triggered webhooks will still have
# valid prices. Triggered only when we have active sync tax webhook.
if webhook_event_map.get(
@@ -119,13 +116,13 @@ def call_checkout_events(
)
webhook_event_map = get_webhooks_for_multiple_events(
- [*event_names, *WebhookEventSyncType.CHECKOUT_EVENTS]
+ [*event_names, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
any_event_requires_sync_webhooks = any(
webhook_async_event_requires_sync_webhooks_to_trigger(
event_name,
webhook_event_map,
- possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,
+ possible_sync_events=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
)
for event_name in event_names
)
@@ -160,7 +157,7 @@ def call_checkout_info_event(
checkout = checkout_info.checkout
if webhook_event_map is None:
webhook_event_map = get_webhooks_for_multiple_events(
- [event_name, *WebhookEventSyncType.CHECKOUT_EVENTS]
+ [event_name, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
if event_name not in CHECKOUT_WEBHOOK_EVENT_MAP:
raise ValueError(f"Event {event_name} not found in CHECKOUT_WEBHOOK_EVENT_MAP.")
@@ -175,7 +172,7 @@ def call_checkout_info_event(
if not webhook_async_event_requires_sync_webhooks_to_trigger(
event_name,
webhook_event_map,
- possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,
+ possible_sync_events=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
):
call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
return
diff --git a/saleor/checkout/delivery_context.py b/saleor/checkout/delivery_context.py
index 72aae0b0ef..c3972a292f 100644
--- a/saleor/checkout/delivery_context.py
+++ b/saleor/checkout/delivery_context.py
@@ -10,11 +10,13 @@ from django.utils import timezone
from prices import Money
from promise import Promise
-from ..core.db.connection import allow_writer
+from ..core.db.connection import (
+ allow_writer,
+)
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..discount import VoucherType
-from ..shipping.interface import ShippingMethodData
+from ..shipping.interface import ExcludedShippingMethod, ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
from ..shipping.utils import (
convert_shipping_method_data_to_checkout_delivery,
@@ -29,7 +31,8 @@ from .lock_objects import checkout_qs_select_for_update
from .models import Checkout, CheckoutDelivery, CheckoutLine
if TYPE_CHECKING:
- from ..account.models import Address
+ from ..account.models import Address, User
+ from ..app.models import App
from ..plugins.manager import PluginsManager
from .fetch import CheckoutInfo, CheckoutLineInfo
@@ -539,10 +542,10 @@ def _refreshed_assigned_delivery_has_impact_on_prices(
return False
-@allow_writer()
def fetch_shipping_methods_for_checkout(
checkout_info: "CheckoutInfo",
-) -> list[CheckoutDelivery]:
+ requestor: Union["App", "User", None],
+) -> Promise[list[CheckoutDelivery]]:
"""Fetch shipping methods for the checkout.
Fetches all available shipping methods, both built-in and external, for the given
@@ -559,101 +562,106 @@ def fetch_shipping_methods_for_checkout(
checkout_info=checkout_info
)
}
- external_shipping_methods_dict: dict[str, ShippingMethodData] = {
- shipping_method.id: shipping_method
- for shipping_method in fetch_external_shipping_methods_for_checkout_info(
- checkout_info=checkout_info,
- available_built_in_methods=list(built_in_shipping_methods_dict.values()),
- ).get()
- }
- all_methods = list(built_in_shipping_methods_dict.values()) + list(
- external_shipping_methods_dict.values()
- )
-
- # Circular import caused by the current definition of subscription payloads
- # and their usage in webhook/transport layer. Until moving them out from the
- # transport, we will have circular imports.
- from .webhooks.exclude_shipping import excluded_shipping_methods_for_checkout
-
- allow_replica = not (
- checkout_info.database_connection_name
- == settings.DATABASE_CONNECTION_DEFAULT_NAME
- )
-
- requestor = (
- checkout_info.manager.requestor_getter()
- if checkout_info.manager.requestor_getter
- else None
- )
-
- excluded_methods = excluded_shipping_methods_for_checkout(
- checkout,
- available_shipping_methods=all_methods,
- allow_replica=allow_replica,
- requestor=requestor,
- ).get()
- initialize_shipping_method_active_status(all_methods, excluded_methods)
-
- checkout_deliveries = {}
- for shipping_method_data in all_methods:
- checkout_delivery_method = convert_shipping_method_data_to_checkout_delivery(
- shipping_method_data, checkout
+ def with_external_methods(external_shipping_methods: list[ShippingMethodData]):
+ external_shipping_methods_dict: dict[str, ShippingMethodData] = {
+ shipping_method.id: shipping_method
+ for shipping_method in external_shipping_methods
+ }
+ all_methods = list(built_in_shipping_methods_dict.values()) + list(
+ external_shipping_methods_dict.values()
)
- checkout_deliveries[shipping_method_data.id] = checkout_delivery_method
-
- with traced_atomic_transaction():
- locked_checkout = (
- checkout_qs_select_for_update().filter(token=checkout.token).first()
+ # Circular import caused by the current definition of subscription payloads
+ # and their usage in webhook/transport layer. Until moving them out from the
+ # transport, we will have circular imports.
+ from .webhooks.exclude_shipping import excluded_shipping_methods_for_checkout
+
+ allow_replica = not (
+ checkout_info.database_connection_name
+ == settings.DATABASE_CONNECTION_DEFAULT_NAME
)
- if not locked_checkout:
- return []
- if locked_checkout.assigned_delivery_id != checkout.assigned_delivery_id:
- return []
-
- assigned_delivery = checkout.assigned_delivery
- checkout.delivery_methods_stale_at = (
- timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
- )
- checkout.save(update_fields=["delivery_methods_stale_at"])
-
- _refresh_checkout_deliveries(
- checkout=locked_checkout,
- assigned_delivery=assigned_delivery,
- checkout_deliveries=list(checkout_deliveries.values()),
- built_in_shipping_methods_dict=built_in_shipping_methods_dict,
- external_shipping_methods_dict=external_shipping_methods_dict,
- )
+ @allow_writer()
+ def with_excluded_methods(excluded_methods: list[ExcludedShippingMethod]):
+ initialize_shipping_method_active_status(all_methods, excluded_methods)
+ checkout_deliveries = {}
+
+ for shipping_method_data in all_methods:
+ checkout_delivery_method = (
+ convert_shipping_method_data_to_checkout_delivery(
+ shipping_method_data, checkout
+ )
+ )
+ checkout_deliveries[shipping_method_data.id] = checkout_delivery_method
+
+ with traced_atomic_transaction():
+ locked_checkout = (
+ checkout_qs_select_for_update().filter(token=checkout.token).first()
+ )
+ if not locked_checkout:
+ return []
+ if (
+ locked_checkout.assigned_delivery_id
+ != checkout.assigned_delivery_id
+ ):
+ return []
+
+ assigned_delivery = checkout.assigned_delivery
+
+ checkout.delivery_methods_stale_at = (
+ timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+
+ _refresh_checkout_deliveries(
+ checkout=locked_checkout,
+ assigned_delivery=assigned_delivery,
+ checkout_deliveries=list(checkout_deliveries.values()),
+ built_in_shipping_methods_dict=built_in_shipping_methods_dict,
+ external_shipping_methods_dict=external_shipping_methods_dict,
+ )
+
+ if _refreshed_assigned_delivery_has_impact_on_prices(
+ assigned_delivery,
+ built_in_shipping_methods_dict,
+ external_shipping_methods_dict,
+ ):
+ from .utils import invalidate_checkout
+
+ invalidate_checkout(
+ checkout_info=checkout_info,
+ lines=checkout_info.lines,
+ manager=checkout_info.manager,
+ recalculate_discount=True,
+ save=True,
+ )
+ if checkout_deliveries:
+ return list(
+ CheckoutDelivery.objects.filter(
+ checkout_id=checkout.pk,
+ is_valid=True,
+ )
+ )
+ return []
- if _refreshed_assigned_delivery_has_impact_on_prices(
- assigned_delivery,
- built_in_shipping_methods_dict,
- external_shipping_methods_dict,
- ):
- from .utils import invalidate_checkout
-
- invalidate_checkout(
- checkout_info=checkout_info,
- lines=checkout_info.lines,
- manager=checkout_info.manager,
- recalculate_discount=True,
- save=True,
- )
+ return excluded_shipping_methods_for_checkout(
+ checkout,
+ available_shipping_methods=all_methods,
+ allow_replica=allow_replica,
+ requestor=requestor,
+ ).then(with_excluded_methods)
- if checkout_deliveries:
- return list(
- CheckoutDelivery.objects.filter(
- checkout_id=checkout.pk,
- is_valid=True,
- )
- )
- return []
+ return fetch_external_shipping_methods_for_checkout_info(
+ checkout_info=checkout_info,
+ available_built_in_methods=list(built_in_shipping_methods_dict.values()),
+ requestor=requestor,
+ ).then(with_external_methods)
def fetch_external_shipping_methods_for_checkout_info(
checkout_info,
available_built_in_methods: list[ShippingMethodData],
+ requestor: Union["App", "User", None],
) -> Promise[list[ShippingMethodData]]:
from .webhooks.list_shipping_methods import list_shipping_methods_for_checkout
@@ -661,11 +669,7 @@ def fetch_external_shipping_methods_for_checkout_info(
checkout_info.database_connection_name
== settings.DATABASE_CONNECTION_DEFAULT_NAME
)
- requestor = (
- checkout_info.manager.requestor_getter()
- if checkout_info.manager.requestor_getter
- else None
- )
+
return list_shipping_methods_for_checkout(
checkout=checkout_info.checkout,
built_in_shipping_methods=available_built_in_methods,
@@ -676,7 +680,9 @@ def fetch_external_shipping_methods_for_checkout_info(
def get_or_fetch_checkout_deliveries(
checkout_info: "CheckoutInfo",
-) -> list[CheckoutDelivery]:
+ requestor: Union["App", "User", None],
+ allow_sync_webhooks: bool = True,
+) -> Promise[list[CheckoutDelivery]]:
"""Get or fetch shipping methods for the checkout.
If the checkout's shipping methods are stale or missing, fetch and update them.
@@ -686,12 +692,16 @@ def get_or_fetch_checkout_deliveries(
if (
checkout.delivery_methods_stale_at is None
or checkout.delivery_methods_stale_at <= timezone.now()
- ):
- return fetch_shipping_methods_for_checkout(checkout_info)
- return list(
- CheckoutDelivery.objects.filter(
- checkout_id=checkout.pk,
- is_valid=True,
+ ) and allow_sync_webhooks:
+ return fetch_shipping_methods_for_checkout(checkout_info, requestor=requestor)
+ return Promise.resolve(
+ list(
+ CheckoutDelivery.objects.using(
+ checkout_info.database_connection_name
+ ).filter(
+ checkout_id=checkout.pk,
+ is_valid=True,
+ )
)
)
@@ -710,20 +720,16 @@ def assign_delivery_method_to_checkout(
checkout=checkout_info.checkout
)
checkout_info.collection_point = None
- checkout_info.assigned_delivery = None
-
elif isinstance(delivery_method, CheckoutDelivery):
fields_to_update = assign_shipping_method_to_checkout(
checkout, delivery_method
)
checkout_info.collection_point = None
- checkout_info.assigned_delivery = delivery_method
elif isinstance(delivery_method, Warehouse):
fields_to_update = assign_collection_point_to_checkout(
checkout, delivery_method
)
checkout_info.shipping_address = checkout.shipping_address
- checkout_info.assigned_delivery = None
if not fields_to_update:
return
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 0c5623c610..d94ce1ed75 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -28,7 +28,7 @@ from .delivery_context import (
ShippingMethodInfo,
get_valid_collection_points_for_checkout,
)
-from .models import Checkout, CheckoutDelivery, CheckoutLine
+from .models import Checkout, CheckoutLine
if TYPE_CHECKING:
from ..account.models import Address, User
@@ -123,7 +123,6 @@ class CheckoutInfo:
tax_configuration: "TaxConfiguration"
discounts: list["CheckoutDiscount"]
lines: list[CheckoutLineInfo]
- assigned_delivery: CheckoutDelivery | None = None
collection_point: Optional["Warehouse"] = None
voucher: Optional["Voucher"] = None
voucher_code: Optional["VoucherCode"] = None
@@ -142,7 +141,7 @@ class CheckoutInfo:
def get_delivery_method_info(self) -> DeliveryMethodBase:
delivery_method: ShippingMethodData | Warehouse | None = None
- if assigned_sm := self.assigned_delivery:
+ if assigned_sm := self.checkout.assigned_delivery:
delivery_method = convert_checkout_delivery_to_shipping_method_data(
assigned_sm
)
@@ -369,7 +368,6 @@ def fetch_checkout_info(
discounts=list(checkout.discounts.all()),
lines=lines,
manager=manager,
- assigned_delivery=checkout.assigned_delivery,
collection_point=checkout.collection_point,
voucher=voucher,
voucher_code=voucher_code,
diff --git a/saleor/checkout/tests/fixtures/checkout_info.py b/saleor/checkout/tests/fixtures/checkout_info.py
index d27adf99aa..c1059abdce 100644
--- a/saleor/checkout/tests/fixtures/checkout_info.py
+++ b/saleor/checkout/tests/fixtures/checkout_info.py
@@ -27,7 +27,6 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):
billing_address=checkout.billing_address,
shipping_address=shipping_address,
tax_configuration=channel.tax_configuration,
- assigned_delivery=checkout.assigned_delivery,
discounts=[],
manager=manager,
lines=lines,
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
index 618852a79b..581a1623b4 100644
--- a/saleor/checkout/tests/test_actions.py
+++ b/saleor/checkout/tests/test_actions.py
@@ -577,8 +577,20 @@ def test_call_checkout_event_triggers_sync_webhook_when_needed(
webhook_id=checkout_created_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
)
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
@@ -672,9 +684,17 @@ def test_call_checkout_event_skips_tax_webhook_when_not_expired(
webhook_id=checkout_created_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
)
+
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
assert (
@@ -919,9 +939,22 @@ def test_call_checkout_info_event_triggers_sync_webhook_when_needed(
webhook_id=checkout_created_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
)
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
+ )
+
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
assert (
@@ -1025,9 +1058,17 @@ def test_call_checkout_info_event_skips_tax_webhook_when_not_expired(
webhook_id=checkout_created_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
)
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
+ )
+
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
assert (
@@ -1243,8 +1284,20 @@ def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
webhook_id=checkout_fully_paid_webhook.id
).exists()
- tax_delivery_call, shipping_methods_call, filter_shipping_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
)
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
@@ -1360,9 +1413,22 @@ def test_transaction_amounts_for_checkout_fully_authorized_triggers_sync_webhook
webhook_id=checkout_fully_authorized_webhook.id
).exists()
- tax_delivery_call, shipping_methods_call, filter_shipping_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
)
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
+ )
+
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
assert (
@@ -1501,9 +1567,22 @@ def test_call_checkout_events_triggers_sync_webhook_when_needed(
webhook_id=checkout_created_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
)
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
+ )
+
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
assert (
@@ -1604,8 +1683,15 @@ def test_call_checkout_events_skips_tax_webhook_when_not_expired(
webhook_id=checkout_created_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
)
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
diff --git a/saleor/checkout/tests/test_delivery_context.py b/saleor/checkout/tests/test_delivery_context.py
index 59fbdefb22..c90a0e2773 100644
--- a/saleor/checkout/tests/test_delivery_context.py
+++ b/saleor/checkout/tests/test_delivery_context.py
@@ -112,7 +112,9 @@ def test_fetch_shipping_methods_for_checkout_with_built_in_shipping_method(
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
# Confirm that new shipping method was created
@@ -191,7 +193,9 @@ def test_fetch_shipping_methods_for_checkout_updates_existing_built_in_shipping_
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
# Confirm that we updated the shipping method instead of creating a new one
@@ -235,7 +239,9 @@ def test_fetch_shipping_methods_for_checkout_removes_non_applicable_built_in_shi
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert CheckoutDelivery.objects.count() == 1
@@ -280,7 +286,9 @@ def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_built_in_sh
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert CheckoutDelivery.objects.count() == 2
@@ -336,7 +344,9 @@ def test_fetch_shipping_methods_for_checkout_with_excluded_built_in_shipping_met
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert len(shipping_methods) == 1
@@ -384,7 +394,7 @@ def test_fetch_shipping_methods_for_checkout_with_changed_price_of_built_in_ship
)
# when
- fetch_shipping_methods_for_checkout(checkout_info)
+ fetch_shipping_methods_for_checkout(checkout_info, requestor=None)
# then
checkout.refresh_from_db()
@@ -437,7 +447,7 @@ def test_fetch_shipping_methods_for_checkout_with_changed_tax_class_of_built_in_
)
# when
- fetch_shipping_methods_for_checkout(checkout_info)
+ fetch_shipping_methods_for_checkout(checkout_info, requestor=None)
# then
checkout.refresh_from_db()
@@ -519,7 +529,9 @@ def test_fetch_shipping_methods_for_checkout_with_external_shipping_method(
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
# Confirms that new shipping method was created
@@ -582,7 +594,9 @@ def test_fetch_shipping_methods_for_checkout_updates_existing_external_shipping_
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert len(shipping_methods) == 1
@@ -646,7 +660,9 @@ def test_fetch_shipping_methods_for_checkout_removes_non_applicable_external_shi
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert len(shipping_methods) == 1
@@ -711,7 +727,9 @@ def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_external_sh
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert CheckoutDelivery.objects.count() == 2
@@ -787,7 +805,9 @@ def test_fetch_shipping_methods_for_checkout_with_excluded_external_shipping_met
)
# when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ shipping_methods = fetch_shipping_methods_for_checkout(
+ checkout_info, requestor=None
+ ).get()
# then
assert len(shipping_methods) == 1
@@ -852,7 +872,7 @@ def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_ship
)
# when
- fetch_shipping_methods_for_checkout(checkout_info)
+ fetch_shipping_methods_for_checkout(checkout_info, requestor=None)
# then
checkout.refresh_from_db()
diff --git a/saleor/checkout/tests/webhooks/test_exclude_shipping.py b/saleor/checkout/tests/webhooks/test_exclude_shipping.py
index f96ef4c75d..ba9fb4a5e7 100644
--- a/saleor/checkout/tests/webhooks/test_exclude_shipping.py
+++ b/saleor/checkout/tests/webhooks/test_exclude_shipping.py
@@ -157,6 +157,7 @@ def test_checkout_deliveries_webhook_called_once(
# given
mocked_webhook.side_effect = [Promise.resolve([]), AssertionError("called twice.")]
staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+
# when
response = staff_api_client.post_graphql(
CHECKOUT_QUERY_SHIPPING_METHOD,
@@ -164,6 +165,7 @@ def test_checkout_deliveries_webhook_called_once(
)
content = get_graphql_content(response)
checkout_data = content["data"]["checkout"]
+
# then
expected_count = ShippingMethod.objects.count()
assert len(checkout_data["availableShippingMethods"]) == expected_count
diff --git a/saleor/checkout/webhooks/exclude_shipping.py b/saleor/checkout/webhooks/exclude_shipping.py
index 3ca3d6b997..7b0f14ce54 100644
--- a/saleor/checkout/webhooks/exclude_shipping.py
+++ b/saleor/checkout/webhooks/exclude_shipping.py
@@ -31,7 +31,7 @@ def excluded_shipping_methods_for_checkout(
available_shipping_methods: list["ShippingMethodData"],
allow_replica: bool,
requestor: Union["App", "User", None],
-) -> "Promise[list[ExcludedShippingMethod]]":
+) -> Promise[list[ExcludedShippingMethod]]:
if not available_shipping_methods:
return Promise.resolve([])
diff --git a/saleor/core/utils/tests/test_events.py b/saleor/core/utils/tests/test_events.py
index 8d03af7a96..6cd1b18ef9 100644
--- a/saleor/core/utils/tests/test_events.py
+++ b/saleor/core/utils/tests/test_events.py
@@ -55,14 +55,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_when_no_webhooks(
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -80,14 +80,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_when_async_webhoo
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -110,14 +110,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_when_sync_webhook
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -137,13 +137,13 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_webhooks_active(
) = setup_checkout_webhooks(event_name)
webhook_event_map = get_webhooks_for_multiple_events(
- [event_name, *WebhookEventSyncType.CHECKOUT_EVENTS]
+ [event_name, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -158,17 +158,17 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_missing_event_in_
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
]
)
+ expected_failure_events = {WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES}
# when & then
with pytest.raises(
ValueError,
- match=(
- f"Event {set(WebhookEventSyncType.CHECKOUT_EVENTS)} not found in "
- "webhook_event_map."
- ),
+ match=(f"Event {expected_failure_events} not found in webhook_event_map."),
):
webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name,
+ webhook_event_map,
+ [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
)
@@ -216,14 +216,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_f
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -251,14 +251,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_s
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -287,14 +287,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_f
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
@@ -319,14 +319,14 @@ def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_f
webhook_event_map = get_webhooks_for_multiple_events(
[
WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- *WebhookEventSyncType.CHECKOUT_EVENTS,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
]
)
# when
should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, WebhookEventSyncType.CHECKOUT_EVENTS
+ event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
)
# then
diff --git a/saleor/graphql/checkout/dataloaders/checkout_delivery.py b/saleor/graphql/checkout/dataloaders/checkout_delivery.py
index d253c86907..a0032543b5 100644
--- a/saleor/graphql/checkout/dataloaders/checkout_delivery.py
+++ b/saleor/graphql/checkout/dataloaders/checkout_delivery.py
@@ -1,8 +1,14 @@
-from collections import defaultdict
+from itertools import chain
from uuid import UUID
+from promise import Promise
+
+from ....checkout.delivery_context import get_or_fetch_checkout_deliveries
from ....checkout.models import CheckoutDelivery
+from ....core.db.connection import allow_writer_in_context
from ...core.dataloaders import DataLoader
+from ...utils import get_user_or_app_from_context
+from .checkout_infos import CheckoutInfoByCheckoutTokenLoader
class CheckoutDeliveryByIdLoader(DataLoader[UUID, CheckoutDelivery]):
@@ -15,16 +21,40 @@ class CheckoutDeliveryByIdLoader(DataLoader[UUID, CheckoutDelivery]):
return [shipping_methods.get(key) for key in keys]
-class CheckoutDeliveriesOnlyValidByCheckoutIdLoader(
- DataLoader[UUID, list[CheckoutDelivery]]
+class CheckoutDeliveriesOnlyValidByCheckoutIdAndWebhookSyncLoader(
+ DataLoader[tuple[UUID, bool], list[CheckoutDelivery]]
):
- context_key = "checkout_deliveries_by_checkout_id"
+ context_key = (
+ "checkout_deliveries_only_valid_by_checkout_id_and_webhook_sync_loader"
+ )
def batch_load(self, keys):
- shipping_methods = CheckoutDelivery.objects.using(
- self.database_connection_name
- ).filter(checkout_id__in=keys, is_valid=True)
- shipping_methods_map: dict[UUID, list[CheckoutDelivery]] = defaultdict(list)
- for shipping_method in shipping_methods:
- shipping_methods_map[shipping_method.checkout_id].append(shipping_method)
- return [shipping_methods_map[key] for key in keys]
+ requestor = get_user_or_app_from_context(self.context)
+ checkout_infos = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(
+ [checkout_id for (checkout_id, _) in keys]
+ )
+
+ def refresh_delivery_dataloader(
+ deliveries: list[list[CheckoutDelivery]],
+ ) -> list[list[CheckoutDelivery]]:
+ for delivery in chain.from_iterable(deliveries):
+ CheckoutDeliveryByIdLoader(self.context).clear(delivery.id)
+ CheckoutDeliveryByIdLoader(self.context).prime(delivery.id, delivery)
+ return deliveries
+
+ def with_checkout_infos(checkout_infos):
+ results = []
+ with allow_writer_in_context(self.context):
+ for checkout_info, (_, allow_sync_webhooks) in zip(
+ checkout_infos, keys, strict=True
+ ):
+ results.append(
+ get_or_fetch_checkout_deliveries(
+ checkout_info=checkout_info,
+ requestor=requestor,
+ allow_sync_webhooks=allow_sync_webhooks,
+ )
+ )
+ return Promise.all(results).then(refresh_delivery_dataloader)
+
+ return checkout_infos.then(with_checkout_infos)
diff --git a/saleor/graphql/checkout/dataloaders/checkout_infos.py b/saleor/graphql/checkout/dataloaders/checkout_infos.py
index b76af2a8f2..edca649d7e 100644
--- a/saleor/graphql/checkout/dataloaders/checkout_infos.py
+++ b/saleor/graphql/checkout/dataloaders/checkout_infos.py
@@ -26,7 +26,6 @@ from ...product.dataloaders import (
)
from ...tax.dataloaders import TaxClassByVariantIdLoader, TaxConfigurationByChannelId
from ...warehouse.dataloaders import WarehouseByIdLoader
-from .checkout_delivery import CheckoutDeliveryByIdLoader
from .models import CheckoutByTokenLoader, CheckoutLinesByCheckoutTokenLoader
from .promotion_rule_infos import VariantPromotionRuleInfoByCheckoutLineIdLoader
@@ -85,15 +84,6 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
self.context
).load_many(channel_ids)
- assigned_deliveries_ids = [
- checkout.assigned_delivery_id
- for checkout in checkouts
- if checkout.assigned_delivery_id
- ]
- assigned_deliveries_loader = CheckoutDeliveryByIdLoader(
- self.context
- ).load_many(assigned_deliveries_ids)
-
def with_checkout_info(results):
(
addresses,
@@ -101,7 +91,6 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
collection_points,
voucher_codes,
tax_configurations,
- assigned_deliveries,
) = results
address_map = {address.id: address for address in addresses}
user_map = {user.id: user for user in users}
@@ -120,11 +109,6 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
tax_configuration.channel_id: tax_configuration
for tax_configuration in tax_configurations
}
- assigned_deliveries_map = {
- delivery.id: delivery
- for delivery in assigned_deliveries
- if delivery
- }
checkout_info_map = {}
for (
@@ -141,9 +125,6 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
checkout_discounts,
strict=False,
):
- assigned_delivery = assigned_deliveries_map.get(
- checkout.assigned_delivery_id
- )
collection_point = collection_points_map.get(
checkout.collection_point_id
)
@@ -166,7 +147,6 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
lines=checkout_lines,
manager=manager,
collection_point=collection_point,
- assigned_delivery=assigned_delivery,
voucher=voucher_code.voucher if voucher_code else None,
voucher_code=voucher_code,
database_connection_name=self.database_connection_name,
@@ -182,7 +162,6 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
collection_points,
voucher_codes,
tax_configurations,
- assigned_deliveries_loader,
]
).then(with_checkout_info)
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 348f80d8d2..6032976232 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -1,6 +1,10 @@
+from typing import Union
+
import graphene
from django.core.exceptions import ValidationError
+from ....account.models import User
+from ....app.models import App
from ....checkout import AddressType, models
from ....checkout.checkout_cleaner import (
clean_checkout_shipping,
@@ -176,6 +180,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):
checkout_info: CheckoutInfo,
lines: list[CheckoutLineInfo],
info: ResolveInfo,
+ requestor: Union["App", "User", None],
):
"""Validate checkout addresses.
@@ -189,9 +194,11 @@ class CheckoutComplete(BaseMutation, I18nMixin):
billing_address = checkout_info.billing_address
if is_shipping_required(lines):
- if checkout_info.assigned_delivery:
+ if checkout_info.checkout.assigned_delivery:
# Refresh stale shipping if needed
- get_or_fetch_checkout_deliveries(checkout_info)
+ get_or_fetch_checkout_deliveries(
+ checkout_info, requestor=requestor
+ ).get()
clean_checkout_shipping(checkout_info, lines, CheckoutErrorCode)
if shipping_address:
shipping_address_data = shipping_address.as_data()
@@ -321,8 +328,11 @@ class CheckoutComplete(BaseMutation, I18nMixin):
)
checkout_info = fetch_checkout_info(checkout, lines, manager)
+ requestor = get_user_or_app_from_context(info.context)
try:
- cls.validate_checkout_addresses(checkout_info, lines, info)
+ cls.validate_checkout_addresses(
+ checkout_info, lines, info, requestor=requestor
+ )
except models.Checkout.DoesNotExist as e:
order = order_models.Order.objects.get_by_checkout_token(
checkout_info.checkout.token
@@ -342,7 +352,6 @@ class CheckoutComplete(BaseMutation, I18nMixin):
}
) from e
- requestor = get_user_or_app_from_context(info.context)
if requestor and requestor.has_perm(AccountPermissions.IMPERSONATE_USER):
# Allow impersonating user and process a checkout by using user details
# assigned to checkout.
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index 098c99944f..6173b1b799 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Union
import graphene
from django.core.exceptions import ValidationError
@@ -11,7 +11,6 @@ from ....checkout.delivery_context import (
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
CheckoutInfo,
- CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
)
@@ -19,7 +18,6 @@ from ....checkout.models import CheckoutDelivery
from ....warehouse import models as warehouse_models
from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
-from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
from ...core.descriptions import DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_CHECKOUT
@@ -28,6 +26,7 @@ from ...core.scalars import UUID
from ...core.types import CheckoutError
from ...core.utils import WebhookEventInfo, from_global_id_or_error
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...utils import get_user_or_app_from_context
from ..types import Checkout
from .utils import (
ERROR_DOES_NOT_SHIP,
@@ -35,7 +34,8 @@ from .utils import (
)
if TYPE_CHECKING:
- from ....plugins.manager import PluginsManager
+ from ....account.models import User
+ from ....app.models import App
class CheckoutDeliveryMethodUpdate(BaseMutation):
@@ -128,12 +128,17 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
@classmethod
def get_checkout_delivery(
- cls, checkout_info: CheckoutInfo, internal_shipping_method_id: str | None
+ cls,
+ checkout_info: CheckoutInfo,
+ internal_shipping_method_id: str | None,
+ requestor: Union["App", "User", None],
) -> CheckoutDelivery | None:
if internal_shipping_method_id is None:
return None
- checkout_deliveries = get_or_fetch_checkout_deliveries(checkout_info)
+ checkout_deliveries = get_or_fetch_checkout_deliveries(
+ checkout_info, requestor=requestor
+ ).get()
for method in checkout_deliveries:
if not method.active:
continue
@@ -153,10 +158,8 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
def get_delivery_method_data(
cls,
checkout_info: CheckoutInfo,
- lines_info: list[CheckoutLineInfo],
- delivery_method_id: str,
- manager: "PluginsManager",
- info: ResolveInfo,
+ delivery_method_id: str | None,
+ requestor: Union["App", "User", None],
) -> CheckoutDelivery | warehouse_models.Warehouse | None:
if delivery_method_id is None:
return None
@@ -170,7 +173,9 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
if type_name == "Warehouse":
delivery_method_data = cls.get_collection_point(checkout_info, internal_id)
else:
- delivery_method_data = cls.get_checkout_delivery(checkout_info, internal_id)
+ delivery_method_data = cls.get_checkout_delivery(
+ checkout_info, internal_id, requestor=requestor
+ )
return delivery_method_data
@classmethod
@@ -188,6 +193,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
use_legacy_error_flow_for_checkout = (
checkout.channel.use_legacy_error_flow_for_checkout
)
+ requestor = get_user_or_app_from_context(info.context)
manager = get_plugin_manager_promise(info.context).get()
lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
@@ -218,7 +224,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
checkout_info = fetch_checkout_info(checkout, lines, manager)
delivery_method_data = cls.get_delivery_method_data(
- checkout_info, lines, delivery_method_id, manager, info
+ checkout_info, delivery_method_id, requestor=requestor
)
assign_delivery_method_to_checkout(
checkout_info,
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index 28f57a6cbf..55fd7dfdaf 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -1,9 +1,14 @@
+from typing import Union
+
import graphene
from django.core.exceptions import ValidationError
+from ....account.models import User
+from ....app.models import App
from ....checkout.delivery_context import (
assign_delivery_method_to_checkout,
get_or_fetch_checkout_deliveries,
+ is_shipping_required,
)
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
@@ -12,9 +17,6 @@ from ....checkout.fetch import (
fetch_checkout_lines,
)
from ....checkout.models import CheckoutDelivery
-from ....checkout.utils import (
- is_shipping_required,
-)
from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...core import ResolveInfo
@@ -26,6 +28,7 @@ from ...core.scalars import UUID
from ...core.types import CheckoutError
from ...core.utils import WebhookEventInfo, from_global_id_or_error
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...utils import get_user_or_app_from_context
from ..types import Checkout
from .utils import (
ERROR_DOES_NOT_SHIP,
@@ -97,11 +100,16 @@ class CheckoutShippingMethodUpdate(BaseMutation):
@classmethod
def get_checkout_delivery(
- cls, checkout_info: CheckoutInfo, shipping_method_id: str | None
+ cls,
+ checkout_info: CheckoutInfo,
+ shipping_method_id: str | None,
+ requestor: Union["App", "User", None],
) -> CheckoutDelivery | None:
if shipping_method_id is None:
return None
- checkout_deliveries = get_or_fetch_checkout_deliveries(checkout_info)
+ checkout_deliveries = get_or_fetch_checkout_deliveries(
+ checkout_info, requestor=requestor
+ ).get()
internal_shipping_method_id = cls._resolve_delivery_method_id(
shipping_method_id
)
@@ -141,6 +149,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
checkout.channel.use_legacy_error_flow_for_checkout
)
+ requestor = get_user_or_app_from_context(info.context)
manager = get_plugin_manager_promise(info.context).get()
lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
@@ -169,7 +178,9 @@ class CheckoutShippingMethodUpdate(BaseMutation):
}
)
- checkout_delivery = cls.get_checkout_delivery(checkout_info, shipping_method_id)
+ checkout_delivery = cls.get_checkout_delivery(
+ checkout_info, shipping_method_id, requestor=requestor
+ )
assign_delivery_method_to_checkout(
checkout_info,
lines,
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index 259691793d..35ba7bd5b9 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -1,6 +1,10 @@
+from typing import Union
+
import graphene
from django.core.exceptions import ValidationError
+from ....account.models import User
+from ....app.models import App
from ....checkout.checkout_cleaner import validate_checkout
from ....checkout.complete_checkout import create_order_from_checkout
from ....checkout.delivery_context import (
@@ -162,10 +166,14 @@ class OrderCreateFromCheckout(BaseMutation):
checkout_lines: list[CheckoutLineInfo],
unavailable_variant_pks: list[int],
manager,
+ requestor: Union["App", "User", None],
):
- if is_shipping_required(checkout_lines) and checkout_info.assigned_delivery:
+ if (
+ is_shipping_required(checkout_lines)
+ and checkout_info.checkout.assigned_delivery
+ ):
# Refresh stale shipping if needed
- get_or_fetch_checkout_deliveries(checkout_info)
+ get_or_fetch_checkout_deliveries(checkout_info, requestor=requestor).get()
validate_checkout(
checkout_info=checkout_info,
lines=checkout_lines,
@@ -209,10 +217,16 @@ class OrderCreateFromCheckout(BaseMutation):
checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
+ app = get_app_promise(info.context).get()
+ requestor = app or user
+
cls.validate_checkout(
- checkout_info, checkout_lines, unavailable_variant_pks, manager
+ checkout_info,
+ checkout_lines,
+ unavailable_variant_pks,
+ manager,
+ requestor=requestor,
)
- app = get_app_promise(info.context).get()
try:
order = create_order_from_checkout(
checkout_info=checkout_info,
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 ca42ee3193..b22eae3fd7 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
@@ -97,7 +97,7 @@ def test_checkout_shipping_method_update(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
mock_get_or_fetch_checkout_deliveries.assert_called_once_with(
- checkout_info,
+ checkout_info, requestor=staff_api_client.user
)
errors = data["errors"]
assert not errors
@@ -150,7 +150,7 @@ def test_checkout_shipping_method_update_not_valid_shipping_method(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
mock_get_or_fetch_checkout_deliveries.assert_called_once_with(
- checkout_info,
+ checkout_info, requestor=staff_api_client.user
)
errors = data["errors"]
assert len(errors) == 1
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index e805d5a9a6..e39fa93f26 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,16 +1,13 @@
-import uuid
from decimal import Decimal
from typing import TYPE_CHECKING, Any
import graphene
-from django.utils import timezone
from promise import Promise
from ...account.models import User
from ...checkout import calculations, models, problems
from ...checkout.calculations import fetch_checkout_data
from ...checkout.delivery_context import (
- fetch_shipping_methods_for_checkout,
get_valid_collection_points_for_checkout,
)
from ...core.db.connection import allow_writer_in_context
@@ -104,7 +101,7 @@ from .dataloaders import (
TransactionItemsByCheckoutIDLoader,
)
from .dataloaders.checkout_delivery import (
- CheckoutDeliveriesOnlyValidByCheckoutIdLoader,
+ CheckoutDeliveriesOnlyValidByCheckoutIdAndWebhookSyncLoader,
CheckoutDeliveryByIdLoader,
)
from .enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
@@ -659,108 +656,25 @@ class Delivery(graphene.ObjectType):
return convert_checkout_delivery_to_shipping_method_data(root)
-def _should_load_denormalized_checkout_deliveries(
- checkout_context: SyncWebhookControlContext[models.Checkout],
-):
- return not checkout_context.allow_sync_webhooks or (
- checkout_context.node.delivery_methods_stale_at
- and checkout_context.node.delivery_methods_stale_at > timezone.now()
- )
-
-
-def _load_denormalized_checkout_deliveries(checkout_pk: uuid.UUID, info: ResolveInfo):
- return (
- CheckoutDeliveriesOnlyValidByCheckoutIdLoader(info.context)
- .load(checkout_pk)
- .then(
- lambda shipping_methods: [
- convert_checkout_delivery_to_shipping_method_data(sm)
- for sm in shipping_methods
- ]
- )
- )
-
-
-def _resolve_checkout_deliveries(
- root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
-):
- checkout = root.node
-
- def with_checkout_info(checkout_info):
- if _should_load_denormalized_checkout_deliveries(root):
- return _load_denormalized_checkout_deliveries(checkout.pk, info)
-
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
- checkout.delivery_methods_stale_at = (
- checkout_info.checkout.delivery_methods_stale_at
- )
- CheckoutDeliveriesOnlyValidByCheckoutIdLoader(info.context).prime(
- checkout.pk, shipping_methods
- )
- return [
- convert_checkout_delivery_to_shipping_method_data(sm)
- for sm in shipping_methods
- ]
-
- if _should_load_denormalized_checkout_deliveries(root):
- return _load_denormalized_checkout_deliveries(checkout.pk, info)
-
- return (
- CheckoutInfoByCheckoutTokenLoader(info.context)
- .load(root.node.token)
- .then(with_checkout_info)
- )
-
-
def _resolve_checkout_delivery(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
-) -> Promise[ShippingMethodData | None] | None:
+) -> Promise[ShippingMethodData | None]:
checkout = root.node
assigned_delivery_id = checkout.assigned_delivery_id
if not assigned_delivery_id:
- return None
-
- if (
- checkout.delivery_methods_stale_at
- and checkout.delivery_methods_stale_at > timezone.now()
- ) or not root.allow_sync_webhooks:
- return (
- CheckoutDeliveryByIdLoader(info.context)
- .load(assigned_delivery_id)
- .then(
- lambda sm: (
- convert_checkout_delivery_to_shipping_method_data(sm)
- if sm.is_valid and sm.active
- else None
- )
- )
- )
-
- def with_checkout_info(checkout_info):
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
- root.node.delivery_methods_stale_at = (
- checkout_info.checkout.delivery_methods_stale_at
- )
- CheckoutDeliveriesOnlyValidByCheckoutIdLoader(info.context).prime(
- checkout.pk, shipping_methods
- )
- CheckoutInfoByCheckoutTokenLoader(info.context).clear(root.node.token)
-
- for sm in shipping_methods:
- if sm.id == assigned_delivery_id:
- CheckoutDeliveryByIdLoader(info.context).prime(assigned_delivery_id, sm)
- return convert_checkout_delivery_to_shipping_method_data(sm)
+ return Promise.resolve(None)
- CheckoutDeliveryByIdLoader(info.context).clear(assigned_delivery_id)
+ def get_shipping_method(deliveries: list[models.CheckoutDelivery]):
+ for delivery in deliveries:
+ if delivery.id == assigned_delivery_id:
+ return convert_checkout_delivery_to_shipping_method_data(delivery)
return None
return (
- CheckoutInfoByCheckoutTokenLoader(info.context)
- .load(root.node.token)
- .then(with_checkout_info)
+ CheckoutDeliveriesOnlyValidByCheckoutIdAndWebhookSyncLoader(info.context)
+ .load((checkout.pk, root.allow_sync_webhooks))
+ .then(get_shipping_method)
)
@@ -1154,7 +1068,16 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_shipping_methods(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- return _resolve_checkout_deliveries(root, info)
+ return (
+ CheckoutDeliveriesOnlyValidByCheckoutIdAndWebhookSyncLoader(info.context)
+ .load((root.node.pk, root.allow_sync_webhooks))
+ .then(
+ lambda deliveries: [
+ convert_checkout_delivery_to_shipping_method_data(delivery)
+ for delivery in deliveries
+ ]
+ )
+ )
@staticmethod
def resolve_delivery_method(
@@ -1294,8 +1217,16 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_available_shipping_methods(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- return _resolve_checkout_deliveries(root, info).then(
- lambda methods: [method for method in methods if method.active]
+ return (
+ CheckoutDeliveriesOnlyValidByCheckoutIdAndWebhookSyncLoader(info.context)
+ .load((root.node.pk, root.allow_sync_webhooks))
+ .then(
+ lambda deliveries: [
+ convert_checkout_delivery_to_shipping_method_data(delivery)
+ for delivery in deliveries
+ if delivery.active
+ ]
+ )
)
@staticmethod
diff --git a/saleor/graphql/meta/tests/mutations/test_checkout.py b/saleor/graphql/meta/tests/mutations/test_checkout.py
index 0064039ea0..dbe7e26a3c 100644
--- a/saleor/graphql/meta/tests/mutations/test_checkout.py
+++ b/saleor/graphql/meta/tests/mutations/test_checkout.py
@@ -481,8 +481,20 @@ def test_add_metadata_for_checkout_triggers_webhooks_with_checkout_updated(
webhook_id=checkout_updated_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
)
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
@@ -576,8 +588,20 @@ def test_add_metadata_for_checkout_triggers_webhooks_with_updated_metadata(
webhook_id=checkout_metadata_updated_webhook.id
).exists()
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
+ filter_shipping_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_filter_webhook.id
+ )
+ tax_delivery_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == tax_webhook.id
+ )
+ shipping_methods_call = next(
+ call
+ for call in mocked_send_webhook_request_sync.mock_calls
+ if call.args[0].webhook_id == shipping_webhook.id
)
shipping_methods_delivery = shipping_methods_call.args[0]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 6eea53aae6..530dd969d6 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -3837,7 +3837,6 @@ def test_get_checkout_line_tax_rate(
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
- assigned_delivery=checkout_with_item.assigned_delivery,
user=None,
tax_configuration=checkout_with_item.channel.tax_configuration,
discounts=[],
@@ -3973,7 +3972,6 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
- assigned_delivery=checkout_with_item.assigned_delivery,
user=None,
tax_configuration=checkout_with_item.channel.tax_configuration,
discounts=[],
diff --git a/saleor/shipping/webhooks/shared.py b/saleor/shipping/webhooks/shared.py
index 59185a0472..92058b55ee 100644
--- a/saleor/shipping/webhooks/shared.py
+++ b/saleor/shipping/webhooks/shared.py
@@ -86,7 +86,7 @@ def _get_excluded_shipping_methods_or_fetch(
allow_replica: bool,
requestor: Union["App", "User", None],
cache_data: dict,
-) -> "Promise[dict[str, list[ExcludedShippingMethod]]]":
+) -> 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
@@ -130,7 +130,7 @@ def get_excluded_shipping_data(
allow_replica: bool,
requestor: Union["App", "User", None],
cache_data: dict,
-) -> "Promise[list[ExcludedShippingMethod]]":
+) -> 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
diff --git a/saleor/tax/utils.py b/saleor/tax/utils.py
index 6e03444ac9..fc2873def6 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -284,7 +284,7 @@ def get_shipping_tax_rate_for_checkout(
[line_info.line for line_info in lines], default_tax_rate
)
shipping_tax_rates: Iterable[TaxClassCountryRate] = []
- if assigned_delivery := checkout_info.assigned_delivery:
+ if assigned_delivery := checkout_info.checkout.assigned_delivery:
# external shipping methods do not have a way to provide tax-class
tax_class_id = assigned_delivery.tax_class_id
if tax_class_id:
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index ef03a1e770..4a7454e25f 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -956,11 +956,6 @@ class WebhookEventSyncType:
PAYMENT_REFUND,
PAYMENT_VOID,
]
- CHECKOUT_EVENTS = [
- SHIPPING_LIST_METHODS_FOR_CHECKOUT,
- CHECKOUT_FILTER_SHIPPING_METHODS,
- CHECKOUT_CALCULATE_TAXES,
- ]
ORDER_EVENTS = [ORDER_CALCULATE_TAXES, ORDER_FILTER_SHIPPING_METHODS]
# Events that are used only in the mutation logic can be excluded from the