Skip to content

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

Extract delivery context logic from fetch.py and utils.py into delivery_context.py (#18861)

Maciej Korycinski3a46c2fd7187
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 3a6ad15631..3d316a7827 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -19,7 +19,6 @@ from .fetch import (
CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
- get_or_fetch_checkout_deliveries,
)
from .models import Checkout
from .payment_utils import (
@@ -90,6 +89,8 @@ 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.
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index e18f6de2d5..b84c8ffb3e 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -16,7 +16,8 @@ from ..discount import VoucherType
if TYPE_CHECKING:
from ..channel.models import Channel
- from .fetch import CheckoutInfo, CheckoutLineInfo, ShippingMethodInfo
+ from .delivery_context import ShippingMethodInfo
+ from .fetch import CheckoutInfo, CheckoutLineInfo
def calculate_base_line_unit_price(
@@ -116,7 +117,7 @@ def base_checkout_undiscounted_delivery_price(
lines: list["CheckoutLineInfo"] | None = None,
) -> Money:
"""Calculate base (untaxed) undiscounted price for any kind of delivery method."""
- from .fetch import ShippingMethodInfo
+ from .delivery_context import ShippingMethodInfo
delivery_method_info = checkout_info.get_delivery_method_info()
currency = checkout_info.checkout.currency
@@ -140,7 +141,7 @@ def calculate_base_price_for_shipping_method(
shipping_method = shipping_method_info.delivery_method
if lines is not None and all(isinstance(line, CheckoutLineInfo) for line in lines):
- from .utils import is_shipping_required
+ from .delivery_context import is_shipping_required
shipping_required = is_shipping_required(lines)
else:
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index e37b57b3ef..df3b9fc1ee 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -13,9 +13,10 @@ from ..payment import models as payment_models
from ..payment.error_codes import PaymentErrorCode
from ..plugins.manager import PluginsManager
from . import models
+from .delivery_context import clear_cc_delivery_method, is_shipping_required
from .error_codes import CheckoutErrorCode, OrderCreateFromCheckoutErrorCode
from .models import Checkout
-from .utils import clear_cc_delivery_method, is_fully_paid, is_shipping_required
+from .utils import is_fully_paid
if TYPE_CHECKING:
from .fetch import CheckoutInfo, CheckoutLineInfo
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 6a8e96f87e..68f5363636 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -80,6 +80,7 @@ from .checkout_cleaner import (
clean_checkout_payment,
clean_checkout_shipping,
)
+from .delivery_context import PRIVATE_META_APP_SHIPPING_ID
from .fetch import (
CheckoutInfo,
CheckoutLineInfo,
@@ -88,7 +89,6 @@ from .fetch import (
)
from .models import Checkout
from .utils import (
- PRIVATE_META_APP_SHIPPING_ID,
calculate_checkout_weight,
delete_checkouts,
get_checkout_metadata,
diff --git a/saleor/checkout/delivery_context.py b/saleor/checkout/delivery_context.py
new file mode 100644
index 0000000000..72aae0b0ef
--- /dev/null
+++ b/saleor/checkout/delivery_context.py
@@ -0,0 +1,743 @@
+from dataclasses import dataclass
+from decimal import Decimal
+from typing import TYPE_CHECKING, Any, Optional, Union
+from uuid import UUID
+
+from django.conf import settings
+from django.db import transaction
+from django.db.models import Q
+from django.utils import timezone
+from prices import Money
+from promise import Promise
+
+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.models import ShippingMethod, ShippingMethodChannelListing
+from ..shipping.utils import (
+ convert_shipping_method_data_to_checkout_delivery,
+ convert_to_shipping_method_data,
+ initialize_shipping_method_active_status,
+)
+from ..warehouse import WarehouseClickAndCollectOption
+from ..warehouse.models import Warehouse
+from ..webhook.event_types import WebhookEventAsyncType
+from . import base_calculations
+from .lock_objects import checkout_qs_select_for_update
+from .models import Checkout, CheckoutDelivery, CheckoutLine
+
+if TYPE_CHECKING:
+ from ..account.models import Address
+ from ..plugins.manager import PluginsManager
+ from .fetch import CheckoutInfo, CheckoutLineInfo
+
+
+PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"
+
+
+@dataclass(frozen=True)
+class DeliveryMethodBase:
+ delivery_method: Union["ShippingMethodData", "Warehouse"] | None = None
+ shipping_address: Optional["Address"] = None
+ store_as_customer_address: bool = False
+
+ @property
+ def warehouse_pk(self) -> UUID | None:
+ pass
+
+ @property
+ def delivery_method_order_field(self) -> dict:
+ return {"shipping_method": self.delivery_method}
+
+ @property
+ def is_local_collection_point(self) -> bool:
+ return False
+
+ @property
+ def delivery_method_name(self) -> dict[str, str | None]:
+ return {"shipping_method_name": None}
+
+ def get_warehouse_filter_lookup(self) -> dict[str, Any]:
+ return {}
+
+ def is_valid_delivery_method(self) -> bool:
+ return False
+
+ def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:
+ return False
+
+ def is_delivery_method_set(self) -> bool:
+ return bool(self.delivery_method)
+
+ def get_details_for_conversion_to_order(self) -> dict[str, Any]:
+ return {"shipping_method_name": None}
+
+
+@dataclass(frozen=True)
+class ShippingMethodInfo(DeliveryMethodBase):
+ delivery_method: "ShippingMethodData"
+ shipping_address: Optional["Address"]
+ store_as_customer_address: bool = True
+
+ @property
+ def delivery_method_name(self) -> dict[str, str | None]:
+ return {"shipping_method_name": str(self.delivery_method.name)}
+
+ @property
+ def delivery_method_order_field(self) -> dict:
+ if not self.delivery_method.is_external:
+ return {"shipping_method_id": int(self.delivery_method.id)}
+ return {}
+
+ def is_valid_delivery_method(self) -> bool:
+ return bool(self.shipping_address)
+
+ def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:
+ return self.delivery_method.active
+
+ def get_details_for_conversion_to_order(self) -> dict[str, str | int | None]:
+ details: dict[str, str | int | None] = {
+ "shipping_method_name": str(self.delivery_method.name)
+ }
+ if not self.delivery_method.is_external:
+ details["shipping_method_id"] = int(self.delivery_method.id)
+
+ if self.delivery_method.tax_class:
+ details["shipping_tax_class_id"] = self.delivery_method.tax_class.id
+ details["shipping_tax_class_name"] = str(
+ self.delivery_method.tax_class.name
+ )
+ details["shipping_tax_class_private_metadata"] = (
+ self.delivery_method.tax_class.private_metadata
+ )
+ details["shipping_tax_class_metadata"] = (
+ self.delivery_method.tax_class.metadata
+ )
+ return details
+
+
+@dataclass(frozen=True)
+class CollectionPointInfo(DeliveryMethodBase):
+ delivery_method: "Warehouse"
+ shipping_address: Optional["Address"]
+
+ @property
+ def warehouse_pk(self):
+ return self.delivery_method.pk
+
+ @property
+ def delivery_method_order_field(self) -> dict:
+ return {"collection_point": self.delivery_method}
+
+ @property
+ def is_local_collection_point(self):
+ return (
+ self.delivery_method.click_and_collect_option
+ == WarehouseClickAndCollectOption.LOCAL_STOCK
+ )
+
+ @property
+ def delivery_method_name(self) -> dict[str, str | None]:
+ return {"collection_point_name": str(self.delivery_method)}
+
+ def get_warehouse_filter_lookup(self) -> dict[str, Any]:
+ return (
+ {"warehouse_id": self.delivery_method.pk}
+ if self.is_local_collection_point
+ else {}
+ )
+
+ def is_valid_delivery_method(self) -> bool:
+ return (
+ self.shipping_address is not None
+ and self.shipping_address == self.delivery_method.address
+ )
+
+ def is_method_in_valid_methods(self, checkout_info) -> bool:
+ valid_delivery_methods = checkout_info.valid_pick_up_points
+ return bool(
+ valid_delivery_methods and self.delivery_method in valid_delivery_methods
+ )
+
+ def get_details_for_conversion_to_order(self) -> dict[str, Any]:
+ return {
+ "collection_point_name": str(self.delivery_method),
+ "collection_point": self.delivery_method,
+ }
+
+
+def is_shipping_required(lines: list["CheckoutLineInfo"]):
+ """Check if shipping is required for given checkout lines."""
+ return any(line_info.product_type.is_shipping_required for line_info in lines)
+
+
+def get_valid_internal_shipping_methods_for_checkout_info(
+ checkout_info: "CheckoutInfo",
+ subtotal: "Money",
+) -> list[ShippingMethodData]:
+ 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(
+ 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=checkout_info.lines,
+ )
+
+ shipping_channel_listings = ShippingMethodChannelListing.objects.using(
+ checkout_info.database_connection_name
+ ).filter(
+ channel_id=checkout_info.channel.id,
+ shipping_method_id__in=[method.pk for method in shipping_methods],
+ )
+
+ channel_listings_map = {
+ listing.shipping_method_id: listing for listing in shipping_channel_listings
+ }
+
+ internal_methods: list[ShippingMethodData] = []
+ for method in shipping_methods:
+ listing = channel_listings_map.get(method.pk)
+ if listing:
+ shipping_method_data = convert_to_shipping_method_data(method, listing)
+ internal_methods.append(shipping_method_data)
+
+ return internal_methods
+
+
+def get_valid_collection_points_for_checkout(
+ lines: list["CheckoutLineInfo"],
+ channel_id: int,
+ quantity_check: bool = True,
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+):
+ """Return a collection of `Warehouse`s that can be used as a collection point.
+
+ Note that `quantity_check=False` should be used, when stocks quantity will
+ be validated in further steps (checkout completion) in order to raise
+ 'InsufficientProductStock' error instead of 'InvalidShippingError'.
+ """
+ if not is_shipping_required(lines):
+ return []
+
+ line_ids = [line_info.line.id for line_info in lines]
+ lines = CheckoutLine.objects.using(database_connection_name).filter(id__in=line_ids)
+
+ return (
+ Warehouse.objects.using(
+ database_connection_name
+ ).applicable_for_click_and_collect(lines, channel_id)
+ if quantity_check
+ else Warehouse.objects.using(
+ database_connection_name
+ ).applicable_for_click_and_collect_no_quantity_check(lines, channel_id)
+ )
+
+
+def _remove_external_shipping_from_metadata(checkout: Checkout):
+ from .utils import get_checkout_metadata
+
+ metadata = get_checkout_metadata(checkout)
+ if not metadata:
+ return
+
+ field_deleted = metadata.delete_value_from_private_metadata(
+ PRIVATE_META_APP_SHIPPING_ID
+ )
+ if field_deleted:
+ 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 _assign_undiscounted_base_shipping_price_to_checkout(
+ checkout, checkout_delivery: CheckoutDelivery
+):
+ current_shipping_price = quantize_price(
+ checkout.undiscounted_base_shipping_price, checkout.currency
+ )
+ new_shipping_price = quantize_price(checkout_delivery.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_shipping_method_to_checkout(
+ checkout: Checkout, checkout_delivery: CheckoutDelivery
+) -> list[str]:
+ fields_to_update = []
+ fields_to_update += remove_click_and_collect_from_checkout(checkout)
+ fields_to_update += _assign_undiscounted_base_shipping_price_to_checkout(
+ checkout, checkout_delivery
+ )
+ if checkout.assigned_delivery_id != checkout_delivery.id:
+ checkout.assigned_delivery = checkout_delivery
+ fields_to_update.append("assigned_delivery_id")
+
+ # make sure that we don't have obsolete data for shipping methods stored in
+ # private metadata
+ _remove_external_shipping_from_metadata(checkout=checkout)
+
+ if checkout.shipping_method_name != checkout_delivery.name:
+ checkout.shipping_method_name = checkout_delivery.name
+ fields_to_update.append("shipping_method_name")
+
+ return fields_to_update
+
+
+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_shipping_method_from_checkout(checkout)
+ if checkout.collection_point_id != collection_point.id:
+ checkout.collection_point_id = collection_point.id
+ fields_to_update.append("collection_point_id")
+ if checkout.shipping_address != collection_point.address:
+ checkout.shipping_address = collection_point.address.get_copy()
+ checkout.save_shipping_address = False
+ fields_to_update.extend(["shipping_address_id", "save_shipping_address"])
+
+ return fields_to_update
+
+
+def remove_shipping_method_from_checkout(checkout: Checkout) -> list[str]:
+ fields_to_update = []
+ if checkout.assigned_delivery_id:
+ checkout.assigned_delivery_id = None
+ fields_to_update.append("assigned_delivery_id")
+ if checkout.shipping_method_name is not None:
+ checkout.shipping_method_name = None
+ fields_to_update.append("shipping_method_name")
+ return fields_to_update
+
+
+def remove_click_and_collect_from_checkout(checkout: Checkout) -> list[str]:
+ fields_to_update = []
+ if checkout.collection_point_id:
+ checkout.collection_point_id = None
+ fields_to_update.append("collection_point_id")
+ if checkout.shipping_address_id:
+ checkout.shipping_address = None
+ # reset the save_shipping_address flag to the default value
+ checkout.save_shipping_address = True
+ fields_to_update.extend(["shipping_address_id", "save_shipping_address"])
+ return fields_to_update
+
+
+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_shipping_method_from_checkout(checkout)
+ fields_to_update += remove_click_and_collect_from_checkout(checkout)
+ return fields_to_update
+
+
+def clear_cc_delivery_method(
+ checkout_info: "CheckoutInfo", save: bool = True
+) -> list[str]:
+ checkout = checkout_info.checkout
+ if checkout.collection_point_id is None:
+ return []
+ updated_fields = remove_click_and_collect_from_checkout(checkout)
+
+ if "collection_point_id" in updated_fields:
+ checkout_info.shipping_address = checkout_info.checkout.shipping_address
+
+ if updated_fields:
+ updated_fields.append("last_change")
+ if save:
+ checkout.safe_update(updated_fields)
+
+ return updated_fields
+
+
+def _get_refreshed_assigned_delivery_data(
+ assigned_delivery: CheckoutDelivery | None,
+ built_in_shipping_methods_dict: dict[int, ShippingMethodData],
+ external_shipping_methods_dict: dict[str, ShippingMethodData],
+) -> ShippingMethodData | None:
+ """Get refreshed shipping method data for assigned delivery.
+
+ Returns the updated ShippingMethodData for the assigned delivery method,
+ or None if the assigned delivery is no longer valid.
+ """
+ if not assigned_delivery:
+ return None
+
+ if external_shipping_method_id := assigned_delivery.external_shipping_method_id:
+ return external_shipping_methods_dict.get(external_shipping_method_id)
+
+ if built_in_shipping_method_id := assigned_delivery.built_in_shipping_method_id:
+ return built_in_shipping_methods_dict.get(built_in_shipping_method_id)
+
+ return None
+
+
+def _refresh_checkout_deliveries(
+ checkout: "Checkout",
+ assigned_delivery: CheckoutDelivery | None,
+ checkout_deliveries: list["CheckoutDelivery"],
+ built_in_shipping_methods_dict: dict[int, ShippingMethodData],
+ external_shipping_methods_dict: dict[str, ShippingMethodData],
+):
+ """Refresh checkout deliveries assigned to the checkout.
+
+ It updates the `CheckoutDelivery` instances associated with the checkout, based
+ on the shipping methods available for the checkout.
+ The non-available shipping methods are removed from the DB, except for the currently
+ assigned delivery method, which is always preserved even if it's no longer valid.
+ """
+ exclude_from_delete = Q(
+ built_in_shipping_method_id__in=list(built_in_shipping_methods_dict.keys())
+ ) | Q(external_shipping_method_id__in=list(external_shipping_methods_dict.keys()))
+
+ if assigned_delivery:
+ # Always preserve the assigned delivery even if it's no longer available
+ exclude_from_delete |= Q(pk=assigned_delivery.pk)
+
+ refreshed_delivery_method = _get_refreshed_assigned_delivery_data(
+ assigned_delivery,
+ built_in_shipping_methods_dict,
+ external_shipping_methods_dict,
+ )
+
+ # Missing refreshed delivery method means that assigned
+ # delivery is no more valid.
+ if not refreshed_delivery_method:
+ assigned_delivery.is_valid = False
+ assigned_delivery.save(update_fields=["is_valid"])
+
+ CheckoutDelivery.objects.filter(
+ checkout_id=checkout.pk,
+ ).exclude(exclude_from_delete).delete()
+
+ if checkout_deliveries:
+ CheckoutDelivery.objects.bulk_create(
+ checkout_deliveries,
+ update_conflicts=True,
+ unique_fields=[
+ "checkout_id",
+ "external_shipping_method_id",
+ "built_in_shipping_method_id",
+ "is_valid",
+ ],
+ update_fields=[
+ "name",
+ "description",
+ "price_amount",
+ "currency",
+ "maximum_delivery_days",
+ "minimum_delivery_days",
+ "metadata",
+ "private_metadata",
+ "active",
+ "message",
+ "updated_at",
+ "is_valid",
+ "is_external",
+ "tax_class_id",
+ "tax_class_name",
+ "tax_class_metadata",
+ "tax_class_private_metadata",
+ ],
+ )
+
+
+def get_available_built_in_shipping_methods_for_checkout_info(
+ checkout_info: "CheckoutInfo",
+) -> list["ShippingMethodData"]:
+ lines = checkout_info.lines
+
+ subtotal = base_calculations.base_checkout_subtotal(
+ lines,
+ checkout_info.channel,
+ checkout_info.checkout.currency,
+ )
+
+ # if a voucher is applied to shipping, we don't want to subtract the discount amount
+ # as some methods based on shipping price may become unavailable,
+ # for example, method on which the discount was applied
+ is_shipping_voucher = (
+ checkout_info.voucher and checkout_info.voucher.type == VoucherType.SHIPPING
+ )
+
+ is_voucher_for_specific_product = (
+ checkout_info.voucher
+ and checkout_info.voucher.type == VoucherType.SPECIFIC_PRODUCT
+ )
+
+ 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_info(
+ checkout_info,
+ subtotal,
+ )
+
+ return valid_shipping_methods
+
+
+def _refreshed_assigned_delivery_has_impact_on_prices(
+ assigned_delivery: CheckoutDelivery | None,
+ built_in_shipping_methods_dict: dict[int, ShippingMethodData],
+ external_shipping_methods_dict: dict[str, ShippingMethodData],
+) -> bool:
+ """Check if refreshed assigned delivery impacts checkout prices.
+
+ If the assigned delivery method has changed in a way that affects pricing,
+ such as a change in tax class, price or marking as invalid, this function
+ returns True. Otherwise, it doesn't impact prices and returns False.
+ """
+ if not assigned_delivery:
+ return False
+
+ refreshed_delivery_method = _get_refreshed_assigned_delivery_data(
+ assigned_delivery,
+ built_in_shipping_methods_dict,
+ external_shipping_methods_dict,
+ )
+
+ if not refreshed_delivery_method:
+ return True
+
+ refreshed_tax_class_id = (
+ refreshed_delivery_method.tax_class.id
+ if refreshed_delivery_method.tax_class
+ else None
+ )
+ # Different tax class can impact on prices
+ if refreshed_tax_class_id != assigned_delivery.tax_class_id:
+ return True
+
+ # Different price means that assigned delivery is invalid
+ if refreshed_delivery_method.price != assigned_delivery.price:
+ return True
+
+ return False
+
+
+@allow_writer()
+def fetch_shipping_methods_for_checkout(
+ checkout_info: "CheckoutInfo",
+) -> list[CheckoutDelivery]:
+ """Fetch shipping methods for the checkout.
+
+ Fetches all available shipping methods, both built-in and external, for the given
+ checkout. Each method is returned as a CheckoutDelivery instance. Existing
+ shipping methods in the database are updated or removed as needed, while the
+ checkout's currently assigned shipping method (`assigned_delivery`) is
+ always preserved, even if it is no longer available.
+ """
+ checkout = checkout_info.checkout
+
+ built_in_shipping_methods_dict: dict[int, ShippingMethodData] = {
+ int(shipping_method.id): shipping_method
+ for shipping_method in get_available_built_in_shipping_methods_for_checkout_info(
+ 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
+ )
+ 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 []
+
+
+def fetch_external_shipping_methods_for_checkout_info(
+ checkout_info,
+ available_built_in_methods: list[ShippingMethodData],
+) -> Promise[list[ShippingMethodData]]:
+ from .webhooks.list_shipping_methods import list_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
+ )
+ return list_shipping_methods_for_checkout(
+ checkout=checkout_info.checkout,
+ built_in_shipping_methods=available_built_in_methods,
+ allow_replica=allow_replica,
+ requestor=requestor,
+ )
+
+
+def get_or_fetch_checkout_deliveries(
+ checkout_info: "CheckoutInfo",
+) -> list[CheckoutDelivery]:
+ """Get or fetch shipping methods for the checkout.
+
+ If the checkout's shipping methods are stale or missing, fetch and update them.
+ Otherwise, return the existing valid shipping methods.
+ """
+ checkout = checkout_info.checkout
+ 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,
+ )
+ )
+
+
+def assign_delivery_method_to_checkout(
+ checkout_info: "CheckoutInfo",
+ lines_info: list["CheckoutLineInfo"],
+ manager: "PluginsManager",
+ delivery_method: CheckoutDelivery | Warehouse | None,
+):
+ fields_to_update = []
+ checkout = checkout_info.checkout
+ with transaction.atomic():
+ if delivery_method is None:
+ fields_to_update = remove_delivery_method_from_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
+
+ from .actions import call_checkout_info_event
+ from .utils import invalidate_checkout
+
+ invalidate_prices_updated_fields = invalidate_checkout(
+ checkout_info, lines_info, manager, save=False
+ )
+ checkout.save(update_fields=fields_to_update + invalidate_prices_updated_fields)
+ call_checkout_info_event(
+ manager,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines_info,
+ )
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 8b0d33fd9c..0c5623c610 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -2,20 +2,15 @@ from collections.abc import Iterable
from dataclasses import dataclass, field
from decimal import Decimal
from functools import cached_property
-from typing import TYPE_CHECKING, Any, Optional, Union
+from typing import TYPE_CHECKING, Optional
from uuid import UUID
from django.conf import settings
-from django.db.models import Q
-from django.utils import timezone
from prices import Money
-from promise import Promise
-from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.pricing.interface import LineInfo
from ..core.taxes import zero_money
-from ..core.tracing import traced_atomic_transaction
from ..discount import VoucherType
from ..discount.interface import (
VariantPromotionRuleInfo,
@@ -25,12 +20,14 @@ from ..discount.interface import (
from ..shipping.interface import ShippingMethodData
from ..shipping.utils import (
convert_checkout_delivery_to_shipping_method_data,
- convert_shipping_method_data_to_checkout_delivery,
- initialize_shipping_method_active_status,
)
-from ..warehouse import WarehouseClickAndCollectOption
from ..warehouse.models import Warehouse
-from .lock_objects import checkout_qs_select_for_update
+from .delivery_context import (
+ CollectionPointInfo,
+ DeliveryMethodBase,
+ ShippingMethodInfo,
+ get_valid_collection_points_for_checkout,
+)
from .models import Checkout, CheckoutDelivery, CheckoutLine
if TYPE_CHECKING:
@@ -136,15 +133,13 @@ class CheckoutInfo:
@cached_property
def valid_pick_up_points(self) -> Iterable["Warehouse"]:
- from .utils import get_valid_collection_points_for_checkout
-
return list(
get_valid_collection_points_for_checkout(
self.lines, self.channel.id, quantity_check=False
)
)
- def get_delivery_method_info(self) -> "DeliveryMethodBase":
+ def get_delivery_method_info(self) -> DeliveryMethodBase:
delivery_method: ShippingMethodData | Warehouse | None = None
if assigned_sm := self.assigned_delivery:
@@ -173,137 +168,6 @@ class CheckoutInfo:
return None
-@dataclass(frozen=True)
-class DeliveryMethodBase:
- delivery_method: Union["ShippingMethodData", "Warehouse"] | None = None
- shipping_address: Optional["Address"] = None
- store_as_customer_address: bool = False
-
- @property
- def warehouse_pk(self) -> UUID | None:
- pass
-
- @property
- def delivery_method_order_field(self) -> dict:
- return {"shipping_method": self.delivery_method}
-
- @property
- def is_local_collection_point(self) -> bool:
- return False
-
- @property
- def delivery_method_name(self) -> dict[str, str | None]:
- return {"shipping_method_name": None}
-
- def get_warehouse_filter_lookup(self) -> dict[str, Any]:
- return {}
-
- def is_valid_delivery_method(self) -> bool:
- return False
-
- def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:
- return False
-
- def is_delivery_method_set(self) -> bool:
- return bool(self.delivery_method)
-
- def get_details_for_conversion_to_order(self) -> dict[str, Any]:
- return {"shipping_method_name": None}
-
-
-@dataclass(frozen=True)
-class ShippingMethodInfo(DeliveryMethodBase):
- delivery_method: "ShippingMethodData"
- shipping_address: Optional["Address"]
- store_as_customer_address: bool = True
-
- @property
- def delivery_method_name(self) -> dict[str, str | None]:
- return {"shipping_method_name": str(self.delivery_method.name)}
-
- @property
- def delivery_method_order_field(self) -> dict:
- if not self.delivery_method.is_external:
- return {"shipping_method_id": int(self.delivery_method.id)}
- return {}
-
- def is_valid_delivery_method(self) -> bool:
- return bool(self.shipping_address)
-
- def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:
- return self.delivery_method.active
-
- def get_details_for_conversion_to_order(self) -> dict[str, str | int | None]:
- details: dict[str, str | int | None] = {
- "shipping_method_name": str(self.delivery_method.name)
- }
- if not self.delivery_method.is_external:
- details["shipping_method_id"] = int(self.delivery_method.id)
-
- if self.delivery_method.tax_class:
- details["shipping_tax_class_id"] = self.delivery_method.tax_class.id
- details["shipping_tax_class_name"] = str(
- self.delivery_method.tax_class.name
- )
- details["shipping_tax_class_private_metadata"] = (
- self.delivery_method.tax_class.private_metadata
- )
- details["shipping_tax_class_metadata"] = (
- self.delivery_method.tax_class.metadata
- )
- return details
-
-
-@dataclass(frozen=True)
-class CollectionPointInfo(DeliveryMethodBase):
- delivery_method: "Warehouse"
- shipping_address: Optional["Address"]
-
- @property
- def warehouse_pk(self):
- return self.delivery_method.pk
-
- @property
- def delivery_method_order_field(self) -> dict:
- return {"collection_point": self.delivery_method}
-
- @property
- def is_local_collection_point(self):
- return (
- self.delivery_method.click_and_collect_option
- == WarehouseClickAndCollectOption.LOCAL_STOCK
- )
-
- @property
- def delivery_method_name(self) -> dict[str, str | None]:
- return {"collection_point_name": str(self.delivery_method)}
-
- def get_warehouse_filter_lookup(self) -> dict[str, Any]:
- return (
- {"warehouse_id": self.delivery_method.pk}
- if self.is_local_collection_point
- else {}
- )
-
- def is_valid_delivery_method(self) -> bool:
- return (
- self.shipping_address is not None
- and self.shipping_address == self.delivery_method.address
- )
-
- def is_method_in_valid_methods(self, checkout_info) -> bool:
- valid_delivery_methods = checkout_info.valid_pick_up_points
- return bool(
- valid_delivery_methods and self.delivery_method in valid_delivery_methods
- )
-
- def get_details_for_conversion_to_order(self) -> dict[str, Any]:
- return {
- "collection_point_name": str(self.delivery_method),
- "collection_point": self.delivery_method,
- }
-
-
def fetch_checkout_lines(
checkout: "Checkout",
prefetch_variant_attributes: bool = False,
@@ -514,66 +378,6 @@ def fetch_checkout_info(
return checkout_info
-def get_available_built_in_shipping_methods_for_checkout_info(
- checkout_info: "CheckoutInfo",
-) -> list["ShippingMethodData"]:
- from . import base_calculations
- from .utils import get_valid_internal_shipping_methods_for_checkout_info
-
- lines = checkout_info.lines
-
- subtotal = base_calculations.base_checkout_subtotal(
- lines,
- checkout_info.channel,
- checkout_info.checkout.currency,
- )
-
- # if a voucher is applied to shipping, we don't want to subtract the discount amount
- # as some methods based on shipping price may become unavailable,
- # for example, method on which the discount was applied
- is_shipping_voucher = (
- checkout_info.voucher and checkout_info.voucher.type == VoucherType.SHIPPING
- )
-
- is_voucher_for_specific_product = (
- checkout_info.voucher
- and checkout_info.voucher.type == VoucherType.SPECIFIC_PRODUCT
- )
-
- 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_info(
- checkout_info,
- subtotal,
- )
-
- return valid_shipping_methods
-
-
-def fetch_external_shipping_methods_for_checkout_info(
- checkout_info,
- available_built_in_methods: list[ShippingMethodData],
-) -> Promise[list[ShippingMethodData]]:
- from .webhooks.list_shipping_methods import list_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
- )
- return list_shipping_methods_for_checkout(
- checkout=checkout_info.checkout,
- built_in_shipping_methods=available_built_in_methods,
- allow_replica=allow_replica,
- requestor=requestor,
- )
-
-
def find_checkout_line_info(
lines: list["CheckoutLineInfo"],
line_id: "UUID",
@@ -583,268 +387,3 @@ def find_checkout_line_info(
The return value represents the updated version of checkout_line_info parameter.
"""
return next(line_info for line_info in lines if line_info.line.pk == line_id)
-
-
-def _get_refreshed_assigned_delivery_data(
- assigned_delivery: CheckoutDelivery | None,
- built_in_shipping_methods_dict: dict[int, ShippingMethodData],
- external_shipping_methods_dict: dict[str, ShippingMethodData],
-) -> ShippingMethodData | None:
- """Get refreshed shipping method data for assigned delivery.
-
- Returns the updated ShippingMethodData for the assigned delivery method,
- or None if the assigned delivery is no longer valid.
- """
- if not assigned_delivery:
- return None
-
- if external_shipping_method_id := assigned_delivery.external_shipping_method_id:
- return external_shipping_methods_dict.get(external_shipping_method_id)
-
- if built_in_shipping_method_id := assigned_delivery.built_in_shipping_method_id:
- return built_in_shipping_methods_dict.get(built_in_shipping_method_id)
-
- return None
-
-
-def _refresh_checkout_deliveries(
- checkout: "Checkout",
- assigned_delivery: CheckoutDelivery | None,
- checkout_deliveries: list["CheckoutDelivery"],
- built_in_shipping_methods_dict: dict[int, ShippingMethodData],
- external_shipping_methods_dict: dict[str, ShippingMethodData],
-):
- """Refresh checkout deliveries assigned to the checkout.
-
- It updates the `CheckoutDelivery` instances associated with the checkout, based
- on the shipping methods available for the checkout.
- The non-available shipping methods are removed from the DB, except for the currently
- assigned delivery method, which is always preserved even if it's no longer valid.
- """
- exclude_from_delete = Q(
- built_in_shipping_method_id__in=list(built_in_shipping_methods_dict.keys())
- ) | Q(external_shipping_method_id__in=list(external_shipping_methods_dict.keys()))
-
- if assigned_delivery:
- # Always preserve the assigned delivery even if it's no longer available
- exclude_from_delete |= Q(pk=assigned_delivery.pk)
-
- refreshed_delivery_method = _get_refreshed_assigned_delivery_data(
- assigned_delivery,
- built_in_shipping_methods_dict,
- external_shipping_methods_dict,
- )
-
- # Missing refreshed delivery method means that assigned
- # delivery is no more valid.
- if not refreshed_delivery_method:
- assigned_delivery.is_valid = False
- assigned_delivery.save(update_fields=["is_valid"])
-
- CheckoutDelivery.objects.filter(
- checkout_id=checkout.pk,
- ).exclude(exclude_from_delete).delete()
-
- if checkout_deliveries:
- CheckoutDelivery.objects.bulk_create(
- checkout_deliveries,
- update_conflicts=True,
- unique_fields=[
- "checkout_id",
- "external_shipping_method_id",
- "built_in_shipping_method_id",
- "is_valid",
- ],
- update_fields=[
- "name",
- "description",
- "price_amount",
- "currency",
- "maximum_delivery_days",
- "minimum_delivery_days",
- "metadata",
- "private_metadata",
- "active",
- "message",
- "updated_at",
- "is_valid",
- "is_external",
- "tax_class_id",
- "tax_class_name",
- "tax_class_metadata",
- "tax_class_private_metadata",
- ],
- )
-
-
-def _refreshed_assigned_delivery_has_impact_on_prices(
- assigned_delivery: CheckoutDelivery | None,
- built_in_shipping_methods_dict: dict[int, ShippingMethodData],
- external_shipping_methods_dict: dict[str, ShippingMethodData],
-) -> bool:
- """Check if refreshed assigned delivery impacts checkout prices.
-
- If the assigned delivery method has changed in a way that affects pricing,
- such as a change in tax class, price or marking as invalid, this function
- returns True. Otherwise, it doesn't impact prices and returns False.
- """
- if not assigned_delivery:
- return False
-
- refreshed_delivery_method = _get_refreshed_assigned_delivery_data(
- assigned_delivery,
- built_in_shipping_methods_dict,
- external_shipping_methods_dict,
- )
-
- if not refreshed_delivery_method:
- return True
-
- refreshed_tax_class_id = (
- refreshed_delivery_method.tax_class.id
- if refreshed_delivery_method.tax_class
- else None
- )
- # Different tax class can impact on prices
- if refreshed_tax_class_id != assigned_delivery.tax_class_id:
- return True
-
- # Different price means that assigned delivery is invalid
- if refreshed_delivery_method.price != assigned_delivery.price:
- return True
-
- return False
-
-
-@allow_writer()
-def fetch_shipping_methods_for_checkout(
- checkout_info: "CheckoutInfo",
-) -> list[CheckoutDelivery]:
- """Fetch shipping methods for the checkout.
-
- Fetches all available shipping methods, both built-in and external, for the given
- checkout. Each method is returned as a CheckoutDelivery instance. Existing
- shipping methods in the database are updated or removed as needed, while the
- checkout's currently assigned shipping method (`assigned_delivery`) is
- always preserved, even if it is no longer available.
- """
- checkout = checkout_info.checkout
-
- built_in_shipping_methods_dict: dict[int, ShippingMethodData] = {
- int(shipping_method.id): shipping_method
- for shipping_method in get_available_built_in_shipping_methods_for_checkout_info(
- 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
- )
- 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 []
-
-
-def get_or_fetch_checkout_deliveries(
- checkout_info: "CheckoutInfo",
-) -> list[CheckoutDelivery]:
- """Get or fetch shipping methods for the checkout.
-
- If the checkout's shipping methods are stale or missing, fetch and update them.
- Otherwise, return the existing valid shipping methods.
- """
- checkout = checkout_info.checkout
- 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,
- )
- )
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 466f126902..634ccc69a6 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -44,7 +44,6 @@ from ..utils import (
cancel_active_payments,
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
- clear_cc_delivery_method,
get_checkout_metadata,
get_voucher_discount_for_checkout,
get_voucher_for_checkout,
@@ -55,54 +54,6 @@ from ..utils import (
)
-def test_is_valid_delivery_method(
- checkout_with_item, address, shipping_zone, checkout_delivery
-):
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save()
- 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.get_delivery_method_info()
- # no shipping method assigned
- assert not delivery_method_info.is_valid_delivery_method()
-
- checkout.assigned_delivery = checkout_delivery(checkout)
- checkout.save()
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.get_delivery_method_info()
-
- assert delivery_method_info.is_valid_delivery_method()
-
- checkout.assigned_delivery.active = False
- checkout.assigned_delivery.save()
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.get_delivery_method_info()
-
- assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
-
-
-def test_clear_cc_delivery_method(
- checkout_with_delivery_method_for_cc,
-):
- # given
- assert checkout_with_delivery_method_for_cc.collection_point_id
-
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(
- checkout_with_delivery_method_for_cc, [], manager
- )
-
- # when
- clear_cc_delivery_method(checkout_info)
-
- # then
- checkout_with_delivery_method_for_cc.refresh_from_db()
- assert not checkout_with_delivery_method_for_cc.collection_point_id
- assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
-
-
def test_last_change_update(checkout):
with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
assert checkout.last_change != datetime.datetime.now(tz=datetime.UTC)
diff --git a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
index 89be016b35..93e66aed73 100644
--- a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
+++ b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
@@ -1,6 +1,6 @@
from decimal import Decimal
-from ..utils import (
+from ..delivery_context import (
assign_collection_point_to_checkout,
assign_shipping_method_to_checkout,
remove_delivery_method_from_checkout,
diff --git a/saleor/checkout/tests/test_delivery_context.py b/saleor/checkout/tests/test_delivery_context.py
new file mode 100644
index 0000000000..59fbdefb22
--- /dev/null
+++ b/saleor/checkout/tests/test_delivery_context.py
@@ -0,0 +1,1005 @@
+from decimal import Decimal
+from unittest import mock
+
+import graphene
+from django.utils import timezone
+from freezegun import freeze_time
+from prices import Money
+from promise import Promise
+
+from ...shipping.interface import ExcludedShippingMethod, ShippingMethodData
+from ...shipping.models import ShippingMethod
+from ...webhook.transport.shipping_helpers import to_shipping_app_id
+from ..delivery_context import (
+ DeliveryMethodBase,
+ assign_delivery_method_to_checkout,
+ clear_cc_delivery_method,
+ fetch_shipping_methods_for_checkout,
+)
+from ..fetch import (
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
+from ..models import CheckoutDelivery
+
+
+def _assert_built_in_shipping_method(
+ checkout_delivery: CheckoutDelivery,
+ available_shipping_method: ShippingMethod,
+ checkout,
+ settings,
+):
+ shipping_listing = available_shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ )
+
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+ assert checkout_delivery.checkout_id == checkout.pk
+ assert checkout_delivery.built_in_shipping_method_id == available_shipping_method.id
+ assert checkout_delivery.name == available_shipping_method.name
+ assert checkout_delivery.price_amount == shipping_listing.price_amount
+ assert checkout_delivery.currency == shipping_listing.price.currency
+ assert str(checkout_delivery.description) == str(
+ available_shipping_method.description
+ )
+ assert (
+ checkout_delivery.minimum_delivery_days
+ == available_shipping_method.minimum_delivery_days
+ )
+ assert (
+ checkout_delivery.maximum_delivery_days
+ == available_shipping_method.maximum_delivery_days
+ )
+ assert checkout_delivery.active is True
+ assert checkout_delivery.is_valid is True
+ assert checkout_delivery.is_external is False
+ assert checkout_delivery.tax_class_id == available_shipping_method.tax_class_id
+ assert checkout_delivery.tax_class_name == available_shipping_method.tax_class.name
+ assert (
+ checkout_delivery.tax_class_metadata
+ == available_shipping_method.tax_class.metadata
+ )
+ assert (
+ checkout_delivery.tax_class_private_metadata
+ == available_shipping_method.tax_class.private_metadata
+ )
+
+ checkout.refresh_from_db()
+ assert (
+ checkout.delivery_methods_stale_at
+ == timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_with_built_in_shipping_method(
+ checkout_with_item, plugins_manager, address, settings
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ CheckoutDelivery.objects.all().delete()
+
+ available_shipping_method = ShippingMethod.objects.get()
+ assert available_shipping_method.tax_class
+
+ available_shipping_method.description = {
+ "time": 1759214012137,
+ "blocks": [
+ {
+ "id": "fQMbdjz2Yt",
+ "data": {"text": "<b>This is Shipping description</b>"},
+ "type": "paragraph",
+ }
+ ],
+ "version": "2.31.0-rc.7",
+ }
+ available_shipping_method.minimum_delivery_days = 5
+ available_shipping_method.maximum_delivery_days = 10
+ available_shipping_method.metadata = {
+ "key": "value",
+ }
+ available_shipping_method.private_metadata = {
+ "private_key": "private_value",
+ }
+ available_shipping_method.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ # Confirm that new shipping method was created
+ assert len(shipping_methods) == 1
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+ assert checkout.shipping_methods.count() == 1
+ # Make sure that shipping method data is aligned with the built-in shipping method
+ _assert_built_in_shipping_method(
+ checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_updates_existing_built_in_shipping_method(
+ checkout_with_item, plugins_manager, address, settings, tax_class_zero_rates
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = (
+ timezone.now() - settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+ checkout.assigned_delivery_id = None
+ checkout.save(
+ update_fields=[
+ "shipping_address",
+ "delivery_methods_stale_at",
+ "assigned_delivery_id",
+ ]
+ )
+
+ available_shipping_method = ShippingMethod.objects.get()
+
+ existing_shipping_method = checkout.shipping_methods.create(
+ built_in_shipping_method_id=available_shipping_method.id,
+ name=available_shipping_method.name,
+ description=available_shipping_method.description,
+ price_amount=Decimal(99),
+ currency="USD",
+ maximum_delivery_days=available_shipping_method.maximum_delivery_days,
+ minimum_delivery_days=available_shipping_method.minimum_delivery_days,
+ metadata=available_shipping_method.metadata,
+ private_metadata=available_shipping_method.private_metadata,
+ active=True,
+ message=None,
+ is_valid=True,
+ is_external=False,
+ )
+
+ available_shipping_method.description = {
+ "time": 1759214012137,
+ "blocks": [
+ {
+ "id": "fQMbdjz2Yt",
+ "data": {"text": "<b>This is Shipping description</b>"},
+ "type": "paragraph",
+ }
+ ],
+ "version": "2.31.0-rc.7",
+ }
+ available_shipping_method.minimum_delivery_days = 5
+ available_shipping_method.maximum_delivery_days = 10
+ available_shipping_method.metadata = {
+ "key": "value",
+ }
+ available_shipping_method.private_metadata = {
+ "private_key": "private_value",
+ }
+ available_shipping_method.tax_class = tax_class_zero_rates
+ available_shipping_method.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ # Confirm that we updated the shipping method instead of creating a new one
+ assert len(shipping_methods) == 1
+ assert CheckoutDelivery.objects.count() == 1
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+ assert existing_shipping_method.id == checkout_delivery.id
+
+ # Make sure that shipping method data has been updated to align with the built-in shipping method
+ _assert_built_in_shipping_method(
+ checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_removes_non_applicable_built_in_shipping_method(
+ checkout_with_item, plugins_manager, address, settings
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = (
+ timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ available_shipping_method = ShippingMethod.objects.get()
+
+ non_applicable_shipping_method_id = available_shipping_method.id + 1
+ checkout.shipping_methods.create(
+ built_in_shipping_method_id=non_applicable_shipping_method_id,
+ name="Nonexisting Shipping Method",
+ price_amount=Decimal(99),
+ currency="USD",
+ )
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert CheckoutDelivery.objects.count() == 1
+ assert len(shipping_methods) == 1
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+
+ # Confirms that the non-applicable shipping method was removed and the
+ # new one was created
+ _assert_built_in_shipping_method(
+ checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_built_in_shipping_method(
+ checkout_with_item, plugins_manager, address, settings
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = (
+ timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ available_shipping_method = ShippingMethod.objects.get()
+
+ non_applicable_shipping_method_id = available_shipping_method.id + 1
+ assigned_delivery = checkout.shipping_methods.create(
+ built_in_shipping_method_id=non_applicable_shipping_method_id,
+ name="Nonexisting Shipping Method",
+ price_amount=Decimal(99),
+ currency="USD",
+ )
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert CheckoutDelivery.objects.count() == 2
+ assert len(shipping_methods) == 1
+
+ new_checkout_delivery = shipping_methods[0]
+ assigned_delivery = CheckoutDelivery.objects.get(is_valid=False)
+
+ # Assigned shipping method is never removed explicitly but marked as invalid
+ assert assigned_delivery.is_valid is False
+ assert (
+ assigned_delivery.built_in_shipping_method_id
+ == assigned_delivery.built_in_shipping_method_id
+ )
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+ # Confirm that new shipping method was created
+ _assert_built_in_shipping_method(
+ new_checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_excluded_built_in_shipping_method(
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ settings,
+):
+ # given
+ unavailable_shipping_method = ShippingMethod.objects.get()
+ exclude_reason = "This shipping method is not available."
+ mocked_exclude_shipping_methods.return_value = Promise.resolve(
+ [
+ ExcludedShippingMethod(
+ id=str(unavailable_shipping_method.id),
+ reason=exclude_reason,
+ )
+ ]
+ )
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert len(shipping_methods) == 1
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+ assert checkout.shipping_methods.count() == 1
+ assert checkout_delivery.active is False
+ assert checkout_delivery.message == exclude_reason
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_with_changed_price_of_built_in_shipping_method(
+ checkout_with_item, plugins_manager, address, settings
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ CheckoutDelivery.objects.all().delete()
+
+ available_shipping_method = ShippingMethod.objects.get()
+ shipping_channel_listing = available_shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ )
+ previous_shipping_price = shipping_channel_listing.price_amount
+
+ assigned_delivery = checkout.shipping_methods.create(
+ built_in_shipping_method_id=available_shipping_method.id,
+ name="Nonexisting Shipping Method",
+ price_amount=previous_shipping_price,
+ currency="USD",
+ )
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ # Change the price of the shipping method in channel listing
+ new_shipping_price_amount = previous_shipping_price + Decimal(10)
+ shipping_channel_listing.price_amount = new_shipping_price_amount
+ shipping_channel_listing.save(update_fields=["price_amount"])
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ checkout.refresh_from_db()
+ assigned_delivery.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+ # Changing the price of shipping method assigned to checkout
+ # caused that after fetching shipping methods, the checkout
+ # prices are marked as expired.
+ assert checkout.price_expiration == timezone.now()
+
+ # The assigned shipping method has updated price
+ assert assigned_delivery.price_amount == new_shipping_price_amount
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_fetch_shipping_methods_for_checkout_with_changed_tax_class_of_built_in_shipping_method(
+ checkout_with_item, plugins_manager, address, settings, tax_class_zero_rates
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ CheckoutDelivery.objects.all().delete()
+
+ available_shipping_method = ShippingMethod.objects.get()
+ shipping_channel_listing = available_shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ )
+ previous_shipping_price = shipping_channel_listing.price_amount
+
+ assigned_delivery = checkout.shipping_methods.create(
+ built_in_shipping_method_id=available_shipping_method.id,
+ name="Nonexisting Shipping Method",
+ price_amount=previous_shipping_price,
+ currency="USD",
+ tax_class_id=available_shipping_method.tax_class_id,
+ )
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ assert available_shipping_method.tax_class != tax_class_zero_rates
+ available_shipping_method.tax_class = tax_class_zero_rates
+ available_shipping_method.save()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+ # Changing the tax class of shipping method assigned to checkout
+ # caused that after fetching shipping methods, the checkout
+ # prices are marked as expired.
+ assert checkout.price_expiration == timezone.now()
+
+
+def _assert_external_shipping_method(
+ checkout_delivery: CheckoutDelivery,
+ available_shipping_method: ShippingMethodData,
+ checkout,
+ settings,
+):
+ assert checkout_delivery.checkout_id == checkout.pk
+ assert checkout_delivery.external_shipping_method_id == available_shipping_method.id
+ assert checkout_delivery.name == available_shipping_method.name
+ assert checkout_delivery.price_amount == available_shipping_method.price.amount
+ assert checkout_delivery.currency == available_shipping_method.price.currency
+ assert checkout_delivery.description == str(available_shipping_method.description)
+ assert (
+ checkout_delivery.minimum_delivery_days
+ == available_shipping_method.minimum_delivery_days
+ )
+ assert (
+ checkout_delivery.maximum_delivery_days
+ == available_shipping_method.maximum_delivery_days
+ )
+ assert checkout_delivery.active == available_shipping_method.active
+ assert checkout_delivery.is_valid is True
+ assert checkout_delivery.is_external is True
+ checkout.refresh_from_db()
+ assert (
+ checkout.delivery_methods_stale_at
+ == timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_external_shipping_method(
+ mocked_webhook,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ app,
+ settings,
+):
+ # given
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(Decimal(10), checkout_with_item.currency),
+ active=False,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_webhook.return_value = Promise.resolve([available_shipping_method])
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ ShippingMethod.objects.all().delete()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ # Confirms that new shipping method was created
+ assert len(shipping_methods) == 1
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+
+ # Make sure that shipping method data is aligned with the external shipping method
+ _assert_external_shipping_method(
+ checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_updates_existing_external_shipping_method(
+ mocked_webhook,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ app,
+ settings,
+):
+ # given
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(Decimal(10), checkout_with_item.currency),
+ active=False,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_webhook.return_value = Promise.resolve([available_shipping_method])
+
+ checkout = checkout_with_item
+ checkout.shipping_methods.create(
+ external_shipping_method_id=to_shipping_app_id(
+ app, "external-shipping-method-id"
+ ),
+ name="Old External Shipping name",
+ price_amount=Decimal(99),
+ currency="USD",
+ )
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ ShippingMethod.objects.all().delete()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert len(shipping_methods) == 1
+
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+ # Make sure that shipping method data has been updated to align with the
+ # external shipping method
+ _assert_external_shipping_method(
+ checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_removes_non_applicable_external_shipping_method(
+ mocked_webhook,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ app,
+ external_app,
+ settings,
+):
+ # given
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(Decimal(10), checkout_with_item.currency),
+ active=False,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_webhook.return_value = Promise.resolve([available_shipping_method])
+
+ checkout = checkout_with_item
+ checkout.shipping_methods.create(
+ external_shipping_method_id=to_shipping_app_id(
+ external_app, "expired-shipping-method-id"
+ ),
+ name="Old External Shipping name",
+ price_amount=Decimal(99),
+ currency="USD",
+ )
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
+
+ ShippingMethod.objects.all().delete()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert len(shipping_methods) == 1
+
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+ # Confirms that the non-applicable shipping method was removed and the
+ # new one was created
+ _assert_external_shipping_method(
+ checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_external_shipping_method(
+ mocked_webhook,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ app,
+ external_app,
+ settings,
+):
+ # given
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(Decimal(10), checkout_with_item.currency),
+ active=False,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_webhook.return_value = Promise.resolve([available_shipping_method])
+
+ checkout = checkout_with_item
+ expired_app_id = to_shipping_app_id(external_app, "expired-shipping-method-id")
+ assigned_delivery = checkout.shipping_methods.create(
+ external_shipping_method_id=expired_app_id,
+ name="Old External Shipping name",
+ price_amount=Decimal(99),
+ currency="USD",
+ is_external=True,
+ )
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.assigned_delivery = assigned_delivery
+ checkout.save()
+
+ ShippingMethod.objects.all().delete()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert CheckoutDelivery.objects.count() == 2
+ assert len(shipping_methods) == 1
+
+ new_checkout_delivery = shipping_methods[0]
+ assigned_delivery = CheckoutDelivery.objects.get(is_valid=False)
+
+ checkout.refresh_from_db()
+ # Assigned shipping method is never removed explicitly but marked as invalid
+ assert assigned_delivery.is_valid is False
+ assert assigned_delivery.external_shipping_method_id == expired_app_id
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+
+ # Confirm that new shipping method was created
+ _assert_external_shipping_method(
+ new_checkout_delivery, available_shipping_method, checkout, settings
+ )
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
+)
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_excluded_external_shipping_method(
+ mocked_list_shipping_methods,
+ mocked_exclude_shipping_methods,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ app,
+ settings,
+):
+ # given
+ unavailable_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(Decimal(10), checkout_with_item.currency),
+ active=False,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+ exclude_reason = "This shipping method is not available."
+ mocked_exclude_shipping_methods.return_value = Promise.resolve(
+ [
+ ExcludedShippingMethod(
+ id=str(unavailable_shipping_method.id),
+ reason=exclude_reason,
+ )
+ ]
+ )
+
+ mocked_list_shipping_methods.return_value = Promise.resolve(
+ [unavailable_shipping_method]
+ )
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ ShippingMethod.objects.all().delete()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ assert len(shipping_methods) == 1
+ checkout_delivery = shipping_methods[0]
+ assert isinstance(checkout_delivery, CheckoutDelivery)
+
+ assert checkout_delivery.active is False
+ assert checkout_delivery.message == exclude_reason
+
+
+@freeze_time("2024-05-31 12:00:01")
+ "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
+)
+def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_shipping_method(
+ mocked_webhook,
+ checkout_with_item,
+ plugins_manager,
+ address,
+ app,
+ settings,
+):
+ # given
+ shipping_price_amount = Decimal(10)
+ shipping_price_amount = Decimal(10)
+
+ available_shipping_method = ShippingMethodData(
+ id=to_shipping_app_id(app, "external-shipping-method-id"),
+ price=Money(shipping_price_amount, checkout_with_item.currency),
+ active=False,
+ name="External Shipping",
+ description="External Shipping Description",
+ maximum_delivery_days=10,
+ minimum_delivery_days=5,
+ metadata={
+ "key": "value",
+ },
+ )
+
+ mocked_webhook.return_value = Promise.resolve([available_shipping_method])
+
+ new_shipping_price_amount = shipping_price_amount + Decimal(99)
+ checkout = checkout_with_item
+ assigned_delivery = checkout.shipping_methods.create(
+ external_shipping_method_id=to_shipping_app_id(
+ app, "external-shipping-method-id"
+ ),
+ name="External Shipping name",
+ price_amount=new_shipping_price_amount,
+ currency="USD",
+ )
+ checkout.assigned_delivery = assigned_delivery
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save()
+
+ ShippingMethod.objects.all().delete()
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines=lines_info, manager=plugins_manager
+ )
+
+ # when
+ fetch_shipping_methods_for_checkout(checkout_info)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ # Changing the price of shipping method assigned to checkout
+ # caused that after fetching shipping methods, the checkout
+ # prices are marked as expired.
+ assert checkout.price_expiration == timezone.now()
+
+ # The assigned shipping method has updated price
+ assert assigned_delivery.price_amount == new_shipping_price_amount
+
+
+def test_assign_delivery_method_to_checkout_delivery_method_to_none(
+ checkout_with_delivery_method_for_cc, plugins_manager
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+
+ # when
+ assign_delivery_method_to_checkout(checkout_info, lines_info, plugins_manager, None)
+
+ # then
+ assert checkout_with_delivery_method_for_cc.collection_point_id is None
+ assert checkout_with_delivery_method_for_cc.shipping_address_id is None
+ assert checkout_info.collection_point is None
+
+
+def test_assign_delivery_method_to_checkout_delivery_method_to_external(
+ checkout_with_shipping_method, shipping_app, plugins_manager
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{app_shipping_id}"
+ )
+
+ shipping_method = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=method_id,
+ name=app_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
+
+ # when
+ assign_delivery_method_to_checkout(
+ checkout_info, lines_info, plugins_manager, shipping_method
+ )
+
+ # then
+ assert checkout.shipping_method_name == app_shipping_name
+ assert checkout.assigned_delivery.shipping_method_id == method_id
+ assert checkout.assigned_delivery.name == app_shipping_name
+ assert checkout_info.collection_point is None
+
+
+def test_assign_delivery_method_to_checkout_delivery_method_to_cc(
+ checkout,
+ shipping_method_weight_based,
+ warehouses_for_cc,
+ checkout_delivery,
+ plugins_manager,
+):
+ # given
+ checkout.assigned_delivery = checkout_delivery(
+ checkout, shipping_method_weight_based
+ )
+ checkout.shipping_method_name = shipping_method_weight_based.name
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+
+ collection_point = warehouses_for_cc[0]
+
+ # when
+ assign_delivery_method_to_checkout(
+ checkout_info, lines_info, plugins_manager, collection_point
+ )
+
+ # then
+ assert checkout.collection_point == collection_point
+ assert checkout.shipping_address == collection_point.address
+ assert int(checkout.shipping_address_id) != int(collection_point.address.id)
+ assert checkout.assigned_delivery is None
+ assert checkout.shipping_method_name is None
+
+
+def test_clear_cc_delivery_method(
+ checkout_with_delivery_method_for_cc, plugins_manager
+):
+ # given
+ assert checkout_with_delivery_method_for_cc.collection_point_id
+
+ checkout_info = fetch_checkout_info(
+ checkout_with_delivery_method_for_cc, [], plugins_manager
+ )
+
+ # when
+ clear_cc_delivery_method(checkout_info)
+
+ # then
+ checkout_with_delivery_method_for_cc.refresh_from_db()
+ assert not checkout_with_delivery_method_for_cc.collection_point_id
+ assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
+
+
+def test_is_valid_delivery_method(
+ checkout_with_item, address, shipping_zone, checkout_delivery, plugins_manager
+):
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save()
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ delivery_method_info = checkout_info.get_delivery_method_info()
+ # no shipping method assigned
+ assert not delivery_method_info.is_valid_delivery_method()
+
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save()
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ delivery_method_info = checkout_info.get_delivery_method_info()
+
+ assert delivery_method_info.is_valid_delivery_method()
+
+ checkout.assigned_delivery.active = False
+ checkout.assigned_delivery.save()
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ delivery_method_info = checkout_info.get_delivery_method_info()
+
+ assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
diff --git a/saleor/checkout/tests/test_fetch.py b/saleor/checkout/tests/test_fetch.py
index 650f7fbd0a..552a7e2ee9 100644
--- a/saleor/checkout/tests/test_fetch.py
+++ b/saleor/checkout/tests/test_fetch.py
@@ -1,23 +1,13 @@
from decimal import Decimal
-from unittest import mock
import pytest
-from django.utils import timezone
-from freezegun import freeze_time
from prices import Money
-from promise import Promise
from ...product.models import ProductChannelListing, ProductVariantChannelListing
-from ...shipping.interface import ExcludedShippingMethod, ShippingMethodData
-from ...shipping.models import ShippingMethod
-from ...webhook.transport.shipping_helpers import to_shipping_app_id
from ..fetch import (
CheckoutLineInfo,
- fetch_checkout_info,
fetch_checkout_lines,
- fetch_shipping_methods_for_checkout,
)
-from ..models import CheckoutDelivery
def test_checkout_line_info_undiscounted_unit_price(checkout_with_item_on_promotion):
@@ -367,846 +357,3 @@ def test_fetch_checkout_lines_info_when_variant_channel_listing_without_price(
line = lines[0]
assert line_info.line.pk == line.pk
assert unavailable_variants == [line.variant_id]
-
-
-def _assert_built_in_shipping_method(
- checkout_delivery: CheckoutDelivery,
- available_shipping_method: ShippingMethod,
- checkout,
- settings,
-):
- shipping_listing = available_shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- )
-
- assert isinstance(checkout_delivery, CheckoutDelivery)
- assert checkout_delivery.checkout_id == checkout.pk
- assert checkout_delivery.built_in_shipping_method_id == available_shipping_method.id
- assert checkout_delivery.name == available_shipping_method.name
- assert checkout_delivery.price_amount == shipping_listing.price_amount
- assert checkout_delivery.currency == shipping_listing.price.currency
- assert str(checkout_delivery.description) == str(
- available_shipping_method.description
- )
- assert (
- checkout_delivery.minimum_delivery_days
- == available_shipping_method.minimum_delivery_days
- )
- assert (
- checkout_delivery.maximum_delivery_days
- == available_shipping_method.maximum_delivery_days
- )
- assert checkout_delivery.active is True
- assert checkout_delivery.is_valid is True
- assert checkout_delivery.is_external is False
- assert checkout_delivery.tax_class_id == available_shipping_method.tax_class_id
- assert checkout_delivery.tax_class_name == available_shipping_method.tax_class.name
- assert (
- checkout_delivery.tax_class_metadata
- == available_shipping_method.tax_class.metadata
- )
- assert (
- checkout_delivery.tax_class_private_metadata
- == available_shipping_method.tax_class.private_metadata
- )
-
- checkout.refresh_from_db()
- assert (
- checkout.delivery_methods_stale_at
- == timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
-def test_fetch_shipping_methods_for_checkout_with_built_in_shipping_method(
- checkout_with_item, plugins_manager, address, settings
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- CheckoutDelivery.objects.all().delete()
-
- available_shipping_method = ShippingMethod.objects.get()
- assert available_shipping_method.tax_class
-
- available_shipping_method.description = {
- "time": 1759214012137,
- "blocks": [
- {
- "id": "fQMbdjz2Yt",
- "data": {"text": "<b>This is Shipping description</b>"},
- "type": "paragraph",
- }
- ],
- "version": "2.31.0-rc.7",
- }
- available_shipping_method.minimum_delivery_days = 5
- available_shipping_method.maximum_delivery_days = 10
- available_shipping_method.metadata = {
- "key": "value",
- }
- available_shipping_method.private_metadata = {
- "private_key": "private_value",
- }
- available_shipping_method.save()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- # Confirm that new shipping method was created
- assert len(shipping_methods) == 1
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
- assert checkout.shipping_methods.count() == 1
- # Make sure that shipping method data is aligned with the built-in shipping method
- _assert_built_in_shipping_method(
- checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
-def test_fetch_shipping_methods_for_checkout_updates_existing_built_in_shipping_method(
- checkout_with_item, plugins_manager, address, settings, tax_class_zero_rates
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = (
- timezone.now() - settings.CHECKOUT_DELIVERY_OPTIONS_TTL
- )
- checkout.assigned_delivery_id = None
- checkout.save(
- update_fields=[
- "shipping_address",
- "delivery_methods_stale_at",
- "assigned_delivery_id",
- ]
- )
-
- available_shipping_method = ShippingMethod.objects.get()
-
- existing_shipping_method = checkout.shipping_methods.create(
- built_in_shipping_method_id=available_shipping_method.id,
- name=available_shipping_method.name,
- description=available_shipping_method.description,
- price_amount=Decimal(99),
- currency="USD",
- maximum_delivery_days=available_shipping_method.maximum_delivery_days,
- minimum_delivery_days=available_shipping_method.minimum_delivery_days,
- metadata=available_shipping_method.metadata,
- private_metadata=available_shipping_method.private_metadata,
- active=True,
- message=None,
- is_valid=True,
- is_external=False,
- )
-
- available_shipping_method.description = {
- "time": 1759214012137,
- "blocks": [
- {
- "id": "fQMbdjz2Yt",
- "data": {"text": "<b>This is Shipping description</b>"},
- "type": "paragraph",
- }
- ],
- "version": "2.31.0-rc.7",
- }
- available_shipping_method.minimum_delivery_days = 5
- available_shipping_method.maximum_delivery_days = 10
- available_shipping_method.metadata = {
- "key": "value",
- }
- available_shipping_method.private_metadata = {
- "private_key": "private_value",
- }
- available_shipping_method.tax_class = tax_class_zero_rates
- available_shipping_method.save()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- # Confirm that we updated the shipping method instead of creating a new one
- assert len(shipping_methods) == 1
- assert CheckoutDelivery.objects.count() == 1
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
- assert existing_shipping_method.id == checkout_delivery.id
-
- # Make sure that shipping method data has been updated to align with the built-in shipping method
- _assert_built_in_shipping_method(
- checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
-def test_fetch_shipping_methods_for_checkout_removes_non_applicable_built_in_shipping_method(
- checkout_with_item, plugins_manager, address, settings
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = (
- timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
- )
- checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
-
- available_shipping_method = ShippingMethod.objects.get()
-
- non_applicable_shipping_method_id = available_shipping_method.id + 1
- checkout.shipping_methods.create(
- built_in_shipping_method_id=non_applicable_shipping_method_id,
- name="Nonexisting Shipping Method",
- price_amount=Decimal(99),
- currency="USD",
- )
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert CheckoutDelivery.objects.count() == 1
- assert len(shipping_methods) == 1
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
-
- # Confirms that the non-applicable shipping method was removed and the
- # new one was created
- _assert_built_in_shipping_method(
- checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
-def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_built_in_shipping_method(
- checkout_with_item, plugins_manager, address, settings
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = (
- timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
- )
- checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
-
- available_shipping_method = ShippingMethod.objects.get()
-
- non_applicable_shipping_method_id = available_shipping_method.id + 1
- assigned_delivery = checkout.shipping_methods.create(
- built_in_shipping_method_id=non_applicable_shipping_method_id,
- name="Nonexisting Shipping Method",
- price_amount=Decimal(99),
- currency="USD",
- )
- checkout.assigned_delivery = assigned_delivery
- checkout.save()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert CheckoutDelivery.objects.count() == 2
- assert len(shipping_methods) == 1
-
- new_checkout_delivery = shipping_methods[0]
- assigned_delivery = CheckoutDelivery.objects.get(is_valid=False)
-
- # Assigned shipping method is never removed explicitly but marked as invalid
- assert assigned_delivery.is_valid is False
- assert (
- assigned_delivery.built_in_shipping_method_id
- == assigned_delivery.built_in_shipping_method_id
- )
- assert checkout.assigned_delivery_id == assigned_delivery.id
-
- # Confirm that new shipping method was created
- _assert_built_in_shipping_method(
- new_checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_with_excluded_built_in_shipping_method(
- mocked_exclude_shipping_methods,
- checkout_with_item,
- plugins_manager,
- address,
- settings,
-):
- # given
- unavailable_shipping_method = ShippingMethod.objects.get()
- exclude_reason = "This shipping method is not available."
- mocked_exclude_shipping_methods.return_value = Promise.resolve(
- [
- ExcludedShippingMethod(
- id=str(unavailable_shipping_method.id),
- reason=exclude_reason,
- )
- ]
- )
-
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert len(shipping_methods) == 1
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
- assert checkout.shipping_methods.count() == 1
- assert checkout_delivery.active is False
- assert checkout_delivery.message == exclude_reason
-
-
-@freeze_time("2024-05-31 12:00:01")
-def test_fetch_shipping_methods_for_checkout_with_changed_price_of_built_in_shipping_method(
- checkout_with_item, plugins_manager, address, settings
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- CheckoutDelivery.objects.all().delete()
-
- available_shipping_method = ShippingMethod.objects.get()
- shipping_channel_listing = available_shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- )
- previous_shipping_price = shipping_channel_listing.price_amount
-
- assigned_delivery = checkout.shipping_methods.create(
- built_in_shipping_method_id=available_shipping_method.id,
- name="Nonexisting Shipping Method",
- price_amount=previous_shipping_price,
- currency="USD",
- )
- checkout.assigned_delivery = assigned_delivery
- checkout.save()
-
- # Change the price of the shipping method in channel listing
- new_shipping_price_amount = previous_shipping_price + Decimal(10)
- shipping_channel_listing.price_amount = new_shipping_price_amount
- shipping_channel_listing.save(update_fields=["price_amount"])
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- checkout.refresh_from_db()
- assigned_delivery.refresh_from_db()
- assert checkout.assigned_delivery_id == assigned_delivery.id
-
- # Changing the price of shipping method assigned to checkout
- # caused that after fetching shipping methods, the checkout
- # prices are marked as expired.
- assert checkout.price_expiration == timezone.now()
-
- # The assigned shipping method has updated price
- assert assigned_delivery.price_amount == new_shipping_price_amount
-
-
-@freeze_time("2024-05-31 12:00:01")
-def test_fetch_shipping_methods_for_checkout_with_changed_tax_class_of_built_in_shipping_method(
- checkout_with_item, plugins_manager, address, settings, tax_class_zero_rates
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- CheckoutDelivery.objects.all().delete()
-
- available_shipping_method = ShippingMethod.objects.get()
- shipping_channel_listing = available_shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- )
- previous_shipping_price = shipping_channel_listing.price_amount
-
- assigned_delivery = checkout.shipping_methods.create(
- built_in_shipping_method_id=available_shipping_method.id,
- name="Nonexisting Shipping Method",
- price_amount=previous_shipping_price,
- currency="USD",
- tax_class_id=available_shipping_method.tax_class_id,
- )
- checkout.assigned_delivery = assigned_delivery
- checkout.save()
-
- assert available_shipping_method.tax_class != tax_class_zero_rates
- available_shipping_method.tax_class = tax_class_zero_rates
- available_shipping_method.save()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- checkout.refresh_from_db()
- assert checkout.assigned_delivery_id == assigned_delivery.id
-
- # Changing the tax class of shipping method assigned to checkout
- # caused that after fetching shipping methods, the checkout
- # prices are marked as expired.
- assert checkout.price_expiration == timezone.now()
-
-
-def _assert_external_shipping_method(
- checkout_delivery: CheckoutDelivery,
- available_shipping_method: ShippingMethodData,
- checkout,
- settings,
-):
- assert checkout_delivery.checkout_id == checkout.pk
- assert checkout_delivery.external_shipping_method_id == available_shipping_method.id
- assert checkout_delivery.name == available_shipping_method.name
- assert checkout_delivery.price_amount == available_shipping_method.price.amount
- assert checkout_delivery.currency == available_shipping_method.price.currency
- assert checkout_delivery.description == str(available_shipping_method.description)
- assert (
- checkout_delivery.minimum_delivery_days
- == available_shipping_method.minimum_delivery_days
- )
- assert (
- checkout_delivery.maximum_delivery_days
- == available_shipping_method.maximum_delivery_days
- )
- assert checkout_delivery.active == available_shipping_method.active
- assert checkout_delivery.is_valid is True
- assert checkout_delivery.is_external is True
- checkout.refresh_from_db()
- assert (
- checkout.delivery_methods_stale_at
- == timezone.now() + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_with_external_shipping_method(
- mocked_webhook,
- checkout_with_item,
- plugins_manager,
- address,
- app,
- settings,
-):
- # given
- available_shipping_method = ShippingMethodData(
- id=to_shipping_app_id(app, "external-shipping-method-id"),
- price=Money(Decimal(10), checkout_with_item.currency),
- active=False,
- name="External Shipping",
- description="External Shipping Description",
- maximum_delivery_days=10,
- minimum_delivery_days=5,
- metadata={
- "key": "value",
- },
- )
-
- mocked_webhook.return_value = Promise.resolve([available_shipping_method])
-
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- ShippingMethod.objects.all().delete()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- # Confirms that new shipping method was created
- assert len(shipping_methods) == 1
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
-
- # Make sure that shipping method data is aligned with the external shipping method
- _assert_external_shipping_method(
- checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_updates_existing_external_shipping_method(
- mocked_webhook,
- checkout_with_item,
- plugins_manager,
- address,
- app,
- settings,
-):
- # given
- available_shipping_method = ShippingMethodData(
- id=to_shipping_app_id(app, "external-shipping-method-id"),
- price=Money(Decimal(10), checkout_with_item.currency),
- active=False,
- name="External Shipping",
- description="External Shipping Description",
- maximum_delivery_days=10,
- minimum_delivery_days=5,
- metadata={
- "key": "value",
- },
- )
-
- mocked_webhook.return_value = Promise.resolve([available_shipping_method])
-
- checkout = checkout_with_item
- checkout.shipping_methods.create(
- external_shipping_method_id=to_shipping_app_id(
- app, "external-shipping-method-id"
- ),
- name="Old External Shipping name",
- price_amount=Decimal(99),
- currency="USD",
- )
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = timezone.now()
- checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
-
- ShippingMethod.objects.all().delete()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert len(shipping_methods) == 1
-
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
- # Make sure that shipping method data has been updated to align with the
- # external shipping method
- _assert_external_shipping_method(
- checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_removes_non_applicable_external_shipping_method(
- mocked_webhook,
- checkout_with_item,
- plugins_manager,
- address,
- app,
- external_app,
- settings,
-):
- # given
- available_shipping_method = ShippingMethodData(
- id=to_shipping_app_id(app, "external-shipping-method-id"),
- price=Money(Decimal(10), checkout_with_item.currency),
- active=False,
- name="External Shipping",
- description="External Shipping Description",
- maximum_delivery_days=10,
- minimum_delivery_days=5,
- metadata={
- "key": "value",
- },
- )
-
- mocked_webhook.return_value = Promise.resolve([available_shipping_method])
-
- checkout = checkout_with_item
- checkout.shipping_methods.create(
- external_shipping_method_id=to_shipping_app_id(
- external_app, "expired-shipping-method-id"
- ),
- name="Old External Shipping name",
- price_amount=Decimal(99),
- currency="USD",
- )
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = timezone.now()
- checkout.save(update_fields=["shipping_address", "delivery_methods_stale_at"])
-
- ShippingMethod.objects.all().delete()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert len(shipping_methods) == 1
-
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
- # Confirms that the non-applicable shipping method was removed and the
- # new one was created
- _assert_external_shipping_method(
- checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_non_applicable_assigned_external_shipping_method(
- mocked_webhook,
- checkout_with_item,
- plugins_manager,
- address,
- app,
- external_app,
- settings,
-):
- # given
- available_shipping_method = ShippingMethodData(
- id=to_shipping_app_id(app, "external-shipping-method-id"),
- price=Money(Decimal(10), checkout_with_item.currency),
- active=False,
- name="External Shipping",
- description="External Shipping Description",
- maximum_delivery_days=10,
- minimum_delivery_days=5,
- metadata={
- "key": "value",
- },
- )
-
- mocked_webhook.return_value = Promise.resolve([available_shipping_method])
-
- checkout = checkout_with_item
- expired_app_id = to_shipping_app_id(external_app, "expired-shipping-method-id")
- assigned_delivery = checkout.shipping_methods.create(
- external_shipping_method_id=expired_app_id,
- name="Old External Shipping name",
- price_amount=Decimal(99),
- currency="USD",
- is_external=True,
- )
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = timezone.now()
- checkout.assigned_delivery = assigned_delivery
- checkout.save()
-
- ShippingMethod.objects.all().delete()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert CheckoutDelivery.objects.count() == 2
- assert len(shipping_methods) == 1
-
- new_checkout_delivery = shipping_methods[0]
- assigned_delivery = CheckoutDelivery.objects.get(is_valid=False)
-
- checkout.refresh_from_db()
- # Assigned shipping method is never removed explicitly but marked as invalid
- assert assigned_delivery.is_valid is False
- assert assigned_delivery.external_shipping_method_id == expired_app_id
- assert checkout.assigned_delivery_id == assigned_delivery.id
-
- # Confirm that new shipping method was created
- _assert_external_shipping_method(
- new_checkout_delivery, available_shipping_method, checkout, settings
- )
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.exclude_shipping.excluded_shipping_methods_for_checkout"
-)
- "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_with_excluded_external_shipping_method(
- mocked_list_shipping_methods,
- mocked_exclude_shipping_methods,
- checkout_with_item,
- plugins_manager,
- address,
- app,
- settings,
-):
- # given
- unavailable_shipping_method = ShippingMethodData(
- id=to_shipping_app_id(app, "external-shipping-method-id"),
- price=Money(Decimal(10), checkout_with_item.currency),
- active=False,
- name="External Shipping",
- description="External Shipping Description",
- maximum_delivery_days=10,
- minimum_delivery_days=5,
- metadata={
- "key": "value",
- },
- )
- exclude_reason = "This shipping method is not available."
- mocked_exclude_shipping_methods.return_value = Promise.resolve(
- [
- ExcludedShippingMethod(
- id=str(unavailable_shipping_method.id),
- reason=exclude_reason,
- )
- ]
- )
-
- mocked_list_shipping_methods.return_value = Promise.resolve(
- [unavailable_shipping_method]
- )
-
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- ShippingMethod.objects.all().delete()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- assert len(shipping_methods) == 1
- checkout_delivery = shipping_methods[0]
- assert isinstance(checkout_delivery, CheckoutDelivery)
-
- assert checkout_delivery.active is False
- assert checkout_delivery.message == exclude_reason
-
-
-@freeze_time("2024-05-31 12:00:01")
- "saleor.checkout.webhooks.list_shipping_methods.list_shipping_methods_for_checkout"
-)
-def test_fetch_shipping_methods_for_checkout_with_changed_price_of_external_shipping_method(
- mocked_webhook,
- checkout_with_item,
- plugins_manager,
- address,
- app,
- settings,
-):
- # given
- shipping_price_amount = Decimal(10)
- shipping_price_amount = Decimal(10)
-
- available_shipping_method = ShippingMethodData(
- id=to_shipping_app_id(app, "external-shipping-method-id"),
- price=Money(shipping_price_amount, checkout_with_item.currency),
- active=False,
- name="External Shipping",
- description="External Shipping Description",
- maximum_delivery_days=10,
- minimum_delivery_days=5,
- metadata={
- "key": "value",
- },
- )
-
- mocked_webhook.return_value = Promise.resolve([available_shipping_method])
-
- new_shipping_price_amount = shipping_price_amount + Decimal(99)
- checkout = checkout_with_item
- assigned_delivery = checkout.shipping_methods.create(
- external_shipping_method_id=to_shipping_app_id(
- app, "external-shipping-method-id"
- ),
- name="External Shipping name",
- price_amount=new_shipping_price_amount,
- currency="USD",
- )
- checkout.assigned_delivery = assigned_delivery
- checkout.shipping_address = address
- checkout.delivery_methods_stale_at = timezone.now()
- checkout.save()
-
- ShippingMethod.objects.all().delete()
-
- lines_info, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines=lines_info, manager=plugins_manager
- )
-
- # when
- fetch_shipping_methods_for_checkout(checkout_info)
-
- # then
- checkout.refresh_from_db()
- assert checkout.assigned_delivery_id == assigned_delivery.id
- # Changing the price of shipping method assigned to checkout
- # caused that after fetching shipping methods, the checkout
- # prices are marked as expired.
- assert checkout.price_expiration == timezone.now()
-
- # The assigned shipping method has updated price
- assert assigned_delivery.price_amount == new_shipping_price_amount
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index fcea057ce9..7647689b64 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -20,7 +20,6 @@ from ..core.exceptions import (
NonExistingCheckoutLines,
ProductNotPublished,
)
-from ..core.prices import quantize_price
from ..core.taxes import zero_taxed_money
from ..core.utils.metadata_manager import (
MetadataItemCollection,
@@ -56,19 +55,16 @@ from ..giftcard.utils import (
from ..payment.models import Payment
from ..plugins.manager import PluginsManager
from ..product import models as product_models
-from ..shipping.interface import ShippingMethodData
-from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
-from ..shipping.utils import convert_to_shipping_method_data
from ..warehouse.availability import check_stock_and_preorder_quantity
-from ..warehouse.models import Warehouse
from ..warehouse.reservations import reserve_stocks_and_preorders
from . import AddressType, base_calculations, calculations
+from .delivery_context import is_shipping_required
from .error_codes import CheckoutErrorCode
from .lock_objects import (
checkout_lines_qs_select_for_update,
checkout_qs_select_for_update,
)
-from .models import Checkout, CheckoutDelivery, CheckoutLine, CheckoutMetadata
+from .models import Checkout, CheckoutLine, CheckoutMetadata
if TYPE_CHECKING:
from measurement.measures import Weight
@@ -78,8 +74,6 @@ if TYPE_CHECKING:
from ..order.models import OrderLine
from .fetch import CheckoutInfo, CheckoutLineInfo
-PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"
-
def invalidate_checkout(
checkout_info: "CheckoutInfo",
@@ -970,101 +964,6 @@ def remove_voucher_from_checkout(checkout: Checkout):
)
-def get_valid_internal_shipping_methods_for_checkout_info(
- checkout_info: "CheckoutInfo",
- subtotal: "Money",
-) -> list[ShippingMethodData]:
- 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(
- 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=checkout_info.lines,
- )
-
- shipping_channel_listings = ShippingMethodChannelListing.objects.using(
- checkout_info.database_connection_name
- ).filter(
- channel_id=checkout_info.channel.id,
- shipping_method_id__in=[method.pk for method in shipping_methods],
- )
-
- channel_listings_map = {
- listing.shipping_method_id: listing for listing in shipping_channel_listings
- }
-
- internal_methods: list[ShippingMethodData] = []
- for method in shipping_methods:
- listing = channel_listings_map.get(method.pk)
- if listing:
- shipping_method_data = convert_to_shipping_method_data(method, listing)
- internal_methods.append(shipping_method_data)
-
- return internal_methods
-
-
-def get_valid_collection_points_for_checkout(
- lines: list["CheckoutLineInfo"],
- channel_id: int,
- quantity_check: bool = True,
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- """Return a collection of `Warehouse`s that can be used as a collection point.
-
- Note that `quantity_check=False` should be used, when stocks quantity will
- be validated in further steps (checkout completion) in order to raise
- 'InsufficientProductStock' error instead of 'InvalidShippingError'.
- """
- if not is_shipping_required(lines):
- return []
-
- line_ids = [line_info.line.id for line_info in lines]
- lines = CheckoutLine.objects.using(database_connection_name).filter(id__in=line_ids)
-
- return (
- Warehouse.objects.using(
- database_connection_name
- ).applicable_for_click_and_collect(lines, channel_id)
- if quantity_check
- else Warehouse.objects.using(
- database_connection_name
- ).applicable_for_click_and_collect_no_quantity_check(lines, channel_id)
- )
-
-
-def clear_cc_delivery_method(
- checkout_info: "CheckoutInfo", save: bool = True
-) -> list[str]:
- checkout = checkout_info.checkout
- if checkout.collection_point_id is None:
- return []
- updated_fields = remove_click_and_collect_from_checkout(checkout)
-
- if "collection_point_id" in updated_fields:
- checkout_info.shipping_address = checkout_info.checkout.shipping_address
-
- if updated_fields:
- updated_fields.append("last_change")
- if save:
- checkout.safe_update(updated_fields)
-
- return updated_fields
-
-
def is_fully_paid(
manager: PluginsManager,
checkout_info: "CheckoutInfo",
@@ -1103,115 +1002,6 @@ def activate_payments(payment_ids: list[int]) -> None:
Payment.objects.filter(id__in=payment_ids).update(is_active=True)
-def is_shipping_required(lines: list["CheckoutLineInfo"]):
- """Check if shipping is required for given checkout lines."""
- return any(line_info.product_type.is_shipping_required for line_info in lines)
-
-
-def _remove_external_shipping_from_metadata(checkout: Checkout):
- metadata = get_checkout_metadata(checkout)
- if not metadata:
- return
-
- field_deleted = metadata.delete_value_from_private_metadata(
- PRIVATE_META_APP_SHIPPING_ID
- )
- if field_deleted:
- 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_shipping_method_from_checkout(checkout: Checkout) -> list[str]:
- fields_to_update = []
- if checkout.assigned_delivery_id:
- checkout.assigned_delivery_id = None
- fields_to_update.append("assigned_delivery_id")
- if checkout.shipping_method_name is not None:
- checkout.shipping_method_name = None
- fields_to_update.append("shipping_method_name")
- return fields_to_update
-
-
-def remove_click_and_collect_from_checkout(checkout: Checkout) -> list[str]:
- fields_to_update = []
- if checkout.collection_point_id:
- checkout.collection_point_id = None
- fields_to_update.append("collection_point_id")
- if checkout.shipping_address_id:
- checkout.shipping_address = None
- # reset the save_shipping_address flag to the default value
- checkout.save_shipping_address = True
- fields_to_update.extend(["shipping_address_id", "save_shipping_address"])
- return fields_to_update
-
-
-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_shipping_method_from_checkout(checkout)
- fields_to_update += remove_click_and_collect_from_checkout(checkout)
- return fields_to_update
-
-
-def _assign_undiscounted_base_shipping_price_to_checkout(
- checkout, checkout_delivery: CheckoutDelivery
-):
- current_shipping_price = quantize_price(
- checkout.undiscounted_base_shipping_price, checkout.currency
- )
- new_shipping_price = quantize_price(checkout_delivery.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_shipping_method_to_checkout(
- checkout: Checkout, checkout_delivery: CheckoutDelivery
-) -> list[str]:
- fields_to_update = []
- fields_to_update += remove_click_and_collect_from_checkout(checkout)
- fields_to_update += _assign_undiscounted_base_shipping_price_to_checkout(
- checkout, checkout_delivery
- )
- if checkout.assigned_delivery_id != checkout_delivery.id:
- checkout.assigned_delivery = checkout_delivery
- fields_to_update.append("assigned_delivery_id")
-
- # make sure that we don't have obsolete data for shipping methods stored in
- # private metadata
- _remove_external_shipping_from_metadata(checkout=checkout)
-
- if checkout.shipping_method_name != checkout_delivery.name:
- checkout.shipping_method_name = checkout_delivery.name
- fields_to_update.append("shipping_method_name")
-
- return fields_to_update
-
-
-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_shipping_method_from_checkout(checkout)
- if checkout.collection_point_id != collection_point.id:
- checkout.collection_point_id = collection_point.id
- fields_to_update.append("collection_point_id")
- if checkout.shipping_address != collection_point.address:
- checkout.shipping_address = collection_point.address.get_copy()
- checkout.save_shipping_address = False
- fields_to_update.extend(["shipping_address_id", "save_shipping_address"])
-
- return fields_to_update
-
-
@allow_writer()
def create_checkout_metadata(
checkout: "Checkout",
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 0f570a5373..348f80d8d2 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -7,15 +7,17 @@ from ....checkout.checkout_cleaner import (
validate_checkout_email,
)
from ....checkout.complete_checkout import complete_checkout
+from ....checkout.delivery_context import (
+ get_or_fetch_checkout_deliveries,
+ is_shipping_required,
+)
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
CheckoutInfo,
CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
- get_or_fetch_checkout_deliveries,
)
-from ....checkout.utils import is_shipping_required
from ....order import models as order_models
from ....permission.enums import AccountPermissions
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index eacad8c6ad..098c99944f 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -3,16 +3,19 @@ from typing import TYPE_CHECKING
import graphene
from django.core.exceptions import ValidationError
+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 (
CheckoutInfo,
CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
- get_or_fetch_checkout_deliveries,
)
from ....checkout.models import CheckoutDelivery
-from ....checkout.utils import is_shipping_required
from ....warehouse import models as warehouse_models
from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -28,7 +31,6 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Checkout
from .utils import (
ERROR_DOES_NOT_SHIP,
- assign_delivery_method_to_checkout,
get_checkout,
)
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index 68001c38d0..28f57a6cbf 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -1,12 +1,15 @@
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.delivery_context import (
+ assign_delivery_method_to_checkout,
+ get_or_fetch_checkout_deliveries,
+)
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
CheckoutInfo,
fetch_checkout_info,
fetch_checkout_lines,
- get_or_fetch_checkout_deliveries,
)
from ....checkout.models import CheckoutDelivery
from ....checkout.utils import (
@@ -26,7 +29,6 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Checkout
from .utils import (
ERROR_DOES_NOT_SHIP,
- assign_delivery_method_to_checkout,
get_checkout,
)
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index fe6152e585..259691793d 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -3,14 +3,16 @@ from django.core.exceptions import ValidationError
from ....checkout.checkout_cleaner import validate_checkout
from ....checkout.complete_checkout import create_order_from_checkout
+from ....checkout.delivery_context import (
+ get_or_fetch_checkout_deliveries,
+ is_shipping_required,
+)
from ....checkout.fetch import (
CheckoutInfo,
CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
- get_or_fetch_checkout_deliveries,
)
-from ....checkout.utils import is_shipping_required
from ....core.exceptions import GiftCardNotApplicable, InsufficientStock
from ....core.taxes import TaxDataError
from ....discount.models import NotApplicable
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index d4364b2fbc..df56c3a6d2 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -15,16 +15,9 @@ from django.utils import timezone
from prices import Money
from ....checkout import models
-from ....checkout.actions import call_checkout_info_event
+from ....checkout.delivery_context import is_shipping_required
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
-from ....checkout.utils import (
- assign_collection_point_to_checkout,
- assign_shipping_method_to_checkout,
- invalidate_checkout,
- is_shipping_required,
- remove_delivery_method_from_checkout,
-)
+from ....checkout.fetch import CheckoutLineInfo
from ....core.exceptions import InsufficientStock, PermissionDenied
from ....discount import DiscountType, DiscountValueType
from ....discount.interface import DiscountInfo
@@ -37,15 +30,12 @@ from ....discount.utils.promotion import (
from ....permission.enums import CheckoutPermissions
from ....product import models as product_models
from ....product.models import ProductChannelListing, ProductVariant
-from ....warehouse import models as warehouse_models
from ....warehouse.availability import check_stock_and_preorder_quantity_bulk
-from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.validators import validate_one_of_args_is_in_mutation
from ..types import Checkout
if TYPE_CHECKING:
- from ....plugins.manager import PluginsManager
from ...core.mutations import BaseMutation
@@ -552,47 +542,3 @@ def _set_checkout_base_subtotal_and_total_on_checkout_creation(
# delivery method during checkout creation
checkout.base_total = checkout.base_subtotal
checkout.save(update_fields=["base_subtotal_amount", "base_total_amount"])
-
-
-def assign_delivery_method_to_checkout(
- checkout_info: CheckoutInfo,
- lines_info: list[CheckoutLineInfo],
- manager: "PluginsManager",
- delivery_method: models.CheckoutDelivery | warehouse_models.Warehouse | None,
-):
- fields_to_update = []
- checkout = checkout_info.checkout
- with transaction.atomic():
- if delivery_method is None:
- fields_to_update = remove_delivery_method_from_checkout(
- checkout=checkout_info.checkout
- )
- checkout_info.collection_point = None
- checkout_info.assigned_delivery = None
-
- elif isinstance(delivery_method, models.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_models.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
-
- invalidate_prices_updated_fields = invalidate_checkout(
- checkout_info, lines_info, manager, save=False
- )
- checkout.save(update_fields=fields_to_update + invalidate_prices_updated_fields)
- call_checkout_info_event(
- manager,
- event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
- checkout_info=checkout_info,
- lines=lines_info,
- )
diff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
index 61da03a420..3bfaff3aa7 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
@@ -4,8 +4,8 @@ from unittest.mock import patch
import pytest
from django.utils import timezone
+from .....checkout.delivery_context import assign_shipping_method_to_checkout
from .....checkout.models import CheckoutDelivery
-from .....checkout.utils import assign_shipping_method_to_checkout
from .....webhook.transport.shipping_helpers import to_shipping_app_id
from ....tests.utils import get_graphql_content
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 802507682d..07ec9cd71c 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
@@ -12,15 +12,17 @@ from django.utils import timezone
from .....account.models import Address
from .....checkout import calculations
+from .....checkout.delivery_context import (
+ PRIVATE_META_APP_SHIPPING_ID,
+ fetch_shipping_methods_for_checkout,
+ get_or_fetch_checkout_deliveries,
+)
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
- fetch_shipping_methods_for_checkout,
- get_or_fetch_checkout_deliveries,
)
from .....checkout.models import Checkout, CheckoutDelivery, CheckoutLine
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
from .....core.exceptions import InsufficientStock, InsufficientStockData
from .....core.taxes import TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
@@ -6288,7 +6290,7 @@ def test_complete_refreshes_shipping_methods_when_stale(
@patch(
- "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ "saleor.checkout.delivery_context.fetch_shipping_methods_for_checkout",
wraps=fetch_shipping_methods_for_checkout,
)
def test_complete_do_not_refresh_shipping_methods_when_not_stale(
@@ -6335,7 +6337,7 @@ def test_complete_do_not_refresh_shipping_methods_when_not_stale(
@patch(
- "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ "saleor.checkout.delivery_context.fetch_shipping_methods_for_checkout",
wraps=fetch_shipping_methods_for_checkout,
)
def test_complete_do_not_refresh_shipping_methods_when_cc_is_used(
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 de6d3772b7..effe0c2607 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
@@ -13,16 +13,19 @@ from prices import TaxedMoney
from .....account.models import Address
from .....channel import MarkAsPaidStrategy
from .....checkout import calculations
+from .....checkout.delivery_context import (
+ PRIVATE_META_APP_SHIPPING_ID,
+ fetch_shipping_methods_for_checkout,
+ get_or_fetch_checkout_deliveries,
+)
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
- fetch_shipping_methods_for_checkout,
- get_or_fetch_checkout_deliveries,
)
from .....checkout.models import Checkout, CheckoutDelivery, CheckoutLine
from .....checkout.payment_utils import update_checkout_payment_statuses
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, add_voucher_to_checkout
+from .....checkout.utils import add_voucher_to_checkout
from .....core.taxes import TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
from .....discount.models import (
@@ -5849,7 +5852,7 @@ def test_checkout_complete_race_condition_on_preparing_checkout(
@patch(
- "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ "saleor.checkout.delivery_context.fetch_shipping_methods_for_checkout",
wraps=fetch_shipping_methods_for_checkout,
)
def test_complete_do_not_refresh_shipping_methods_when_not_stale(
@@ -5897,7 +5900,7 @@ def test_complete_do_not_refresh_shipping_methods_when_not_stale(
@patch(
- "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ "saleor.checkout.delivery_context.fetch_shipping_methods_for_checkout",
wraps=fetch_shipping_methods_for_checkout,
)
def test_complete_do_not_refresh_shipping_methods_when_cc_is_used(
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 0ec89f1ab0..66fb90acf9 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
@@ -75,7 +75,7 @@ MUTATION_UPDATE_DELIVERY_METHOD = """
indirect=("delivery_method",),
)
@patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_not_applicable_delivery_method(
@@ -125,7 +125,7 @@ def test_checkout_delivery_method_update_not_applicable_delivery_method(
indirect=("delivery_method",),
)
@patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update(
@@ -219,7 +219,7 @@ def test_checkout_delivery_method_update_when_line_without_channel_listing(
indirect=("delivery_method",),
)
@patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_missing_checkout_metadata_when_not_applicable_method(
@@ -270,7 +270,7 @@ def test_checkout_delivery_method_update_missing_checkout_metadata_when_not_appl
indirect=("delivery_method",),
)
@patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_checkout_without_metadata(
@@ -901,7 +901,7 @@ MUTATION_UPDATE_DELIVERY_METHOD_WITH_ONLY_ID = """
@patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -997,7 +997,7 @@ def test_checkout_delivery_method_update_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1081,7 +1081,7 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1191,11 +1191,11 @@ def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1261,11 +1261,11 @@ def test_checkout_delivery_method_update_from_cc_to_external_shipping(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_cc_to_none(
@@ -1306,11 +1306,11 @@ def test_checkout_delivery_method_update_from_cc_to_none(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_cc_to_built_in_shipping(
@@ -1358,11 +1358,11 @@ def test_checkout_delivery_method_update_from_cc_to_built_in_shipping(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_cc_to_the_same_cc(
@@ -1412,11 +1412,11 @@ def test_checkout_delivery_method_update_from_cc_to_the_same_cc(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_cc_to_different_cc(
@@ -1474,11 +1474,11 @@ def test_checkout_delivery_method_update_from_cc_to_different_cc(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_external_shipping_to_cc(
@@ -1538,11 +1538,11 @@ def test_checkout_delivery_method_update_from_external_shipping_to_cc(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_external_shipping_to_built_in_shipping(
@@ -1584,17 +1584,19 @@ def test_checkout_delivery_method_update_from_external_shipping_to_built_in_ship
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
- mocked_invalidate_checkout.assert_called_once()
+ # mark as invalid when assigned_delivery is not available
+ # mark as invalid when new assigned_delivery is assigned
+ assert mocked_invalidate_checkout.call_count == 2
mocked_call_checkout_info_event.assert_called_once()
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_external_shipping_to_different_external(
@@ -1652,16 +1654,18 @@ def test_checkout_delivery_method_update_from_external_shipping_to_different_ext
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
- mocked_invalidate_checkout.assert_called_once()
+ # mark as invalid when assigned_delivery is not available
+ # mark as invalid when new assigned_delivery is assigned
+ assert mocked_invalidate_checkout.call_count == 2
mocked_call_checkout_info_event.assert_called_once()
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_external_shipping_to_none(
@@ -1702,12 +1706,12 @@ def test_checkout_delivery_method_update_from_external_shipping_to_none(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_external_shipping_to_the_same_external(
@@ -1784,11 +1788,11 @@ def test_checkout_delivery_method_update_from_external_shipping_to_the_same_exte
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_built_in_shipping_to_cc(
@@ -1847,12 +1851,12 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_cc(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_built_in_shipping_to_external_shipping(
@@ -1916,11 +1920,11 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_external_ship
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_built_in_shipping_to_differnt_built_in(
@@ -1968,11 +1972,11 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_differnt_buil
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_built_in_shipping_to_the_same_shipping(
@@ -2024,11 +2028,11 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_the_same_ship
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_from_built_in_shipping_to_none(
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 fba58cb922..ca42ee3193 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
@@ -12,14 +12,17 @@ from promise import Promise
from .....account.models import Address
from .....checkout.actions import call_checkout_info_event
from .....checkout.calculations import fetch_checkout_data
+from .....checkout.delivery_context import (
+ PRIVATE_META_APP_SHIPPING_ID,
+ get_or_fetch_checkout_deliveries,
+)
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
- get_or_fetch_checkout_deliveries,
)
from .....checkout.models import CheckoutDelivery
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout
+from .....checkout.utils import invalidate_checkout
from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....shipping import models as shipping_models
@@ -64,7 +67,7 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
wraps=get_or_fetch_checkout_deliveries,
)
@patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update(
@@ -111,7 +114,7 @@ def test_checkout_shipping_method_update(
wraps=get_or_fetch_checkout_deliveries,
)
@patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_not_valid_shipping_method(
@@ -589,7 +592,7 @@ MUTATION_UPDATE_SHIPPING_METHOD_WITH_ONLY_ID = """
@patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -687,7 +690,7 @@ def test_checkout_shipping_method_update_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -768,12 +771,12 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_external_shipping_to_different_external(
@@ -826,17 +829,19 @@ def test_checkout_shipping_method_update_from_external_shipping_to_different_ext
assert checkout.assigned_delivery.shipping_method_id == method_id
assert checkout.shipping_method_name == response_shipping_name
- mocked_invalidate_checkout.assert_called_once()
+ # mark as invalid when assigned_delivery is not available
+ # mark as invalid when new assigned_delivery is assigned
+ assert mocked_invalidate_checkout.call_count == 2
mocked_call_checkout_info_event.assert_called_once()
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_external_shipping_to_the_same_external(
@@ -911,11 +916,11 @@ def test_checkout_shipping_method_update_from_external_shipping_to_the_same_exte
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_external_shipping_to_built_in_method(
@@ -952,16 +957,18 @@ def test_checkout_shipping_method_update_from_external_shipping_to_built_in_meth
assert checkout.collection_point_id is None
assert checkout.shipping_method_name == shipping_method.name
- mocked_invalidate_checkout.assert_called_once()
+ # mark as invalid when assigned_delivery is not available
+ # mark as invalid when new assigned_delivery is assigned
+ assert mocked_invalidate_checkout.call_count == 2
mocked_call_checkout_info_event.assert_called_once()
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_external_shipping_to_none(
@@ -996,11 +1003,11 @@ def test_checkout_shipping_method_update_from_external_shipping_to_none(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_built_in_shipping_to_different_built_in(
@@ -1043,12 +1050,12 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_different_bui
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_built_in_shipping_to_external(
@@ -1106,11 +1113,11 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_external(
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_built_in_shipping_to_the_same_built_in(
@@ -1157,11 +1164,11 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_the_same_buil
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ "saleor.checkout.actions.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_from_built_in_shipping_to_none(
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 95f7153fb6..f0125a9691 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
@@ -13,16 +13,18 @@ from prices import Money, TaxedMoney
from .....channel import MarkAsPaidStrategy
from .....checkout import calculations
+from .....checkout.delivery_context import (
+ PRIVATE_META_APP_SHIPPING_ID,
+ fetch_shipping_methods_for_checkout,
+ get_or_fetch_checkout_deliveries,
+)
from .....checkout.error_codes import OrderCreateFromCheckoutErrorCode
from .....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
- fetch_shipping_methods_for_checkout,
- get_or_fetch_checkout_deliveries,
)
from .....checkout.models import Checkout, CheckoutDelivery, CheckoutLine
from .....checkout.payment_utils import update_checkout_payment_statuses
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
from .....core.taxes import TaxDataError, TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
from .....discount.models import CheckoutLineDiscount, OrderLineDiscount
@@ -2921,7 +2923,7 @@ def test_order_from_checkout_refreshes_shipping_methods_when_stale(
@freeze_time("2023-01-01 12:00:00")
@patch(
- "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ "saleor.checkout.delivery_context.fetch_shipping_methods_for_checkout",
wraps=fetch_shipping_methods_for_checkout,
)
def test_order_from_checkout_do_not_refresh_shipping_methods_when_not_stale(
diff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.py
index 0cae4c412f..24ee36efad 100644
--- a/saleor/graphql/checkout/tests/mutations/test_utils.py
+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py
@@ -1,11 +1,8 @@
import graphene
-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.models import CheckoutDelivery
-from .....plugins.manager import get_plugins_manager
+from .....checkout.fetch import fetch_checkout_lines
from ...mutations.utils import (
CheckoutLineData,
- assign_delivery_method_to_checkout,
group_lines_input_data_on_update,
group_lines_input_on_add,
)
@@ -182,94 +179,3 @@ def test_group_on_update_when_one_line_and_mixed_parameters_provided(
assert expected == group_lines_input_data_on_update(
lines_data, existing_checkout_lines
)
-
-
-def test_assign_delivery_method_to_checkout_delivery_method_to_none(
- checkout_with_delivery_method_for_cc,
-):
- # given
- checkout = checkout_with_delivery_method_for_cc
-
- lines_info, _ = fetch_checkout_lines(checkout)
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- # when
- assign_delivery_method_to_checkout(checkout_info, lines_info, manager, None)
-
- # then
- assert checkout_with_delivery_method_for_cc.collection_point_id is None
- assert checkout_with_delivery_method_for_cc.shipping_address_id is None
- assert checkout_info.collection_point is None
-
-
-def test_assign_delivery_method_to_checkout_delivery_method_to_external(
- checkout_with_shipping_method, shipping_app
-):
- # given
- checkout = checkout_with_shipping_method
-
- lines_info, _ = fetch_checkout_lines(checkout)
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- app_shipping_id = "abcd"
- app_shipping_name = "Shipping"
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{app_shipping_id}"
- )
-
- shipping_method = CheckoutDelivery.objects.create(
- checkout=checkout,
- external_shipping_method_id=method_id,
- name=app_shipping_name,
- price_amount="10.00",
- currency="USD",
- maximum_delivery_days=7,
- is_external=True,
- )
-
- # when
- assign_delivery_method_to_checkout(
- checkout_info, lines_info, manager, shipping_method
- )
-
- # then
- assert checkout.shipping_method_name == app_shipping_name
- assert checkout.assigned_delivery.shipping_method_id == method_id
- assert checkout.assigned_delivery.name == app_shipping_name
- assert checkout_info.collection_point is None
-
-
-def test_assign_delivery_method_to_checkout_delivery_method_to_cc(
- checkout, shipping_method_weight_based, warehouses_for_cc, checkout_delivery
-):
- # given
- checkout.assigned_delivery = checkout_delivery(
- checkout, shipping_method_weight_based
- )
- checkout.shipping_method_name = shipping_method_weight_based.name
-
- lines_info, _ = fetch_checkout_lines(checkout)
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- collection_point = warehouses_for_cc[0]
-
- # when
- assign_delivery_method_to_checkout(
- checkout_info, lines_info, manager, collection_point
- )
-
- # then
- assert checkout.collection_point == collection_point
- assert checkout.shipping_address == collection_point.address
- assert int(checkout.shipping_address_id) != int(collection_point.address.id)
- assert checkout.assigned_delivery is None
- assert checkout.shipping_method_name is None
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 95c0bd387a..db1519b611 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -26,11 +26,11 @@ from ....checkout.checkout_cleaner import (
clean_checkout_payment,
clean_checkout_shipping,
)
+from ....checkout.delivery_context import PRIVATE_META_APP_SHIPPING_ID
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.models import Checkout
from ....checkout.utils import (
- PRIVATE_META_APP_SHIPPING_ID,
add_variant_to_checkout,
add_voucher_to_checkout,
)
diff --git a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
index 1781ec844e..dd845cf9e5 100644
--- a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
+++ b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
@@ -292,7 +292,7 @@ mutation updateCheckoutShippingOptions($token: UUID!, $shippingMethodId: ID) {
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_invalidate_prices(
@@ -335,7 +335,7 @@ mutation updateCheckoutDeliveryOptions($token: UUID!, $deliveryMethodId: ID!) {
@mock.patch(
- "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ "saleor.checkout.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_invalidate_prices(
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 9172cd38e5..e805d5a9a6 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -9,8 +9,10 @@ from promise import Promise
from ...account.models import User
from ...checkout import calculations, models, problems
from ...checkout.calculations import fetch_checkout_data
-from ...checkout.fetch import fetch_shipping_methods_for_checkout
-from ...checkout.utils import get_valid_collection_points_for_checkout
+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
from ...core.prices import quantize_price
from ...core.taxes import zero_money, zero_taxed_money
diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.py
index 422eeb6e9c..6c327b52e7 100644
--- a/saleor/graphql/order/tests/queries/test_order.py
+++ b/saleor/graphql/order/tests/queries/test_order.py
@@ -4,7 +4,7 @@ import graphene
import pytest
from prices import Money, TaxedMoney
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
+from .....checkout.delivery_context import PRIVATE_META_APP_SHIPPING_ID
from .....core.prices import quantize_price
from .....core.taxes import zero_taxed_money
from .....discount import DiscountType