Skip to content

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

Introduce CheckoutDelivery to store checkout's shipping methods (#18432)

Maciej Korycinski66b8f9b708dd
diff --git a/saleor/app/tests/fixtures/webhooks/shipping_app.py b/saleor/app/tests/fixtures/webhooks/shipping_app.py
index 535f57532c..942c1c443e 100644
--- a/saleor/app/tests/fixtures/webhooks/shipping_app.py
+++ b/saleor/app/tests/fixtures/webhooks/shipping_app.py
@@ -93,7 +93,10 @@ def exclude_shipping_app_with_subscription(db, permission_manage_checkouts):
subscription {
event {
... on CheckoutFilterShippingMethods {
- __typename
+ __typename
+ shippingMethods {
+ id
+ }
}
}
}
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 448f35a0ac..d03e50c47b 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -19,6 +19,7 @@ from .fetch import (
CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
+ get_or_fetch_checkout_deliveries,
)
from .models import Checkout
from .payment_utils import (
@@ -89,8 +90,7 @@ def _trigger_checkout_sync_webhooks(
webhook_event_map: dict[str, set["Webhook"]],
address: Optional["Address"] = None,
):
- _ = checkout_info.get_all_shipping_methods()
-
+ get_or_fetch_checkout_deliveries(checkout_info)
# + timedelta(seconds=10) to confirm that triggered webhooks will still have
# valid prices. Triggered only when we have active sync tax webhook.
if webhook_event_map.get(
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index 0ffd86055b..e37b57b3ef 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -15,7 +15,7 @@ from ..plugins.manager import PluginsManager
from . import models
from .error_codes import CheckoutErrorCode, OrderCreateFromCheckoutErrorCode
from .models import Checkout
-from .utils import clear_delivery_method, is_fully_paid, is_shipping_required
+from .utils import clear_cc_delivery_method, is_fully_paid, is_shipping_required
if TYPE_CHECKING:
from .fetch import CheckoutInfo, CheckoutLineInfo
@@ -52,7 +52,8 @@ def clean_checkout_shipping(
}
)
if not delivery_method_info.is_method_in_valid_methods(checkout_info):
- clear_delivery_method(checkout_info)
+ if checkout_info.checkout.collection_point_id:
+ clear_cc_delivery_method(checkout_info)
raise ValidationError(
{
"shipping_method": ValidationError(
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 56450ee606..8ba36292b4 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -59,7 +59,6 @@ from ..product.models import ProductTranslation, ProductVariantTranslation
from ..shipping.interface import ShippingMethodData
from ..tax.calculations import get_taxed_undiscounted_price
from ..tax.utils import (
- get_shipping_tax_class_kwargs_for_order,
get_tax_class_kwargs_for_order_line,
)
from ..warehouse.availability import check_stock_and_preorder_quantity_bulk
@@ -213,7 +212,16 @@ def _process_shipping_data_for_order(
shipping_address = shipping_address.get_copy()
shipping_method = delivery_method_info.delivery_method
- tax_class = getattr(shipping_method, "tax_class", None)
+ is_external = getattr(shipping_method, "is_external", False)
+ if is_external and shipping_method:
+ # It is temporary solution for setting up the external shipping method
+ # for order. Order doesn't have any field for storing the external shipping
+ # method.
+ checkout_metadata = get_or_create_checkout_metadata(checkout_info.checkout)
+ checkout_metadata.store_value_in_private_metadata(
+ {PRIVATE_META_APP_SHIPPING_ID: shipping_method.id}
+ )
+ checkout_metadata.save()
result: dict[str, Any] = {
"undiscounted_base_shipping_price": undiscounted_base_shipping_price,
@@ -221,10 +229,8 @@ def _process_shipping_data_for_order(
"base_shipping_price": base_shipping_price,
"shipping_price": shipping_price,
"weight": calculate_checkout_weight(lines),
- **get_shipping_tax_class_kwargs_for_order(tax_class),
+ **delivery_method_info.get_details_for_conversion_to_order(),
}
- result.update(delivery_method_info.delivery_method_order_field)
- result.update(delivery_method_info.delivery_method_name)
if isinstance(shipping_method, ShippingMethodData):
result.update(
@@ -873,15 +879,6 @@ def _create_order(
{data.key: data.value for data in private_metadata_list}
)
- if checkout_info.checkout.external_shipping_method_id:
- # Add external shipping method to metadata, as order still uses private
- # metadata for external shipping id.
- order.store_value_in_private_metadata(
- {
- PRIVATE_META_APP_SHIPPING_ID: checkout_info.checkout.external_shipping_method_id
- }
- )
-
update_order_charge_data(order, with_save=False)
update_order_authorize_data(order, with_save=False)
order.search_vector = FlatConcatSearchVector(
@@ -1450,15 +1447,14 @@ def _create_order_from_checkout(
{data.key: data.value for data in private_metadata_list}
)
- if checkout_info.checkout.external_shipping_method_id:
- # Add external shipping method to metadata, as order still uses private
- # metadata for external shipping id. The metadata will be transfered to the
- # order.
- checkout_metadata.store_value_in_private_metadata(
- {
- PRIVATE_META_APP_SHIPPING_ID: checkout_info.checkout.external_shipping_method_id
- }
- )
+ shipping_details = _process_shipping_data_for_order(
+ checkout_info,
+ undiscounted_base_shipping_price,
+ base_shipping_price,
+ shipping_total,
+ manager,
+ checkout_lines_info,
+ )
# order
order = Order.objects.create( # type: ignore[misc] # see below:
@@ -1478,14 +1474,7 @@ def _create_order_from_checkout(
tax_exemption=checkout_info.checkout.tax_exemption,
tax_error=checkout_info.checkout.tax_error,
lines_count=len(checkout_lines_info),
- **_process_shipping_data_for_order(
- checkout_info,
- undiscounted_base_shipping_price,
- base_shipping_price,
- shipping_total,
- manager,
- checkout_lines_info,
- ),
+ **shipping_details,
**_process_user_data_for_order(checkout_info, manager),
)
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 7b830e972d..59a80ead75 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -1,18 +1,20 @@
-import itertools
from collections.abc import Iterable
from dataclasses import dataclass, field
from decimal import Decimal
-from functools import cached_property, singledispatch
+from functools import cached_property
from typing import TYPE_CHECKING, Any, Optional, Union
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 ..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,
@@ -20,19 +22,19 @@ from ..discount.interface import (
fetch_voucher_info,
)
from ..shipping.interface import ShippingMethodData
-from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
from ..shipping.utils import (
- convert_to_shipping_method_data,
+ 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 ..webhook.transport.shipping_helpers import convert_to_app_id_with_identifier
+from .lock_objects import checkout_qs_select_for_update
+from .models import Checkout, CheckoutDelivery, CheckoutLine
if TYPE_CHECKING:
from ..account.models import Address, User
from ..channel.models import Channel
- from ..checkout.models import CheckoutLine
from ..discount.models import (
CheckoutDiscount,
CheckoutLineDiscount,
@@ -48,7 +50,6 @@ if TYPE_CHECKING:
ProductVariantChannelListing,
)
from ..tax.models import TaxClass, TaxConfiguration
- from .models import Checkout
@dataclass
@@ -124,8 +125,7 @@ class CheckoutInfo:
tax_configuration: "TaxConfiguration"
discounts: list["CheckoutDiscount"]
lines: list[CheckoutLineInfo]
- shipping_channel_listings: list["ShippingMethodChannelListing"]
- shipping_method: Optional["ShippingMethod"] = None
+ assigned_delivery: CheckoutDelivery | None = None
collection_point: Optional["Warehouse"] = None
voucher: Optional["Voucher"] = None
voucher_code: Optional["VoucherCode"] = None
@@ -133,61 +133,6 @@ class CheckoutInfo:
pregenerated_payloads_for_excluded_shipping_method: dict | None = None
allow_sync_webhooks: bool = True
- _cached_built_in_shipping_methods: list[ShippingMethodData] | None = None
- _cached_external_shipping_methods: list[ShippingMethodData] | None = None
-
- def get_all_shipping_methods(
- self,
- ) -> list["ShippingMethodData"]:
- """Return list of all available shipping methods.
-
- If self.allow_sync_webhooks is set to False, any external calls will be skipped.
- If self.allow_sync_webhooks is set to True, the external calls like: external
- shipping methods or exclude shipping methods will be called.
-
- The fetched values are stored in self object to remove any additional
- external/DB calls.
- """
- if (
- self._cached_external_shipping_methods is not None
- and self._cached_built_in_shipping_methods is not None
- ):
- return (
- self._cached_built_in_shipping_methods
- + self._cached_external_shipping_methods
- )
-
- if (
- not self.allow_sync_webhooks
- and self._cached_built_in_shipping_methods is not None
- ):
- return self._cached_built_in_shipping_methods
-
- if self._cached_built_in_shipping_methods is None:
- self._cached_built_in_shipping_methods = (
- get_available_built_in_shipping_methods_for_checkout_info(self)
- )
-
- if not self.allow_sync_webhooks:
- excluded_methods = []
- all_methods = self._cached_built_in_shipping_methods
- else:
- self._cached_external_shipping_methods = (
- get_external_shipping_methods_for_checkout_info(self)
- )
- all_methods = (
- self._cached_built_in_shipping_methods
- + self._cached_external_shipping_methods
- )
- # Filter shipping methods using sync webhooks
- excluded_methods = self.manager.excluded_shipping_methods_for_checkout(
- self.checkout,
- self.channel,
- all_methods,
- self.pregenerated_payloads_for_excluded_shipping_method,
- )
- initialize_shipping_method_active_status(all_methods, excluded_methods)
- return all_methods
@cached_property
def valid_pick_up_points(self) -> Iterable["Warehouse"]:
@@ -199,95 +144,20 @@ class CheckoutInfo:
)
)
- def _update_denormalized_shipping_method_fields(
- self, delivery_method: ShippingMethodData | Warehouse
- ):
- checkout = self.checkout
- fields_to_update = []
- if isinstance(delivery_method, ShippingMethodData):
- new_shipping_method_name = delivery_method.name
- new_shipping_price = delivery_method.price
- else:
- new_shipping_method_name = None
- new_shipping_price = zero_money(checkout.currency)
-
- if checkout.shipping_method_name != new_shipping_method_name:
- checkout.shipping_method_name = new_shipping_method_name
- fields_to_update.append("shipping_method_name")
- current_shipping_price = quantize_price(
- checkout.undiscounted_base_shipping_price, checkout.currency
- )
- new_shipping_price = quantize_price(new_shipping_price, checkout.currency)
- if current_shipping_price != new_shipping_price:
- checkout.undiscounted_base_shipping_price_amount = new_shipping_price.amount
- fields_to_update.append("undiscounted_base_shipping_price_amount")
-
- if fields_to_update:
- with allow_writer():
- checkout.save(update_fields=fields_to_update)
-
def get_delivery_method_info(self) -> "DeliveryMethodBase":
- from .utils import get_external_shipping_id
-
delivery_method: ShippingMethodData | Warehouse | None = None
- if self.shipping_method:
- # Find listing for the currently selected shipping method
- shipping_channel_listing = None
- for listing in self.shipping_channel_listings:
- if listing.shipping_method_id == self.shipping_method.id:
- shipping_channel_listing = listing
- break
-
- if shipping_channel_listing:
- delivery_method = convert_to_shipping_method_data(
- self.shipping_method, shipping_channel_listing
- )
-
- elif external_shipping_method_id := get_external_shipping_id(self.checkout):
- if self.allow_sync_webhooks:
- methods = {
- method.id: method for method in self.get_all_shipping_methods()
- }
- if method := methods.get(external_shipping_method_id):
- delivery_method = method
- else:
- new_shipping_method_id = convert_to_app_id_with_identifier(
- external_shipping_method_id
- )
- if new_shipping_method_id is None:
- delivery_method = None
- else:
- delivery_method = methods.get(new_shipping_method_id)
- else:
- delivery_method = ShippingMethodData(
- id=get_external_shipping_id(self.checkout),
- name=self.checkout.shipping_method_name or "",
- price=self.checkout.undiscounted_base_shipping_price,
- )
-
- else:
- delivery_method = self.collection_point
-
- if isinstance(delivery_method, ShippingMethodData):
- self._update_denormalized_shipping_method_fields(delivery_method)
-
- return get_delivery_method_info(delivery_method, self.shipping_address)
+ if assigned_sm := self.assigned_delivery:
+ delivery_method = convert_checkout_delivery_to_shipping_method_data(
+ assigned_sm
+ )
+ return ShippingMethodInfo(delivery_method, self.shipping_address)
- @property
- def valid_shipping_methods(self) -> list["ShippingMethodData"]:
- return [method for method in self.get_all_shipping_methods() if method.active]
+ delivery_method = self.collection_point
+ if delivery_method is not None:
+ return CollectionPointInfo(delivery_method, delivery_method.address)
- @property
- def valid_delivery_methods(
- self,
- ) -> list[Union["ShippingMethodData", "Warehouse"]]:
- return list(
- itertools.chain(
- self.valid_shipping_methods,
- self.valid_pick_up_points,
- )
- )
+ return DeliveryMethodBase()
def get_country(self) -> str:
address = self.shipping_address or self.billing_address
@@ -337,6 +207,9 @@ class DeliveryMethodBase:
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):
@@ -358,10 +231,27 @@ class ShippingMethodInfo(DeliveryMethodBase):
return bool(self.shipping_address)
def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:
- valid_delivery_methods = checkout_info.valid_delivery_methods
- return bool(
- valid_delivery_methods and self.delivery_method in valid_delivery_methods
- )
+ 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)
@@ -402,28 +292,16 @@ class CollectionPointInfo(DeliveryMethodBase):
)
def is_method_in_valid_methods(self, checkout_info) -> bool:
- valid_delivery_methods = checkout_info.valid_delivery_methods
+ valid_delivery_methods = checkout_info.valid_pick_up_points
return bool(
valid_delivery_methods and self.delivery_method in valid_delivery_methods
)
-
-@singledispatch
-def get_delivery_method_info(
- delivery_method: Union["ShippingMethodData", "Warehouse"] | None,
- address: Optional["Address"] = None,
-) -> DeliveryMethodBase:
- if delivery_method is None:
- return DeliveryMethodBase()
- if isinstance(delivery_method, ShippingMethodData):
- return ShippingMethodInfo(delivery_method, address)
- if isinstance(delivery_method, Warehouse):
- # TODO: Workaround for lack of using in tests.
- # The warehouse address should be loaded when CheckoutInfo is created.
- with allow_writer():
- return CollectionPointInfo(delivery_method, delivery_method.address)
-
- raise NotImplementedError()
+ 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(
@@ -599,7 +477,6 @@ def fetch_checkout_info(
checkout: "Checkout",
lines: list[CheckoutLineInfo],
manager: "PluginsManager",
- shipping_channel_listings: Iterable["ShippingMethodChannelListing"] | None = None,
voucher: Optional["Voucher"] = None,
voucher_code: Optional["VoucherCode"] = None,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
@@ -610,8 +487,6 @@ def fetch_checkout_info(
channel = checkout.channel
tax_configuration = channel.tax_configuration
shipping_address = checkout.shipping_address
- if shipping_channel_listings is None:
- shipping_channel_listings = channel.shipping_method_listings.all()
if not voucher or not voucher_code:
voucher, voucher_code = get_voucher_for_checkout(
@@ -630,8 +505,7 @@ def fetch_checkout_info(
discounts=list(checkout.discounts.all()),
lines=lines,
manager=manager,
- shipping_channel_listings=list(shipping_channel_listings),
- shipping_method=checkout.shipping_method,
+ assigned_delivery=checkout.assigned_delivery,
collection_point=checkout.collection_point,
voucher=voucher,
voucher_code=voucher_code,
@@ -677,64 +551,272 @@ def get_available_built_in_shipping_methods_for_checkout_info(
return valid_shipping_methods
-def get_external_shipping_methods_for_checkout_info(
+def fetch_external_shipping_methods_for_checkout_info(
checkout_info,
+ available_built_in_methods: list[ShippingMethodData],
) -> list[ShippingMethodData]:
manager = checkout_info.manager
return manager.list_shipping_methods_for_checkout(
- checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug
+ checkout=checkout_info.checkout,
+ channel_slug=checkout_info.channel.slug,
+ built_in_shipping_methods=available_built_in_methods,
)
-def get_all_shipping_methods_list(
- checkout_info,
+def find_checkout_line_info(
+ lines: list["CheckoutLineInfo"],
+ line_id: "UUID",
+) -> "CheckoutLineInfo":
+ """Return checkout line info from lines parameter.
+
+ 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],
):
- return list(
- itertools.chain(
- get_available_built_in_shipping_methods_for_checkout_info(
- checkout_info,
- ),
- get_external_shipping_methods_for_checkout_info(checkout_info),
+ """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
-def update_delivery_method_lists_for_checkout_info(
+ return False
+
+
+@allow_writer()
+def fetch_shipping_methods_for_checkout(
checkout_info: "CheckoutInfo",
- shipping_method: Optional["ShippingMethod"],
- collection_point: Optional["Warehouse"],
- shipping_address: Optional["Address"],
- lines: list[CheckoutLineInfo],
- shipping_channel_listings: Iterable[ShippingMethodChannelListing],
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- # Update checkout info fields with new data
- checkout_info.shipping_method = shipping_method
- checkout_info.collection_point = collection_point
- checkout_info.shipping_address = shipping_address
- checkout_info.lines = lines
- checkout_info.shipping_channel_listings = list(shipping_channel_listings)
-
- # Clear cached properties if they were already calculated, so they can be
- # recalculated.
- try:
- del checkout_info._cached_built_in_shipping_methods
- del checkout_info._cached_external_shipping_methods
- except AttributeError:
- pass
+) -> 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
- try:
- del checkout_info.valid_pick_up_points
- except AttributeError:
- pass
+ 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()),
+ )
+ }
+ all_methods = list(built_in_shipping_methods_dict.values()) + list(
+ external_shipping_methods_dict.values()
+ )
+ excluded_methods = checkout_info.manager.excluded_shipping_methods_for_checkout(
+ checkout,
+ checkout_info.channel,
+ all_methods,
+ checkout_info.pregenerated_payloads_for_excluded_shipping_method,
+ )
+ initialize_shipping_method_active_status(all_methods, excluded_methods)
+ checkout_deliveries = {}
-def find_checkout_line_info(
- lines: list["CheckoutLineInfo"],
- line_id: "UUID",
-) -> "CheckoutLineInfo":
- """Return checkout line info from lines parameter.
+ 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
- The return value represents the updated version of checkout_line_info parameter.
+ 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.
"""
- return next(line_info for line_info in lines if line_info.line.pk == line_id)
+ 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/migrations/0085_checkout_delivery_methods_stale_at_checkoutdelivery_and_more.py b/saleor/checkout/migrations/0085_checkout_delivery_methods_stale_at_checkoutdelivery_and_more.py
new file mode 100644
index 0000000000..361d8779a4
--- /dev/null
+++ b/saleor/checkout/migrations/0085_checkout_delivery_methods_stale_at_checkoutdelivery_and_more.py
@@ -0,0 +1,131 @@
+# Generated by Django 5.2.8 on 2025-11-25 11:09
+
+import uuid
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0084_checkout_automaticcompletionattempt_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="delivery_methods_stale_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.CreateModel(
+ name="CheckoutDelivery",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ unique=True,
+ ),
+ ),
+ (
+ "external_shipping_method_id",
+ models.CharField(
+ blank=True,
+ db_index=True,
+ editable=False,
+ max_length=1024,
+ null=True,
+ ),
+ ),
+ (
+ "built_in_shipping_method_id",
+ models.IntegerField(
+ blank=True, db_index=True, editable=False, null=True
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("description", models.TextField(blank=True, null=True)),
+ ("price_amount", models.DecimalField(decimal_places=3, max_digits=20)),
+ ("currency", models.CharField(max_length=3)),
+ (
+ "maximum_delivery_days",
+ models.PositiveIntegerField(blank=True, null=True),
+ ),
+ (
+ "minimum_delivery_days",
+ models.PositiveIntegerField(blank=True, null=True),
+ ),
+ ("metadata", models.JSONField(default=dict)),
+ ("private_metadata", models.JSONField(default=dict)),
+ ("active", models.BooleanField(default=True)),
+ ("message", models.TextField(blank=True, null=True)),
+ ("is_external", models.BooleanField(default=False)),
+ ("is_valid", models.BooleanField(default=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("tax_class_id", models.IntegerField(blank=True, null=True)),
+ (
+ "tax_class_name",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ (
+ "tax_class_private_metadata",
+ models.JSONField(
+ blank=True,
+ db_default={},
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ ),
+ ),
+ (
+ "tax_class_metadata",
+ models.JSONField(
+ blank=True,
+ db_default={},
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ ),
+ ),
+ (
+ "checkout",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="shipping_methods",
+ to="checkout.checkout",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("created_at", "pk"),
+ },
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="assigned_delivery",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="checkout.checkoutdelivery",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="checkoutdelivery",
+ constraint=models.UniqueConstraint(
+ fields=(
+ "checkout",
+ "external_shipping_method_id",
+ "built_in_shipping_method_id",
+ "is_valid",
+ ),
+ name="unique_for_checkout",
+ nulls_distinct=False,
+ ),
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 26422ff3ad..b331c1668a 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -19,6 +19,7 @@ from ..channel.models import Channel
from ..core.db.fields import MoneyField, TaxedMoneyField
from ..core.models import ModelWithMetadata
from ..core.taxes import TAX_ERROR_FIELD_LENGTH, zero_money
+from ..core.utils.json_serializer import CustomJsonEncoder
from ..giftcard.models import GiftCard
from ..permission.enums import CheckoutPermissions
from ..shipping.models import ShippingMethod
@@ -33,6 +34,78 @@ def get_default_country():
return settings.DEFAULT_COUNTRY
+class CheckoutDelivery(models.Model):
+ """Model to cache shipping methods for a checkout."""
+
+ id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)
+ checkout = models.ForeignKey(
+ "checkout.Checkout",
+ related_name="shipping_methods",
+ on_delete=models.CASCADE,
+ )
+ external_shipping_method_id = models.CharField(
+ max_length=1024, blank=True, null=True, editable=False, db_index=True
+ )
+ built_in_shipping_method_id = models.IntegerField(
+ blank=True, null=True, editable=False, db_index=True
+ )
+
+ name = models.CharField(max_length=255)
+ description = models.TextField(null=True, blank=True)
+
+ price = MoneyField(amount_field="price_amount", currency_field="currency")
+ price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ )
+ currency = models.CharField(
+ max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
+ )
+
+ maximum_delivery_days = models.PositiveIntegerField(null=True, blank=True)
+ minimum_delivery_days = models.PositiveIntegerField(null=True, blank=True)
+ metadata = models.JSONField(default=dict)
+ private_metadata = models.JSONField(default=dict)
+
+ active = models.BooleanField(default=True)
+ message = models.TextField(blank=True, null=True)
+
+ is_external = models.BooleanField(default=False)
+ is_valid = models.BooleanField(default=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ # Denormalized tax class data
+ tax_class_id = models.IntegerField(null=True, blank=True)
+ tax_class_name = models.CharField(max_length=255, null=True, blank=True)
+ tax_class_private_metadata = models.JSONField(
+ blank=True, db_default={}, default=dict, encoder=CustomJsonEncoder
+ )
+ tax_class_metadata = models.JSONField(
+ blank=True, db_default={}, default=dict, encoder=CustomJsonEncoder
+ )
+
+ @property
+ def shipping_method_id(self) -> str:
+ return self.external_shipping_method_id or str(self.built_in_shipping_method_id)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=[
+ "checkout",
+ "external_shipping_method_id",
+ "built_in_shipping_method_id",
+ "is_valid",
+ ],
+ name="unique_for_checkout",
+ nulls_distinct=False,
+ ),
+ ]
+ ordering = ("created_at", "pk")
+
+
class Checkout(models.Model):
"""A shopping checkout."""
@@ -197,11 +270,20 @@ class Checkout(models.Model):
db_index=True,
)
+ delivery_methods_stale_at = models.DateTimeField(null=True, blank=True)
price_expiration = models.DateTimeField(default=timezone.now)
# Expiration time of the applied discounts.
# Decides if the discounts are updated before tax recalculation.
discount_expiration = models.DateTimeField(default=timezone.now)
+ assigned_delivery = models.ForeignKey(
+ CheckoutDelivery,
+ blank=True,
+ null=True,
+ related_name="+",
+ on_delete=models.SET_NULL,
+ )
+
discount_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
diff --git a/saleor/checkout/tests/fixtures/checkout.py b/saleor/checkout/tests/fixtures/checkout.py
index 9cb05cf6fe..e4571f41c8 100644
--- a/saleor/checkout/tests/fixtures/checkout.py
+++ b/saleor/checkout/tests/fixtures/checkout.py
@@ -7,10 +7,40 @@ from django.utils import timezone
from ....plugins.manager import get_plugins_manager
from ....product.models import ProductVariantChannelListing
from ...fetch import fetch_checkout_info, fetch_checkout_lines
-from ...models import Checkout, CheckoutLine, CheckoutMetadata
+from ...models import Checkout, CheckoutDelivery, CheckoutLine, CheckoutMetadata
from ...utils import add_variant_to_checkout
+def checkout_delivery(shipping_zone):
+ def wrap(checkout, shipping_method=None):
+ if not shipping_method:
+ shipping_method = shipping_zone.shipping_methods.first()
+
+ listing = shipping_method.channel_listings.get(channel_id=checkout.channel_id)
+ tax_class_details = {}
+ if shipping_method.tax_class:
+ tax_class_details = {
+ "tax_class_id": shipping_method.tax_class.id,
+ "tax_class_name": shipping_method.tax_class.name,
+ "tax_class_metadata": shipping_method.tax_class.metadata,
+ "tax_class_private_metadata": shipping_method.tax_class.private_metadata,
+ }
+
+ return CheckoutDelivery.objects.create(
+ checkout=checkout,
+ built_in_shipping_method_id=shipping_method.id,
+ description=shipping_method.description,
+ name=shipping_method.name,
+ price_amount=listing.price_amount,
+ currency=listing.currency,
+ is_external=False,
+ **tax_class_details,
+ )
+
+ return wrap
+
+
@pytest.fixture
def checkout(db, channel_USD, settings):
checkout = Checkout.objects.create(
@@ -123,16 +153,19 @@ def checkouts_assigned_to_customer(channel_USD, channel_PLN, customer_user):
@pytest.fixture
-def checkout_ready_to_complete(checkout_with_item, address, shipping_method, gift_card):
+def checkout_ready_to_complete(
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
items={"accepted": "false"}
)
- checkout_with_item.gift_cards.add(gift_card)
checkout.save()
checkout.metadata_storage.save()
return checkout
@@ -166,19 +199,23 @@ def checkout_with_shipping_required(checkout_with_item, product):
@pytest.fixture
-def checkout_with_item_and_shipping_method(checkout_with_item, shipping_method):
+def checkout_with_item_and_shipping_method(
+ checkout_with_item, checkout_delivery, address
+):
checkout = checkout_with_item
- checkout.shipping_method = shipping_method
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
return checkout
@pytest.fixture
-def checkout_with_shipping_method(checkout_with_shipping_address, shipping_method):
+def checkout_with_shipping_method(
+ checkout_with_shipping_address,
+ checkout_delivery,
+):
checkout = checkout_with_shipping_address
-
- checkout.shipping_method = shipping_method
- checkout.shipping_method_name = shipping_method.name
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
return checkout
@@ -208,7 +245,10 @@ def checkout_with_single_item(checkout, product):
@pytest.fixture
def checkout_with_variant_without_inventory_tracking(
- checkout, variant_without_inventory_tracking, address, shipping_method
+ checkout,
+ variant_without_inventory_tracking,
+ address,
+ checkout_delivery,
):
variant = variant_without_inventory_tracking
checkout_info = fetch_checkout_info(
@@ -216,7 +256,7 @@ def checkout_with_variant_without_inventory_tracking(
)
add_variant_to_checkout(checkout_info, variant, 1)
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -355,9 +395,15 @@ def checkout_with_delivery_method_for_cc(
@pytest.fixture
def checkout_with_delivery_method_for_external_shipping(checkout_with_item, address):
+ sm = checkout_with_item.shipping_methods.create(
+ external_shipping_method_id="YXBwOlFYQndPakU9OmFiY2Q=",
+ name="Provider - Economy",
+ price_amount=Decimal(99),
+ currency=checkout_with_item.currency,
+ is_external=True,
+ )
+ checkout_with_item.assigned_delivery = sm
checkout_with_item.shipping_address = address.get_copy()
- checkout_with_item.external_shipping_method_id = "YXBwOlFYQndPakU9OmFiY2Q="
- checkout_with_item.shipping_method_name = "Provider - Economy"
checkout_with_item.save()
return checkout_with_item
@@ -378,18 +424,22 @@ def checkout_with_items(checkout, product_list, product):
@pytest.fixture
-def checkout_with_items_and_shipping(checkout_with_items, address, shipping_method):
+def checkout_with_items_and_shipping(checkout_with_items, address, checkout_delivery):
checkout_with_items.shipping_address = address
- checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
checkout_with_items.billing_address = address
checkout_with_items.save()
return checkout_with_items
@pytest.fixture
-def checkout_with_item_and_shipping(checkout_with_item, address, shipping_method):
+def checkout_with_item_and_shipping(
+ checkout_with_item,
+ address,
+ checkout_delivery,
+):
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.billing_address = address
checkout_with_item.save()
return checkout_with_item
@@ -466,7 +516,7 @@ def checkout_with_problems(
checkout_with_items,
product_type,
address,
- shipping_method,
+ checkout_delivery,
category,
default_tax_class,
channel_USD,
@@ -474,9 +524,13 @@ def checkout_with_problems(
):
checkout_with_items.shipping_address = address
checkout_with_items.billing_address = address
- checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
checkout_with_items.save(
- update_fields=["shipping_address", "shipping_method", "billing_address"]
+ update_fields=[
+ "shipping_address",
+ "assigned_delivery",
+ "billing_address",
+ ]
)
first_line = checkout_with_items.lines.first()
diff --git a/saleor/checkout/tests/fixtures/checkout_info.py b/saleor/checkout/tests/fixtures/checkout_info.py
index 135a813aef..d27adf99aa 100644
--- a/saleor/checkout/tests/fixtures/checkout_info.py
+++ b/saleor/checkout/tests/fixtures/checkout_info.py
@@ -1,7 +1,6 @@
import pytest
from ....plugins.manager import get_plugins_manager
-from ....shipping.models import ShippingMethodChannelListing
from ...fetch import CheckoutInfo, fetch_checkout_info, fetch_checkout_lines
@@ -18,11 +17,7 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):
checkout = checkout_with_items_and_shipping
channel = checkout.channel
shipping_address = checkout.shipping_address
- shipping_method = checkout.shipping_method
- shipping_channel_listing = ShippingMethodChannelListing.objects.get(
- channel=channel,
- shipping_method=shipping_method,
- )
+
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = CheckoutInfo(
@@ -31,9 +26,8 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):
channel=channel,
billing_address=checkout.billing_address,
shipping_address=shipping_address,
- shipping_method=shipping_method,
- shipping_channel_listings=[shipping_channel_listing],
tax_configuration=channel.tax_configuration,
+ assigned_delivery=checkout.assigned_delivery,
discounts=[],
manager=manager,
lines=lines,
diff --git a/saleor/checkout/tests/fixtures/checkout_with_discount.py b/saleor/checkout/tests/fixtures/checkout_with_discount.py
index 227ed95e86..4ff8d10ed7 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_discount.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_discount.py
@@ -178,10 +178,11 @@ def checkout_with_item_and_voucher_once_per_order(checkout_with_item, voucher):
@pytest.fixture
def checkout_with_item_and_voucher_and_shipping_method(
- checkout_with_item_and_voucher, shipping_method
+ checkout_with_item_and_voucher, checkout_delivery, address
):
checkout = checkout_with_item_and_voucher
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
checkout.save()
return checkout
diff --git a/saleor/checkout/tests/fixtures/checkout_with_prices.py b/saleor/checkout/tests/fixtures/checkout_with_prices.py
index 32da626efd..460cc4558d 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_prices.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_prices.py
@@ -17,14 +17,14 @@ def checkout_with_prices(
address_other_country,
warehouse,
customer_user,
- shipping_method,
+ checkout_delivery,
voucher,
):
# Need to save shipping_method before fetching checkout info.
- checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
country_code = address_other_country.country.code
checkout_with_items.set_country(country_code, commit=False)
- checkout_with_items.save(update_fields=["shipping_method", "country"])
+ checkout_with_items.save(update_fields=["assigned_delivery", "country"])
manager = get_plugins_manager(allow_replica=False)
lines = checkout_with_items.lines.all()
diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.py
index f58cc40650..3f76e67014 100644
--- a/saleor/checkout/tests/test_base_calculations.py
+++ b/saleor/checkout/tests/test_base_calculations.py
@@ -636,13 +636,17 @@ def test_base_tax_rate_gross_price_zero():
assert calculate_tax_rate(price) == Decimal("0.0")
-def test_base_checkout_total(checkout_with_item, shipping_method, voucher_percentage):
+def test_base_checkout_total(
+ checkout_with_item, checkout_delivery, shipping_method, voucher_percentage
+):
# given
manager = get_plugins_manager(allow_replica=False)
channel = checkout_with_item.channel
currency = checkout_with_item.currency
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_method
+ )
# only line vouchers are applied on based price so this discount won't be included
# in base price
discount_amount = Money(5, currency)
@@ -669,7 +673,7 @@ def test_base_checkout_total(checkout_with_item, shipping_method, voucher_percen
def test_base_checkout_total_high_discount_on_entire_order_apply_once_per_order(
- checkout_with_item, shipping_method, voucher_percentage
+ checkout_with_item, checkout_delivery, shipping_method, voucher_percentage
):
# given
voucher_percentage.apply_once_per_order = True
@@ -681,7 +685,9 @@ def test_base_checkout_total_high_discount_on_entire_order_apply_once_per_order(
manager = get_plugins_manager(allow_replica=False)
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_method
+ )
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.save(update_fields=["shipping_method", "voucher_code"])
@@ -704,7 +710,7 @@ def test_base_checkout_total_high_discount_on_entire_order_apply_once_per_order(
def test_base_checkout_total_high_discount_on_shipping(
- checkout_with_item, shipping_method, voucher_shipping_type
+ checkout_with_item, shipping_method, voucher_shipping_type, checkout_delivery
):
# given
manager = get_plugins_manager(allow_replica=False)
@@ -713,7 +719,9 @@ def test_base_checkout_total_high_discount_on_shipping(
shipping_price = shipping_method.channel_listings.get(channel=channel).price
currency = checkout_with_item.currency
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_method
+ )
checkout_with_item.voucher_code = voucher_shipping_type.code
checkout_with_item.discount = shipping_price + Money(10, currency)
checkout_with_item.save()
@@ -733,14 +741,14 @@ def test_base_checkout_total_high_discount_on_shipping(
def test_base_checkout_total_order_discount(
- checkout_with_item_and_order_discount, shipping_method
+ checkout_with_item_and_order_discount, shipping_method, checkout_delivery
):
# given
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_item_and_order_discount
channel = checkout.channel
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout_lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
@@ -760,14 +768,14 @@ def test_base_checkout_total_order_discount(
def test_checkout_total_order_discount(
- checkout_with_item_and_order_discount, shipping_method
+ checkout_with_item_and_order_discount, shipping_method, checkout_delivery
):
# given
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_item_and_order_discount
channel = checkout.channel
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout_lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
@@ -789,14 +797,14 @@ def test_checkout_total_order_discount(
def test_base_checkout_total_gift_promotion(
- checkout_with_item_and_gift_promotion, shipping_method
+ checkout_with_item_and_gift_promotion, shipping_method, checkout_delivery
):
# given
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_item_and_gift_promotion
channel = checkout.channel
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout_lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
@@ -817,14 +825,14 @@ def test_base_checkout_total_gift_promotion(
def test_checkout_total_gift_promotion(
- checkout_with_item_and_gift_promotion, shipping_method
+ checkout_with_item_and_gift_promotion, shipping_method, checkout_delivery
):
# given
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_item_and_gift_promotion
channel = checkout.channel
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout_lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index da716b85bd..4e5b1793da 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -10,6 +10,7 @@ from freezegun import freeze_time
from graphene import Node
from prices import Money, TaxedMoney
+from ...checkout.models import CheckoutDelivery
from ...core.prices import quantize_price
from ...core.taxes import (
TaxData,
@@ -26,7 +27,6 @@ from ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401
from ...plugins.manager import get_plugins_manager
from ...plugins.tests.sample_plugins import PluginSample
from ...product.models import ProductVariantChannelListing
-from ...shipping.interface import ShippingMethodData
from ...tax import TaxCalculationStrategy
from ...tax.calculations.checkout import update_checkout_prices_with_flat_rates
from ...tax.models import TaxClass, TaxClassCountryRate
@@ -46,7 +46,9 @@ from ..calculations import (
)
from ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_lines
from ..models import Checkout
-from ..utils import add_promo_code_to_checkout, assign_external_shipping_to_checkout
+from ..utils import (
+ add_promo_code_to_checkout,
+)
@pytest.fixture
@@ -334,8 +336,10 @@ def test_fetch_checkout_data_flat_rates(
country=country_code, rate=23
)
- checkout.shipping_method.tax_class.country_rates.update_or_create(
- country=country_code, rate=23
+ TaxClassCountryRate.objects.update_or_create(
+ country=country_code,
+ rate=23,
+ tax_class_id=checkout.assigned_delivery.tax_class_id,
)
# when
@@ -389,8 +393,8 @@ def test_fetch_checkout_data_flat_rates_with_weighted_shipping_tax(
third_tax_class = tax_classes[1]
third_tax_class.country_rates.filter(country=country_code).update(rate=223)
- checkout.shipping_method.tax_class = third_tax_class
- checkout.shipping_method.save()
+ checkout.assigned_delivery.tax_class_id = third_tax_class.id
+ checkout.assigned_delivery.save()
lines, _ = fetch_checkout_lines(checkout_with_items_and_shipping)
checkout_info = fetch_checkout_info(
@@ -439,9 +443,10 @@ def test_fetch_checkout_data_flat_rates_and_no_tax_calc_strategy(
line.variant.product.tax_class.country_rates.update_or_create(
country=country_code, rate=23
)
-
- checkout.shipping_method.tax_class.country_rates.update_or_create(
- country=country_code, rate=23
+ TaxClassCountryRate.objects.update_or_create(
+ country=country_code,
+ rate=23,
+ tax_class_id=checkout.assigned_delivery.tax_class_id,
)
# when
@@ -934,7 +939,7 @@ def test_fetch_checkout_data_flat_rates_shipping_tax_differs_from_default(
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_external_shipping_method_called_only_once_during_tax_calculations(
+def test_external_shipping_webhook_it_not_called_during_tax_calculations(
mock_send_webhook_request_sync,
checkout_with_single_item,
settings,
@@ -946,41 +951,33 @@ def test_external_shipping_method_called_only_once_during_tax_calculations(
external_method_id = "method-1-from-shipping-app"
shipping_name = "Shipping app method 1"
shipping_price = Decimal(10)
- currency = "USD"
- mock_send_webhook_request_sync.side_effect = (
- [
- {
- "amount": shipping_price,
- "currency": currency,
- "id": external_method_id,
- "name": shipping_name,
- }
+ mock_send_webhook_request_sync.return_value = {
+ "lines": [
+ {"tax_rate": 0, "total_gross_amount": "21.6", "total_net_amount": 20}
],
- {
- "lines": [
- {"tax_rate": 0, "total_gross_amount": "21.6", "total_net_amount": 20}
- ],
- "shipping_price_gross_amount": "1443.96",
- "shipping_price_net_amount": "1337",
- "shipping_tax_rate": 0,
- },
- )
+ "shipping_price_gross_amount": "1443.96",
+ "shipping_price_net_amount": "1337",
+ "shipping_tax_rate": 0,
+ }
+
external_shipping_method_id = Node.to_global_id(
"app", f"{shipping_app_with_subscription.id}:{external_method_id}"
)
- external_shipping_method = ShippingMethodData(
- id=external_shipping_method_id,
- name=shipping_name,
- price=Money(shipping_price, currency),
- )
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager(allow_replica=False)
- checkout_with_single_item.shipping_address = address
- assign_external_shipping_to_checkout(
- checkout_with_single_item, external_shipping_method
+ checkout_with_single_item.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout_with_single_item,
+ external_shipping_method_id=external_shipping_method_id,
+ name=shipping_name,
+ price_amount=shipping_price,
+ currency="USD",
+ maximum_delivery_days=7,
)
+
+ checkout_with_single_item.shipping_address = address
+
checkout_with_single_item.save()
checkout_with_single_item.metadata_storage.save()
checkout_lines, _ = fetch_checkout_lines(checkout_with_single_item)
@@ -1003,7 +1000,7 @@ def test_external_shipping_method_called_only_once_during_tax_calculations(
)
# then
- assert mock_send_webhook_request_sync.call_count == 2
+ assert mock_send_webhook_request_sync.call_count == 1
assert checkout_with_single_item.shipping_price == TaxedMoney(
net=Money("1337.00", "USD"), gross=Money("1443.96", "USD")
)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index ee350ca5bd..466f126902 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -29,9 +29,6 @@ from ...discount.models import (
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...product.models import VariantChannelListingPromotionRule
-from ...shipping.interface import ShippingMethodData
-from ...shipping.models import ShippingZone
-from ...webhook.event_types import WebhookEventSyncType
from .. import base_calculations, calculations
from ..fetch import (
CheckoutInfo,
@@ -40,15 +37,14 @@ from ..fetch import (
fetch_checkout_info,
fetch_checkout_lines,
)
-from ..models import Checkout, CheckoutLine, CheckoutMetadata
+from ..models import Checkout, CheckoutLine
from ..utils import (
- PRIVATE_META_APP_SHIPPING_ID,
add_voucher_to_checkout,
calculate_checkout_quantity,
cancel_active_payments,
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
- clear_delivery_method,
+ clear_cc_delivery_method,
get_checkout_metadata,
get_voucher_discount_for_checkout,
get_voucher_for_checkout,
@@ -59,7 +55,9 @@ from ..utils import (
)
-def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):
+def test_is_valid_delivery_method(
+ checkout_with_item, address, shipping_zone, checkout_delivery
+):
checkout = checkout_with_item
checkout.shipping_address = address
checkout.save()
@@ -69,468 +67,42 @@ def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):
delivery_method_info = checkout_info.get_delivery_method_info()
# no shipping method assigned
assert not delivery_method_info.is_valid_delivery_method()
- shipping_method = shipping_zone.shipping_methods.first()
- checkout.shipping_method = shipping_method
+
+ checkout.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()
- zone = ShippingZone.objects.create(name="DE", countries=["DE"])
- shipping_method.shipping_zone = zone
- shipping_method.save()
+ 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)
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_is_valid_delivery_method_external_method(
- mock_send_request, checkout_with_item, address, settings, shipping_app
-):
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- assert not shipping_app.identifier
- response_method_id = "abcd"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
-
- mock_send_request.return_value = mock_json_response
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: method_id
- }
- checkout.save()
- checkout.metadata_storage.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()
-
- assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_is_valid_delivery_method_external_method_with_metadata_and_description(
- mock_send_request, checkout_with_item, address, settings, shipping_app
-):
- # given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- assert not shipping_app.identifier
- response_method_id = "abcd"
- metadata = {"key": "value", "key_2": "value_2"}
- description = "Shipping Method Description"
- mock_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- "minimum_delivery_days": "1",
- "description": description,
- "metadata": metadata,
- }
- ]
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
-
- mock_send_request.return_value = mock_response
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: method_id
- }
- checkout.save()
- checkout.metadata_storage.save()
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
-
- # when
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.get_delivery_method_info()
-
- # then
- assert delivery_method_info.delivery_method.metadata == metadata
- assert delivery_method_info.delivery_method.description == description
- assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_delivery_method_external_method_with_not_allowed_webhooks(
- mocked_request, checkout_with_item, shipping_app, settings
-):
- # given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- shipping_method_id = "abcd"
- shipping_method_name = "Default shipping"
- graphql_shipping_method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{shipping_method_id}"
- )
-
- checkout = checkout_with_item
- shipping_price = Money(Decimal(10), currency=checkout.currency)
-
- checkout.external_shipping_method_id = graphql_shipping_method_id
- checkout.undiscounted_base_shipping_price = shipping_price
- checkout.shipping_method_name = shipping_method_name
- checkout.save()
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.allow_sync_webhooks = False
-
- # when
- delivery_method_info = checkout_info.get_delivery_method_info()
-
- # then
- delivery_method = delivery_method_info.delivery_method
- assert isinstance(delivery_method, ShippingMethodData)
- assert delivery_method.name == shipping_method_name
- assert delivery_method.price == shipping_price
- assert delivery_method.id == graphql_shipping_method_id
- mocked_request.assert_not_called()
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_delivery_method_exclude_shipping_methods_with_not_allowed_webhooks(
- mocked_request, checkout_with_item, shipping_app, settings
-):
- # given
- webhook = shipping_app.webhooks.get()
- webhook.events.create(
- event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- )
-
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- shipping_method_id = "abcd"
- shipping_method_name = "Default shipping"
- graphql_shipping_method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{shipping_method_id}"
- )
-
- checkout = checkout_with_item
- shipping_price = Money(Decimal(10), currency=checkout.currency)
-
- checkout.external_shipping_method_id = graphql_shipping_method_id
- checkout.undiscounted_base_shipping_price = shipping_price
- checkout.shipping_method_name = shipping_method_name
- checkout.save()
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.allow_sync_webhooks = False
-
- # when
- delivery_method_info = checkout_info.get_delivery_method_info()
-
- # then
- delivery_method = delivery_method_info.delivery_method
- assert isinstance(delivery_method, ShippingMethodData)
- assert delivery_method.name == shipping_method_name
- assert delivery_method.price == shipping_price
- assert delivery_method.id == graphql_shipping_method_id
- mocked_request.assert_not_called()
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_get_all_shipping_methods_with_external_methods_and_not_allowed_webhooks(
- mocked_request, checkout_with_shipping_method, shipping_app, settings
-):
- # given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- checkout = checkout_with_shipping_method
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.allow_sync_webhooks = False
-
- # when
- shipping_methods = checkout_info.get_all_shipping_methods()
-
- # then
- assert all(not shipping_method.is_external for shipping_method in shipping_methods)
- mocked_request.assert_not_called()
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_get_all_shipping_methods_with_exclude_shipping_methods_with_not_allowed_webhooks(
- mocked_request, checkout_with_shipping_method, shipping_app, settings
+def test_clear_cc_delivery_method(
+ checkout_with_delivery_method_for_cc,
):
# given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- webhook = shipping_app.webhooks.get()
- webhook.events.create(
- event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- )
-
- checkout = checkout_with_shipping_method
+ assert checkout_with_delivery_method_for_cc.collection_point_id
manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.allow_sync_webhooks = False
-
- # when
- shipping_methods = checkout_info.get_all_shipping_methods()
-
- # then
- assert all(shipping_method.active for shipping_method in shipping_methods)
- mocked_request.assert_not_called()
-
-
- "invalid_metadata",
- [
- ("invalid", "format", "tuple"),
- {9: "invalid key"},
- ("", "invalid empty key"),
- "invalid format string",
- ],
-)
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_is_valid_delivery_method_external_method_with_invalid_metadata(
- mock_send_request,
- invalid_metadata,
- checkout_with_item,
- address,
- settings,
- shipping_app,
-):
- # given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- assert not shipping_app.identifier
- response_method_id = "abcd"
- metadata = invalid_metadata
- description = "Shipping Method Description"
- mock_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- "minimum_delivery_days": "1",
- "description": description,
- "metadata": metadata,
- }
- ]
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
-
- mock_send_request.return_value = mock_response
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: method_id
- }
- checkout.save()
- checkout.metadata_storage.save()
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
-
- # when
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method_info = checkout_info.get_delivery_method_info()
-
- # then
- assert delivery_method_info.delivery_method.metadata == {}
- assert delivery_method_info.delivery_method.description == description
- assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_is_valid_delivery_method_external_method_shipping_app_id_with_identifier(
- mock_send_request, checkout_with_item, address, settings, shipping_app
-):
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- shipping_app.identifier = "abcd"
- shipping_app.save(update_fields=["identifier"])
-
- response_method_id = "123"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.identifier}:{response_method_id}"
- )
-
- mock_send_request.return_value = mock_json_response
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: method_id
- }
- checkout.save()
- checkout.metadata_storage.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()
-
- assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_is_valid_delivery_method_external_method_old_shipping_app_id(
- mock_send_request, checkout_with_item, address, settings, shipping_app
-):
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- shipping_app.identifier = "abcd"
- shipping_app.save(update_fields=["identifier"])
-
- response_method_id = "123"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
+ checkout_info = fetch_checkout_info(
+ checkout_with_delivery_method_for_cc, [], manager
)
- mock_send_request.return_value = mock_json_response
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: method_id
- }
- checkout.save()
- checkout.metadata_storage.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()
-
- assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-
-
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_is_valid_delivery_method_external_method_no_longer_available(
- mock_send_request, checkout_with_item, address, settings, shipping_app
-):
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- mock_json_response = [
- {
- "id": "New-ID",
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- method_id = graphene.Node.to_global_id("app", f"{shipping_app.id}:1")
-
- mock_send_request.return_value = mock_json_response
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: method_id
- }
- checkout.save()
- checkout.metadata_storage.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()
-
- assert delivery_method_info.is_method_in_valid_methods(checkout_info) is False
-
-
-def test_clear_delivery_method(checkout, shipping_method):
- checkout.shipping_method = shipping_method
- checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, [], manager)
- clear_delivery_method(checkout_info)
- checkout.refresh_from_db()
- assert not checkout.shipping_method
- assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
-
-
[email protected](CheckoutMetadata, "save")
-def test_clear_delivery_method_do_not_update_metadata_when_no_external_shipping(
- mocked_metadata_save, checkout, shipping_method
-):
- # given
- checkout.shipping_method = shipping_method
- checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, [], manager)
-
# when
- clear_delivery_method(checkout_info)
+ clear_cc_delivery_method(checkout_info)
# then
- checkout.refresh_from_db()
- assert not mocked_metadata_save.called
- assert not checkout.shipping_method
+ 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)
[email protected](CheckoutMetadata, "save")
-def test_clear_delivery_method_update_metadata_when_external_shipping(
- mocked_metadata_save, checkout, shipping_method
-):
- # given
- checkout.shipping_method = shipping_method
- checkout.metadata_storage.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: "ID"}
- checkout.metadata_storage.save()
- checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, [], manager)
-
- # when
- clear_delivery_method(checkout_info)
-
- # then
- checkout.refresh_from_db()
- checkout.metadata_storage.refresh_from_db()
- assert mocked_metadata_save.called
- assert not checkout.shipping_method
- assert isinstance(checkout_info.get_delivery_method_info(), DeliveryMethodBase)
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
-
-
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)
@@ -541,12 +113,12 @@ def test_last_change_update(checkout):
assert checkout.last_change == datetime.datetime.now(tz=datetime.UTC)
-def test_last_change_update_foreign_key(checkout, shipping_method):
+def test_last_change_update_foreign_key(checkout, checkout_delivery):
with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
assert checkout.last_change != datetime.datetime.now(tz=datetime.UTC)
- checkout.shipping_method = shipping_method
- checkout.save(update_fields=["shipping_method", "last_change"])
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save(update_fields=["assigned_delivery", "last_change"])
assert checkout.last_change == datetime.datetime.now(tz=datetime.UTC)
@@ -630,7 +202,6 @@ def test_get_discount_for_checkout_value_entire_order_voucher(
tax_configuration=channel_USD.tax_configuration,
manager=manager,
lines=lines,
- shipping_channel_listings=[],
discounts=[],
)
@@ -797,7 +368,6 @@ def test_get_discount_for_checkout_value_specific_product_voucher(
tax_configuration=channel_USD.tax_configuration,
manager=manager,
lines=lines,
- shipping_channel_listings=[],
discounts=[],
)
@@ -899,7 +469,6 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
tax_configuration=channel_USD.tax_configuration,
manager=manager,
lines=[],
- shipping_channel_listings=[],
discounts=[],
)
with pytest.raises(NotApplicable):
@@ -1078,7 +647,6 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
tax_configuration=channel_USD.tax_configuration,
manager=manager,
lines=[],
- shipping_channel_listings=[],
discounts=[],
)
with pytest.raises(NotApplicable):
@@ -1097,7 +665,7 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
[
(
Decimal("10.00"),
- None,
+ "FR",
50,
DiscountValueType.PERCENTAGE,
[],
@@ -1105,7 +673,7 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
),
(
Decimal("10.00"),
- None,
+ "FR",
20,
DiscountValueType.FIXED,
[],
@@ -1136,32 +704,12 @@ def test_get_discount_for_checkout_shipping_voucher(
discount_type,
countries,
expected_value,
- monkeypatch,
channel_USD,
- shipping_method,
+ checkout_with_items,
+ checkout_delivery,
+ address,
):
- manager = get_plugins_manager(allow_replica=False)
- tax = Decimal("1.23")
- shipping = TaxedMoney(
- Money(shipping_cost, "USD"), Money(shipping_cost * tax, "USD")
- )
- subtotal = Money(100, "USD")
- monkeypatch.setattr(
- "saleor.checkout.base_calculations.base_checkout_subtotal",
- lambda *args: subtotal,
- )
- monkeypatch.setattr(
- "saleor.checkout.utils.is_shipping_required", lambda lines: True
- )
- checkout = Mock(
- spec=Checkout,
- is_shipping_required=Mock(return_value=True),
- channel_id=channel_USD.id,
- channel=channel_USD,
- shipping_method=shipping_method,
- get_shipping_price=Mock(return_value=shipping.gross),
- shipping_address=Mock(country=Country(shipping_country_code)),
- )
+ # given
voucher = Voucher.objects.create(
type=VoucherType.SHIPPING,
discount_value_type=discount_type,
@@ -1173,48 +721,36 @@ def test_get_discount_for_checkout_shipping_voucher(
channel=channel_USD,
discount=Money(discount_value, channel_USD.currency_code),
)
- shipping_address = Mock(spec=Address, country=Mock(code="PL"))
- checkout_info = CheckoutInfo(
- checkout=checkout,
- shipping_address=shipping_address,
- billing_address=None,
- channel=channel_USD,
- user=None,
- tax_configuration=channel_USD.tax_configuration,
- manager=manager,
- shipping_method=shipping_method,
- lines=[],
- shipping_channel_listings=shipping_method.channel_listings.all(),
- discounts=[],
- )
+ assigned_delivery = checkout_delivery(checkout_with_items)
+ assigned_delivery.price_amount = shipping_cost
+ assigned_delivery.save()
+
+ address.country = Country(shipping_country_code)
+ address.save()
+
+ checkout_with_items.shipping_address = address
+ checkout_with_items.assigned_delivery = assigned_delivery
+ checkout_with_items.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
+
+ # when
discount = get_voucher_discount_for_checkout(
- manager, voucher, checkout_info, [], None
+ manager, voucher, checkout_info, lines, None
)
+
+ # then
assert discount == Money(expected_value, "USD")
def test_get_discount_for_checkout_shipping_voucher_all_countries(
- monkeypatch, channel_USD, shipping_method
+ monkeypatch, channel_USD, checkout_delivery, checkout_with_items
):
- subtotal = Money(100, "USD")
- monkeypatch.setattr(
- "saleor.checkout.base_calculations.base_checkout_subtotal",
- lambda *args: subtotal,
- )
- monkeypatch.setattr(
- "saleor.checkout.utils.is_shipping_required", lambda lines: True
- )
- shipping_total = TaxedMoney(Money(10, "USD"), Money(10, "USD"))
- checkout = Mock(
- spec=Checkout,
- channel_id=channel_USD.id,
- channel=channel_USD,
- shipping_method_id=shipping_method.id,
- is_shipping_required=Mock(return_value=True),
- shipping_method=Mock(get_total=Mock(return_value=shipping_total)),
- shipping_address=Mock(country=Country("PL")),
- )
+ # given
+
voucher = Voucher.objects.create(
type=VoucherType.SHIPPING,
discount_value_type=DiscountValueType.PERCENTAGE,
@@ -1227,25 +763,21 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(
discount=Money(50, channel_USD.currency_code),
)
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
+ checkout_with_items.save()
+
manager = get_plugins_manager(allow_replica=False)
- checkout_info = CheckoutInfo(
- checkout=checkout,
- shipping_address=Mock(spec=Address, country=Mock(code="PL")),
- billing_address=None,
- channel=channel_USD,
- user=None,
- tax_configuration=channel_USD.tax_configuration,
- shipping_method=shipping_method,
- shipping_channel_listings=shipping_method.channel_listings.all(),
- manager=manager,
- lines=[],
- discounts=[],
- )
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
+
+ # when
discount = get_voucher_discount_for_checkout(
- manager, voucher, checkout_info, [], None
+ manager, voucher, checkout_info, lines, None
)
- assert discount == Money(5, "USD")
+ # then
+ expected_value = Decimal("5.00")
+ assert discount == Money(expected_value, "USD")
def test_get_discount_for_checkout_shipping_voucher_limited_countries(
@@ -1286,7 +818,6 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
tax_configuration=channel_USD.tax_configuration,
manager=manager,
lines=[],
- shipping_channel_listings=[],
discounts=[],
)
with pytest.raises(NotApplicable):
@@ -1299,172 +830,194 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
)
- (
- "is_shipping_required",
- "shipping_method_data",
- "discount_value",
- "discount_type",
- "countries",
- "min_spent_amount",
- "min_checkout_items_quantity",
- "subtotal",
- "total_quantity",
- "error_msg",
- ),
- [
- (
- True,
- ShippingMethodData("1", "test", Money(10, "USD")),
- 10,
- DiscountValueType.FIXED,
- ["US"],
- None,
- None,
- Money(10, "USD"),
- 10,
- "This offer is not valid in your country.",
- ),
- (
- True,
- None,
- 10,
- DiscountValueType.FIXED,
- [],
- None,
- None,
- Money(10, "USD"),
- 10,
- "Please select a delivery method first.",
- ),
- (
- False,
- None,
- 10,
- DiscountValueType.FIXED,
- [],
- None,
- None,
- Money(10, "USD"),
- 10,
- "Your order does not require shipping.",
- ),
- (
- True,
- ShippingMethodData("1", "test", Money(10, "USD")),
- 10,
- DiscountValueType.FIXED,
- [],
- 5,
- None,
- Money(2, "USD"),
- 10,
- "This offer is only valid for orders over 5.00 USD.",
- ),
- (
- True,
- ShippingMethodData("1", "test", Money(10, "USD")),
- 10,
- DiscountValueType.FIXED,
- [],
- 5,
- 10,
- Money(5, "USD"),
- 9,
- "This offer is only valid for orders with a minimum of 10 quantity.",
- ),
- (
- True,
- ShippingMethodData("1", "test", Money(10, "USD")),
- 10,
- DiscountValueType.FIXED,
- [],
- 5,
- 10,
- Money(2, "USD"),
- 9,
- "This offer is only valid for orders over 5.00 USD.",
- ),
- ],
-)
-def test_get_discount_for_checkout_shipping_voucher_not_applicable(
- is_shipping_required,
- shipping_method,
- shipping_method_data,
- discount_value,
- discount_type,
- countries,
- min_spent_amount,
- min_checkout_items_quantity,
- subtotal,
- total_quantity,
- error_msg,
- monkeypatch,
- channel_USD,
+def test_get_discount_for_checkout_shipping_voucher_not_applicable_missing_delivery(
+ checkout_with_items,
):
- monkeypatch.setattr(
- "saleor.checkout.base_calculations.base_checkout_subtotal",
- lambda *args: subtotal,
+ # given
+ voucher = Voucher.objects.create(
+ type=VoucherType.SHIPPING,
+ discount_value_type=DiscountValueType.FIXED,
)
- monkeypatch.setattr(
- "saleor.checkout.utils.is_shipping_required", lambda lines: is_shipping_required
+ VoucherCode.objects.create(code="unique", voucher=voucher)
+
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=checkout_with_items.channel,
+ discount=Money(10, checkout_with_items.currency),
)
+ assert checkout_with_items.assigned_delivery is None
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
+
+ # when
+ with pytest.raises(NotApplicable) as e:
+ get_voucher_discount_for_checkout(
+ manager,
+ voucher,
+ checkout_info,
+ lines,
+ checkout_with_items.shipping_address,
+ )
+ # then
+ assert str(e.value) == "Please select a delivery method first."
- if shipping_method_data:
- shipping_channel_listings = shipping_method.channel_listings.all()
- else:
- shipping_method = None
- shipping_channel_listings = []
- meta_storage_mock = Mock()
- meta_storage_mock.get_value_from_private_metadata.return_value = None
- checkout = Mock(
- is_shipping_required=Mock(return_value=is_shipping_required),
- shipping_method=shipping_method,
- shipping_address=Mock(spec=Address, country=Mock(code="PL")),
- quantity=total_quantity,
- spec=Checkout,
- channel=channel_USD,
- metadata_storage=meta_storage_mock,
- external_shipping_method_id=None,
+def test_get_discount_for_checkout_shipping_voucher_not_applicable_delivery_not_required(
+ checkout_with_digital_item,
+):
+ # given
+ checkout = checkout_with_digital_item
+ voucher = Voucher.objects.create(
+ type=VoucherType.SHIPPING,
+ discount_value_type=DiscountValueType.FIXED,
+ )
+ VoucherCode.objects.create(code="unique", voucher=voucher)
+
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=checkout.channel,
+ discount=Money(10, checkout.currency),
)
+ assert checkout.assigned_delivery is None
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ with pytest.raises(NotApplicable) as e:
+ get_voucher_discount_for_checkout(
+ manager,
+ voucher,
+ checkout_info,
+ lines,
+ checkout.shipping_address,
+ )
+ # then
+ assert str(e.value) == "Your order does not require shipping."
+
+
+def test_get_discount_for_checkout_shipping_voucher_not_applicable_in_country(
+ checkout_with_items, checkout_delivery, address
+):
+ # given
+ assert address.country.code != "US"
+ checkout_with_items.shipping_address = address
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
+ checkout_with_items.save()
voucher = Voucher.objects.create(
type=VoucherType.SHIPPING,
- discount_value_type=discount_type,
- min_checkout_items_quantity=min_checkout_items_quantity,
- countries=countries,
+ discount_value_type=DiscountValueType.FIXED,
+ countries=["US"],
+ )
+ VoucherCode.objects.create(code="unique", voucher=voucher)
+
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=checkout_with_items.channel,
+ discount=Money(10, checkout_with_items.currency),
+ )
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
+
+ # when
+ with pytest.raises(NotApplicable) as e:
+ get_voucher_discount_for_checkout(
+ manager,
+ voucher,
+ checkout_info,
+ lines,
+ checkout_with_items.shipping_address,
+ )
+ # then
+ assert str(e.value) == "This offer is not valid in your country."
+
+
+def test_get_discount_for_checkout_shipping_voucher_not_applicable_spent_not_enough(
+ checkout_with_items, checkout_delivery, address
+):
+ # given
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
+ checkout_with_items.save()
+
+ voucher = Voucher.objects.create(
+ type=VoucherType.SHIPPING,
+ discount_value_type=DiscountValueType.FIXED,
)
VoucherCode.objects.create(code="unique", voucher=voucher)
+
manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
+
+ total = base_calculations.base_checkout_total(
+ checkout_info,
+ lines,
+ )
VoucherChannelListing.objects.create(
voucher=voucher,
- channel=channel_USD,
- discount=Money(discount_value, channel_USD.currency_code),
- min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ channel=checkout_with_items.channel,
+ discount=Money(10, checkout_with_items.currency),
+ min_spent_amount=total.amount * 2,
)
- checkout_info = CheckoutInfo(
- checkout=checkout,
- shipping_address=Mock(spec=Address, country=Mock(code="PL")),
- billing_address=None,
- channel=channel_USD,
- user=None,
- tax_configuration=channel_USD.tax_configuration,
- manager=manager,
- lines=[],
- shipping_method=shipping_method,
- shipping_channel_listings=shipping_channel_listings,
- discounts=[],
+
+ # when
+ with pytest.raises(NotApplicable) as e:
+ get_voucher_discount_for_checkout(
+ manager,
+ voucher,
+ checkout_info,
+ lines,
+ checkout_with_items.shipping_address,
+ )
+ # then
+ assert str(e.value) == "This offer is only valid for orders over 160.00 USD."
+
+
+def test_get_discount_for_checkout_shipping_voucher_not_applicable_minimum_quantity_not_reached(
+ checkout_with_items, checkout_delivery, address
+):
+ # given
+ checkout_with_items.shipping_address = address
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
+ checkout_with_items.save()
+
+ voucher = Voucher.objects.create(
+ type=VoucherType.SHIPPING,
+ discount_value_type=DiscountValueType.FIXED,
+ min_checkout_items_quantity=10,
+ )
+ VoucherCode.objects.create(code="unique", voucher=voucher)
+
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=checkout_with_items.channel,
+ discount=Money(10, checkout_with_items.currency),
)
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
+
+ # when
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(
manager,
voucher,
checkout_info,
- [],
- checkout.shipping_address,
+ lines,
+ checkout_with_items.shipping_address,
)
- assert str(e.value) == error_msg
+ # then
+ assert (
+ str(e.value)
+ == "This offer is only valid for orders with a minimum of 10 quantity."
+ )
def test_get_voucher_for_checkout_info(checkout_with_voucher, voucher):
@@ -1831,26 +1384,28 @@ def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, vo
def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping(
checkout_with_voucher_free_shipping,
- shipping_method,
- channel_USD,
):
+ # given
checkout = checkout_with_voucher_free_shipping
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- channel_listing = shipping_method.channel_listings.get(channel_id=channel_USD.id)
- channel_listing.price = calculations.checkout_subtotal(
+
+ checkout.assigned_delivery.price = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
address=checkout.shipping_address,
).gross + Money("10.00", "USD")
- channel_listing.save()
+ checkout.assigned_delivery.save()
checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
recalculate_checkout_discount(manager, checkout_info, lines)
- assert checkout.discount == channel_listing.price
+ # then
+ assert checkout.discount == checkout.assigned_delivery.price
assert checkout.discount_name == "Free shipping"
checkout_total = calculations.calculate_checkout_total(
manager=manager,
@@ -1872,23 +1427,27 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shippi
shipping_method,
channel_USD,
):
+ # given
checkout = checkout_with_voucher_free_shipping
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- channel_listing = shipping_method.channel_listings.get(channel=channel_USD)
- channel_listing.price = calculations.checkout_subtotal(
+
+ checkout.assigned_delivery.price = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
address=checkout.shipping_address,
- ).gross - Money("1.00", "USD")
- channel_listing.save()
+ ).gross - Money("10.00", "USD")
+ checkout.assigned_delivery.save()
checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
recalculate_checkout_discount(manager, checkout_info, lines)
- assert checkout.discount == channel_listing.price
+ # then
+ assert checkout.discount == checkout.assigned_delivery.price
assert checkout.discount_name == "Free shipping"
checkout_total = calculations.calculate_checkout_total(
manager=manager,
@@ -1957,8 +1516,6 @@ def test_change_address_in_checkout(checkout, address):
checkout_info,
address,
store_shipping_address_in_user_addresses,
- lines,
- checkout.channel.shipping_method_listings.all(),
)
billing_updated_fields = change_billing_address_in_checkout(
checkout, address, store_billing_address_in_user_addresses
@@ -1987,8 +1544,6 @@ def test_change_address_in_checkout_to_none(checkout, address):
checkout_info,
None,
store_shipping_address_in_user_addresses,
- lines,
- checkout.channel.shipping_method_listings.all(),
)
billing_updated_fields = change_billing_address_in_checkout(
checkout, None, store_billing_address_in_user_addresses
@@ -2019,8 +1574,6 @@ def test_change_address_in_checkout_to_same(checkout, address):
checkout_info,
address,
store_shipping_address_in_user_addresses,
- lines,
- checkout.channel.shipping_method_listings.all(),
)
billing_updated_fields = change_billing_address_in_checkout(
checkout, address, store_billing_address_in_user_addresses
@@ -2051,8 +1604,6 @@ def test_change_address_in_checkout_to_other(checkout, address):
checkout_info,
other_address,
store_shipping_address_in_user_addresses,
- lines,
- checkout.channel.shipping_method_listings.all(),
)
billing_updated_fields = change_billing_address_in_checkout(
checkout, other_address, store_billing_address_in_user_addresses
@@ -2087,8 +1638,6 @@ def test_change_address_in_checkout_from_user_address_to_other(
checkout_info,
other_address,
store_shipping_address_in_user_addresses,
- lines,
- checkout.channel.shipping_method_listings.all(),
)
billing_updated_fields = change_billing_address_in_checkout(
checkout, other_address, store_billing_address_in_user_addresses
@@ -2104,46 +1653,6 @@ def test_change_address_in_checkout_from_user_address_to_other(
assert checkout.save_billing_address == store_billing_address_in_user_addresses
-def test_change_address_in_checkout_invalidates_shipping_methods(
- checkout_with_items, address, shipping_method, shipping_zone
-):
- # given
- checkout = checkout_with_items
- store_address_in_user_addresses = True
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout=checkout,
- lines=lines,
- manager=manager,
- shipping_channel_listings=shipping_method.channel_listings.all(),
- )
-
- all_shipping_methods = checkout_info.get_all_shipping_methods()
- assert all_shipping_methods == []
-
- # when
- shipping_updated_fields = change_shipping_address_in_checkout(
- checkout_info,
- address,
- store_address_in_user_addresses,
- lines,
- checkout.channel.shipping_method_listings.all(),
- )
- billing_updated_fields = change_billing_address_in_checkout(
- checkout, address, store_address_in_user_addresses
- )
- checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)
- checkout.refresh_from_db()
-
- # then
- assert checkout.shipping_address == address
- assert checkout.billing_address == address
- assert checkout_info.shipping_address == address
- assert checkout_info.get_all_shipping_methods()
-
-
def test_add_voucher_to_checkout(checkout_with_item, voucher):
assert checkout_with_item.voucher_code is None
manager = get_plugins_manager(allow_replica=False)
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 5d73158ef0..0e48dd9011 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -50,7 +50,6 @@ def test_create_order_captured_payment_creates_expected_events(
mock_notify,
checkout_with_item,
customer_user,
- shipping_method,
payment_txn_captured,
channel_USD,
site_settings,
@@ -67,7 +66,6 @@ def test_create_order_captured_payment_creates_expected_events(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_shipping_address
- checkout.shipping_method = shipping_method
checkout.payments.add(payment_txn_captured)
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
@@ -214,7 +212,6 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(
mock_notify,
checkout_with_item,
customer_user,
- shipping_method,
payment_txn_captured,
channel_USD,
site_settings,
@@ -232,7 +229,6 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(
checkout.email = "[email protected]"
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_shipping_address
- checkout.shipping_method = shipping_method
checkout.payments.add(payment_txn_captured)
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
@@ -375,7 +371,6 @@ def test_create_order_preauth_payment_creates_expected_events(
mock_notify,
checkout_with_item,
customer_user,
- shipping_method,
payment_txn_preauth,
channel_USD,
site_settings,
@@ -392,7 +387,6 @@ def test_create_order_preauth_payment_creates_expected_events(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_shipping_address
- checkout.shipping_method = shipping_method
checkout.payments.add(payment_txn_preauth)
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
@@ -491,7 +485,6 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
mock_notify,
checkout_with_item,
customer_user,
- shipping_method,
payment_txn_preauth,
channel_USD,
site_settings,
@@ -509,7 +502,6 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
checkout.email = "[email protected]"
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_shipping_address
- checkout.shipping_method = shipping_method
checkout.payments.add(payment_txn_preauth)
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
@@ -622,13 +614,13 @@ def test_create_order_insufficient_stock(
def test_create_order_doesnt_duplicate_order(
- checkout_with_item, customer_user, shipping_method
+ checkout_with_item,
+ customer_user,
):
checkout = checkout_with_item
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -666,14 +658,13 @@ def test_create_order_doesnt_duplicate_order(
@pytest.mark.parametrize("is_anonymous_user", [True, False])
def test_create_order_with_gift_card(
- checkout_with_gift_card, customer_user, shipping_method, is_anonymous_user
+ checkout_with_gift_card, customer_user, is_anonymous_user
):
checkout_user = None if is_anonymous_user else customer_user
checkout = checkout_with_gift_card
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -723,13 +714,14 @@ def test_create_order_with_gift_card(
def test_create_order_with_gift_card_partial_use(
- checkout_with_item, gift_card_used, customer_user, shipping_method
+ checkout_with_item,
+ gift_card_used,
+ customer_user,
):
checkout = checkout_with_item
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -782,13 +774,11 @@ def test_create_order_with_many_gift_cards(
gift_card_created_by_staff,
gift_card,
customer_user,
- shipping_method,
):
checkout = checkout_with_item
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -850,7 +840,6 @@ def test_create_order_gift_card_bought(
checkout_with_gift_card_items,
payment_txn_captured,
customer_user,
- shipping_method,
is_anonymous_user,
non_shippable_gift_card_product,
django_capture_on_commit_callbacks,
@@ -861,7 +850,6 @@ def test_create_order_gift_card_bought(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -944,7 +932,6 @@ def test_create_order_gift_card_bought_order_not_captured_gift_cards_not_sent(
send_notification_mock,
checkout_with_gift_card_items,
customer_user,
- shipping_method,
is_anonymous_user,
django_capture_on_commit_callbacks,
):
@@ -955,7 +942,6 @@ def test_create_order_gift_card_bought_order_not_captured_gift_cards_not_sent(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -1007,7 +993,6 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
checkout,
shippable_gift_card_product,
customer_user,
- shipping_method,
is_anonymous_user,
):
checkout_user = None if is_anonymous_user else customer_user
@@ -1020,7 +1005,6 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -1067,7 +1051,6 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
site_settings,
checkout_with_gift_card_items,
customer_user,
- shipping_method,
is_anonymous_user,
non_shippable_gift_card_product,
):
@@ -1080,7 +1063,6 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -1181,7 +1163,8 @@ def test_create_order_with_variant_tracking_false(
@override_settings(LANGUAGE_CODE="fr")
def test_create_order_use_translations(
- checkout_with_item, customer_user, shipping_method
+ checkout_with_item,
+ customer_user,
):
translated_product_name = "French name"
translated_variant_name = "French variant name"
@@ -1190,7 +1173,6 @@ def test_create_order_use_translations(
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
checkout.language_code = "fr"
@@ -1837,7 +1819,9 @@ def test_complete_checkout_checkout_completed_in_the_meantime(
def test_process_shipping_data_for_order_store_customer_shipping_address(
- checkout_with_item, customer_user, address_usa, shipping_method
+ checkout_with_item,
+ customer_user,
+ address_usa,
):
# given
checkout = checkout_with_item
@@ -1845,7 +1829,6 @@ def test_process_shipping_data_for_order_store_customer_shipping_address(
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = address_usa
- checkout.shipping_method = shipping_method
checkout.save()
user_address_count = customer_user.addresses.count()
@@ -1874,7 +1857,9 @@ def test_process_shipping_data_for_order_store_customer_shipping_address(
def test_process_shipping_data_for_order_not_store_customer_shipping_address_saving_addresses_off(
- checkout_with_item, customer_user, address_usa, shipping_method
+ checkout_with_item,
+ customer_user,
+ address_usa,
):
# given
checkout = checkout_with_item
@@ -1882,7 +1867,6 @@ def test_process_shipping_data_for_order_not_store_customer_shipping_address_sav
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = address_usa
- checkout.shipping_method = shipping_method
checkout.save_shipping_address = False
checkout.save()
@@ -2043,14 +2027,12 @@ def test_create_order_update_display_gross_prices(checkout_with_item, customer_u
def test_create_order_store_shipping_prices(
- checkout_with_items_and_shipping, shipping_method, customer_user
+ checkout_with_items_and_shipping, customer_user
):
# given
checkout = checkout_with_items_and_shipping
- expected_base_shipping_price = shipping_method.channel_listings.get(
- channel=checkout.channel
- ).price
+ expected_base_shipping_price = checkout.assigned_delivery.price
expected_shipping_price = TaxedMoney(
net=expected_base_shipping_price * Decimal("0.9"),
gross=expected_base_shipping_price,
@@ -2102,16 +2084,13 @@ def test_create_order_store_shipping_prices(
def test_create_order_store_shipping_prices_with_free_shipping_voucher(
checkout_with_voucher_free_shipping,
- shipping_method,
customer_user,
):
# given
checkout = checkout_with_voucher_free_shipping
manager = get_plugins_manager(allow_replica=False)
- expected_undiscounted_shipping_price = shipping_method.channel_listings.get(
- channel=checkout.channel
- ).price
+ expected_undiscounted_shipping_price = checkout.assigned_delivery.price
expected_base_shipping_price = zero_money(checkout.currency)
expected_shipping_price = zero_taxed_money(checkout.currency)
expected_shipping_tax_rate = Decimal("0.0")
@@ -2202,7 +2181,8 @@ def test_complete_checkout_invalid_shipping_method(
checkout.save()
# make the current shipping method invalid
- checkout.shipping_method.channel_listings.filter(channel=checkout.channel).delete()
+ checkout.assigned_delivery.is_valid = False
+ checkout.assigned_delivery.save()
voucher.apply_once_per_customer = True
voucher.save()
@@ -2516,7 +2496,7 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
mocked_get_tax_calculation_strategy_for_checkout,
customer_user,
checkout_with_item,
- shipping_method,
+ checkout_delivery,
app,
address,
payment_dummy,
@@ -2552,7 +2532,7 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
checkout.price_expiration = timezone.now() + datetime.timedelta(hours=2)
@@ -2787,7 +2767,7 @@ def test_complete_checkout_fail_handler_with_voucher_and_payment(
def test_checkout_complete_with_voucher_0_total(
- shipping_method,
+ checkout_delivery,
checkout_with_item,
customer_user,
voucher_percentage,
@@ -2798,7 +2778,7 @@ def test_checkout_complete_with_voucher_0_total(
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -2809,9 +2789,9 @@ def test_checkout_complete_with_voucher_0_total(
voucher_listing.discount_value = 100
voucher_listing.save(update_fields=["discount_value"])
- shipping_listing = shipping_method.channel_listings.get(channel=channel)
- shipping_listing.price_amount = 0
- shipping_listing.save(update_fields=["price_amount"])
+ checkout.assigned_delivery.price_amount = Decimal("0.0")
+ checkout.assigned_delivery.save(update_fields=["price_amount"])
+
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
diff --git a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
index 17cc307c8a..89be016b35 100644
--- a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
+++ b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
@@ -1,16 +1,9 @@
from decimal import Decimal
-from prices import Money
-
-from ...shipping.interface import ShippingMethodData
from ..utils import (
- PRIVATE_META_APP_SHIPPING_ID,
- assign_built_in_shipping_to_checkout,
assign_collection_point_to_checkout,
- assign_external_shipping_to_checkout,
- get_external_shipping_id,
+ assign_shipping_method_to_checkout,
remove_delivery_method_from_checkout,
- remove_external_shipping_from_checkout,
)
@@ -34,37 +27,21 @@ def test_remove_delivery_method_from_checkout_with_cc(
assert checkout_with_delivery_method_for_cc.shipping_address_id is None
-def test_remove_delivery_method_from_checkout_with_external_shipping(
- checkout_with_item,
-):
- # given
- checkout_with_item.external_shipping_method_id = "abd"
- checkout_with_item.shipping_method_name = "Ext shipping"
-
- expected_updated_fields = {"shipping_method_name", "external_shipping_method_id"}
- # when
- updated_fields = remove_delivery_method_from_checkout(checkout_with_item)
-
- # then
- assert expected_updated_fields == set(updated_fields)
- assert checkout_with_item.external_shipping_method_id is None
- assert checkout_with_item.shipping_method_name is None
-
-
-def test_remove_delivery_method_from_checkout_with_built_in_shipping(
- checkout_with_item, shipping_method
+def test_remove_delivery_method_from_checkout_with_shipping(
+ checkout_with_item, checkout_delivery
):
# given
- checkout_with_item.shipping_method = shipping_method
- checkout_with_item.shipping_method_name = shipping_method.name
+ assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.assigned_delivery = assigned_delivery
+ checkout_with_item.shipping_method_name = assigned_delivery.name
- expected_updated_fields = {"shipping_method_id", "shipping_method_name"}
+ expected_updated_fields = {"assigned_delivery_id", "shipping_method_name"}
# when
updated_fields = remove_delivery_method_from_checkout(checkout_with_item)
# then
assert expected_updated_fields == set(updated_fields)
- assert checkout_with_item.shipping_method is None
+ assert checkout_with_item.assigned_delivery is None
assert checkout_with_item.shipping_method_name is None
@@ -79,297 +56,94 @@ def test_remove_delivery_method_from_checkout_without_method(checkout_with_item)
assert expected_updated_fields == updated_fields
-def test_assign_external_shipping_to_checkout_with_cc(
- checkout_with_delivery_method_for_cc,
-):
- # given
- app_shipping_id = "abcd"
- app_shipping_name = "Shipping"
- external_shipping_data = ShippingMethodData(
- name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
- )
- checkout = checkout_with_delivery_method_for_cc
-
- expected_updated_fields = {
- "external_shipping_method_id",
- "shipping_method_name",
- "collection_point_id",
- "shipping_address_id",
- "save_shipping_address",
- }
-
- # when
- fields_to_updated = assign_external_shipping_to_checkout(
- checkout, external_shipping_data
- )
-
- # then
- assert expected_updated_fields == set(fields_to_updated)
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id == app_shipping_id
- assert checkout.shipping_method_name == app_shipping_name
- assert checkout.collection_point_id is None
- assert checkout.shipping_address_id is None
-
-
-def test_assign_external_shipping_to_checkout_without_delivery_method(checkout):
- # given
- app_shipping_id = "abcd"
- app_shipping_name = "Shipping"
- external_shipping_data = ShippingMethodData(
- name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
- )
-
- expected_updated_fields = {
- "external_shipping_method_id",
- "shipping_method_name",
- }
-
- # when
- fields_to_updated = assign_external_shipping_to_checkout(
- checkout, external_shipping_data
- )
-
- # then
- assert expected_updated_fields == set(fields_to_updated)
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id == app_shipping_id
- assert checkout.shipping_method_name == app_shipping_name
-
-
-def test_assign_external_shipping_to_checkout_with_built_in_shipping(
- checkout_with_item, shipping_method
-):
- # given
- app_shipping_id = "abcd"
- app_shipping_name = "Shipping"
- external_shipping_data = ShippingMethodData(
- name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
- )
- checkout_with_item.shipping_method = shipping_method
- checkout = checkout_with_item
-
- expected_updated_fields = {
- "external_shipping_method_id",
- "shipping_method_name",
- "shipping_method_id",
- }
-
- # when
- fields_to_updated = assign_external_shipping_to_checkout(
- checkout, external_shipping_data
- )
-
- # then
- assert expected_updated_fields == set(fields_to_updated)
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id == app_shipping_id
- assert checkout.shipping_method_name == app_shipping_name
- assert checkout.shipping_method_id is None
-
-
-def test_assign_external_shipping_to_checkout_with_different_external_shipping(
- checkout_with_item,
-):
- # given
- app_shipping_id = "abcd"
- app_shipping_name = "Shipping"
- external_shipping_data = ShippingMethodData(
- name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
- )
- checkout = checkout_with_item
- checkout.external_shipping_method_id = "different-shipp"
- checkout.shipping_method_name = "Ext shipping"
-
- expected_updated_fields = {
- "external_shipping_method_id",
- "shipping_method_name",
- }
-
- # when
- fields_to_updated = assign_external_shipping_to_checkout(
- checkout, external_shipping_data
- )
-
- # then
- assert expected_updated_fields == set(fields_to_updated)
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id == app_shipping_id
- assert checkout.shipping_method_name == app_shipping_name
-
-
-def test_assign_external_shipping_to_checkout_with_the_same_shipping_method(
- checkout_with_item, shipping_method
-):
- # given
- app_shipping_id = "abcd"
- app_shipping_name = "Shipping"
- external_shipping_data = ShippingMethodData(
- name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
- )
- checkout = checkout_with_item
- checkout.external_shipping_method_id = app_shipping_id
- checkout.shipping_method_name = app_shipping_name
-
- # when
- fields_to_updated = assign_external_shipping_to_checkout(
- checkout, external_shipping_data
- )
-
- # then
- assert not fields_to_updated
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id == app_shipping_id
- assert checkout.shipping_method_name == app_shipping_name
-
-
-def test_assign_built_in_shipping_to_checkout_without_delivery_method(
- checkout, shipping_method
+def test_assign_shipping_to_checkout_without_delivery_method(
+ checkout, checkout_delivery
):
# given
expected_updated_fields = {
- "shipping_method_id",
+ "assigned_delivery_id",
"shipping_method_name",
"undiscounted_base_shipping_price_amount",
}
- shipping_method_data = ShippingMethodData(
- id=str(shipping_method.id),
- name=shipping_method.name,
- price=Money(10, checkout.currency),
- )
+ assigned_delivery = checkout_delivery(checkout=checkout)
+
# when
- fields_to_update = assign_built_in_shipping_to_checkout(
- checkout, shipping_method_data
- )
+ fields_to_update = assign_shipping_method_to_checkout(checkout, assigned_delivery)
# then
assert expected_updated_fields == set(fields_to_update)
- assert checkout.shipping_method == shipping_method
- assert checkout.shipping_method_name == shipping_method.name
+ assert checkout.assigned_delivery == assigned_delivery
+ assert checkout.shipping_method_name == assigned_delivery.name
-def test_assign_built_in_shipping_to_checkout_with_cc(
- checkout_with_delivery_method_for_cc, shipping_method
+def test_assign_shipping_to_checkout_with_cc(
+ checkout_with_delivery_method_for_cc, checkout_delivery
):
# given
checkout = checkout_with_delivery_method_for_cc
expected_updated_fields = {
- "shipping_method_id",
+ "assigned_delivery_id",
"shipping_method_name",
"collection_point_id",
"shipping_address_id",
"undiscounted_base_shipping_price_amount",
"save_shipping_address",
}
- shipping_method_data = ShippingMethodData(
- id=str(shipping_method.id),
- name=shipping_method.name,
- price=Money(10, checkout.currency),
- )
+
+ assigned_delivery = checkout_delivery(checkout=checkout)
# when
- fields_to_update = assign_built_in_shipping_to_checkout(
- checkout, shipping_method_data
- )
+ fields_to_update = assign_shipping_method_to_checkout(checkout, assigned_delivery)
assert expected_updated_fields == set(fields_to_update)
- assert checkout.shipping_method == shipping_method
- assert checkout.shipping_method_name == shipping_method.name
+ assert checkout.assigned_delivery == assigned_delivery
+ assert checkout.shipping_method_name == assigned_delivery.name
assert checkout.collection_point_id is None
assert checkout.shipping_address_id is None
-def test_assign_built_in_shipping_to_checkout_with_external_shipping_method(
- checkout, shipping_method
+def test_assign_shipping_to_checkout_with_different_shipping_method(
+ checkout, shipping_method, shipping_method_weight_based, checkout_delivery
):
# given
- checkout.external_shipping_method_id = "ext-id"
- checkout.shipping_method_name = "Ext default"
- expected_updated_fields = {
- "shipping_method_id",
- "shipping_method_name",
- "external_shipping_method_id",
- "undiscounted_base_shipping_price_amount",
- }
- shipping_method_data = ShippingMethodData(
- id=str(shipping_method.id),
- name=shipping_method.name,
- price=Money(10, checkout.currency),
+ checkout.assigned_delivery = checkout_delivery(
+ checkout, shipping_method_weight_based
)
-
- # when
- fields_to_update = assign_built_in_shipping_to_checkout(
- checkout, shipping_method_data
- )
- assert expected_updated_fields == set(fields_to_update)
- assert checkout.shipping_method == shipping_method
- assert checkout.shipping_method_name == shipping_method.name
- assert checkout.external_shipping_method_id is None
-
-
-def test_assign_built_in_shipping_to_checkout_with_different_shipping_method(
- checkout, shipping_method, shipping_method_weight_based
-):
- # given
- checkout.shipping_method = shipping_method_weight_based
checkout.shipping_method_name = shipping_method_weight_based.name
- shipping_method_data = ShippingMethodData(
- id=str(shipping_method.id),
- name=shipping_method.name,
- price=Money(10, checkout.currency),
- )
+ assigned_delivery = checkout_delivery(checkout=checkout)
expected_updated_fields = {
- "shipping_method_id",
+ "assigned_delivery_id",
"shipping_method_name",
"undiscounted_base_shipping_price_amount",
}
# when
- fields_to_update = assign_built_in_shipping_to_checkout(
- checkout, shipping_method_data
- )
+ fields_to_update = assign_shipping_method_to_checkout(checkout, assigned_delivery)
# then
assert expected_updated_fields == set(fields_to_update)
- assert checkout.shipping_method == shipping_method
+ assert checkout.assigned_delivery == assigned_delivery
assert checkout.shipping_method_name == shipping_method.name
-def test_assign_built_in_shipping_to_checkout_with_the_same_shipping_method(
- checkout, shipping_method
+def test_assign_shipping_to_checkout_with_the_same_shipping_method(
+ checkout, checkout_delivery
):
# given
+ assigned_delivery = checkout_delivery(checkout=checkout)
shipping_price_amount = Decimal(10)
- checkout.shipping_method = shipping_method
- checkout.shipping_method_name = shipping_method.name
+ checkout.assigned_delivery = assigned_delivery
+ checkout.shipping_method_name = assigned_delivery.name
checkout.undiscounted_base_shipping_price_amount = shipping_price_amount
- shipping_method_data = ShippingMethodData(
- id=str(shipping_method.id),
- name=shipping_method.name,
- price=Money(shipping_price_amount, checkout.currency),
- )
-
# when
- fields_to_update = assign_built_in_shipping_to_checkout(
- checkout, shipping_method_data
- )
+ fields_to_update = assign_shipping_method_to_checkout(checkout, assigned_delivery)
# then
assert not fields_to_update
- assert checkout.shipping_method == shipping_method
- assert checkout.shipping_method_name == shipping_method.name
+ assert checkout.assigned_delivery == assigned_delivery
+ assert checkout.shipping_method_name == assigned_delivery.name
def test_assign_collection_point_to_checkout_without_delivery_method(
@@ -394,46 +168,19 @@ def test_assign_collection_point_to_checkout_without_delivery_method(
assert int(checkout.shipping_address_id) != int(collection_point.address.id)
-def test_assign_collection_point_to_checkout_with_external_shipping_method(
- checkout, warehouses_for_cc
-):
- # given
- checkout.external_shipping_method_id = "ext-id"
- checkout.shipping_method_name = "Ext default"
-
- collection_point = warehouses_for_cc[0]
- expected_updated_fields = {
- "collection_point_id",
- "shipping_address_id",
- "external_shipping_method_id",
- "shipping_method_name",
- "save_shipping_address",
- }
-
- # when
- fields_to_update = assign_collection_point_to_checkout(checkout, collection_point)
-
- # then
- assert expected_updated_fields == set(fields_to_update)
- 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.external_shipping_method_id is None
- assert checkout.shipping_method_name is None
-
-
def test_assign_collection_point_to_checkout_with_shipping_method(
- checkout, shipping_method_weight_based, warehouses_for_cc
+ checkout, checkout_delivery, warehouses_for_cc
):
# given
- checkout.shipping_method = shipping_method_weight_based
- checkout.shipping_method_name = shipping_method_weight_based.name
+ assigned_delivery = checkout_delivery(checkout)
+ checkout.assigned_delivery = assigned_delivery
+ checkout.shipping_method_name = assigned_delivery.name
collection_point = warehouses_for_cc[0]
expected_updated_fields = {
"collection_point_id",
"shipping_address_id",
- "shipping_method_id",
+ "assigned_delivery_id",
"shipping_method_name",
"save_shipping_address",
}
@@ -446,7 +193,7 @@ def test_assign_collection_point_to_checkout_with_shipping_method(
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.shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.shipping_method_name is None
@@ -497,72 +244,3 @@ def test_assign_collection_point_to_checkout_with_the_same_cc(
assert checkout.collection_point == collection_point
assert checkout.shipping_address == collection_point.address
assert int(checkout.shipping_address_id) != int(collection_point.address.id)
-
-
-def test_get_external_shipping_id_from_metadata(checkout):
- # given
- app_shipping_id = "abcd"
- initial_private_metadata = {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
-
- # when
- shipping_id = get_external_shipping_id(checkout)
-
- # then
- assert shipping_id == app_shipping_id
-
-
-def test_get_external_shipping_id(checkout):
- # given
- app_shipping_id = "abcd"
- checkout.external_shipping_method_id = app_shipping_id
-
- # when
- shipping_id = get_external_shipping_id(checkout)
-
- # then
- assert shipping_id == app_shipping_id
-
-
-def test_remove_external_shipping_from_checkout(checkout):
- # given
- app_shipping_id = "abcd"
- expected_private_metadata = {"test": "123"}
- initial_private_metadata = {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
- checkout.external_shipping_method_id = app_shipping_id
-
- initial_private_metadata.update(expected_private_metadata)
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
-
- # when
- remove_external_shipping_from_checkout(checkout)
-
- # then
- assert checkout.metadata_storage.private_metadata == expected_private_metadata
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_name is None
- assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
-
-
-def test_remove_external_shipping_from_checkout_with_save(checkout):
- # given
- app_shipping_id = "abcd"
- expected_private_metadata = {"test": "123"}
- initial_private_metadata = {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
- checkout.external_shipping_method_id = app_shipping_id
-
- initial_private_metadata.update(expected_private_metadata)
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
-
- # when
- remove_external_shipping_from_checkout(checkout, save=True)
-
- # then
- checkout.refresh_from_db()
- assert checkout.metadata_storage.private_metadata == expected_private_metadata
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_name is None
- assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
diff --git a/saleor/checkout/tests/test_fetch.py b/saleor/checkout/tests/test_fetch.py
index 85aae89fbb..0371173530 100644
--- a/saleor/checkout/tests/test_fetch.py
+++ b/saleor/checkout/tests/test_fetch.py
@@ -1,10 +1,23 @@
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 ...plugins.base_plugin import ExcludedShippingMethod
from ...product.models import ProductChannelListing, ProductVariantChannelListing
-from ..fetch import CheckoutLineInfo, fetch_checkout_lines
+from ...shipping.interface import 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):
@@ -354,3 +367,826 @@ 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.plugins.manager.PluginsManager.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 = [
+ 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")
[email protected]("saleor.plugins.manager.PluginsManager.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 = [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")
[email protected]("saleor.plugins.manager.PluginsManager.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 = [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")
[email protected]("saleor.plugins.manager.PluginsManager.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 = [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")
[email protected]("saleor.plugins.manager.PluginsManager.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 = [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",
+ )
+ 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.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
+)
[email protected]("saleor.plugins.manager.PluginsManager.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 = [
+ ExcludedShippingMethod(
+ id=str(unavailable_shipping_method.id),
+ reason=exclude_reason,
+ )
+ ]
+
+ mocked_list_shipping_methods.return_value = [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")
[email protected]("saleor.plugins.manager.PluginsManager.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)
+
+ 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 = [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/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index 099be3d072..dc87ee0b06 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -58,14 +58,13 @@ def test_create_order_insufficient_stock(
@pytest.mark.parametrize("is_anonymous_user", [True, False])
def test_create_order_with_gift_card(
- checkout_with_gift_card, customer_user, shipping_method, is_anonymous_user, app
+ checkout_with_gift_card, customer_user, is_anonymous_user, app
):
checkout_user = None if is_anonymous_user else customer_user
checkout = checkout_with_gift_card
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -108,13 +107,12 @@ def test_create_order_with_gift_card(
def test_create_order_with_gift_card_partial_use(
- checkout_with_item, gift_card_used, customer_user, shipping_method, app
+ checkout_with_item, gift_card_used, customer_user, app
):
checkout = checkout_with_item
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -163,7 +161,6 @@ def test_create_order_with_many_gift_cards_worth_more_than_total(
gift_card_created_by_staff,
gift_card,
customer_user,
- shipping_method,
app,
):
# given
@@ -231,14 +228,12 @@ def test_create_order_with_many_gift_cards(
gift_card_created_by_staff,
gift_card,
customer_user,
- shipping_method,
app,
):
checkout = checkout_with_item
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -295,7 +290,6 @@ def test_create_order_gift_card_bought(
send_notification_mock,
checkout_with_gift_card_items,
customer_user,
- shipping_method,
is_anonymous_user,
non_shippable_gift_card_product,
app,
@@ -308,7 +302,6 @@ def test_create_order_gift_card_bought(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -375,7 +368,6 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
checkout,
shippable_gift_card_product,
customer_user,
- shipping_method,
is_anonymous_user,
app,
):
@@ -389,7 +381,6 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -429,7 +420,6 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
site_settings,
checkout_with_gift_card_items,
customer_user,
- shipping_method,
is_anonymous_user,
non_shippable_gift_card_product,
app,
@@ -443,7 +433,6 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
checkout.user = checkout_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -477,12 +466,9 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
assert not GiftCard.objects.all()
-def test_note_in_created_order(
- checkout_with_item, address, customer_user, shipping_method, app
-):
+def test_note_in_created_order(checkout_with_item, address, customer_user, app):
checkout_with_item.shipping_address = address
checkout_with_item.billing_address = address
- checkout_with_item.shipping_method = shipping_method
checkout_with_item.note = "test_note"
checkout_with_item.tracking_code = "tracking_code"
checkout_with_item.redirect_url = "https://www.example.com"
@@ -502,9 +488,7 @@ def test_note_in_created_order(
@override_settings(LANGUAGE_CODE="fr")
-def test_create_order_use_translations(
- checkout_with_item, customer_user, shipping_method, app
-):
+def test_create_order_use_translations(checkout_with_item, customer_user, app):
translated_product_name = "French name"
translated_variant_name = "French variant name"
@@ -512,7 +496,6 @@ def test_create_order_use_translations(
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
checkout.language_code = "fr"
@@ -548,12 +531,11 @@ def test_create_order_use_translations(
def test_create_order_from_checkout_updates_total_authorized_amount(
- checkout_with_item, address, customer_user, shipping_method, app
+ checkout_with_item, address, customer_user, app
):
# given
checkout_with_item.shipping_address = address
checkout_with_item.billing_address = address
- checkout_with_item.shipping_method = shipping_method
checkout_with_item.redirect_url = "https://www.example.com"
checkout_with_item.save()
@@ -580,12 +562,11 @@ def test_create_order_from_checkout_updates_total_authorized_amount(
def test_create_order_from_checkout_updates_total_charged_amount(
- checkout_with_item, address, customer_user, shipping_method, app
+ checkout_with_item, address, customer_user, app
):
# given
checkout_with_item.shipping_address = address
checkout_with_item.billing_address = address
- checkout_with_item.shipping_method = shipping_method
checkout_with_item.redirect_url = "https://www.example.com"
checkout_with_item.save()
@@ -695,7 +676,7 @@ def test_create_order_from_checkout_store_shipping_prices(
def test_create_order_from_checkout_valid_undiscounted_prices(
- checkout_with_items_and_shipping, shipping_method, customer_user, app
+ checkout_with_items_and_shipping, customer_user, app
):
# given
checkout = checkout_with_items_and_shipping
@@ -750,7 +731,6 @@ def test_create_order_from_checkout_valid_undiscounted_prices(
def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(
checkout_with_voucher_free_shipping,
- shipping_method,
customer_user,
voucher_free_shipping,
app,
@@ -758,9 +738,7 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(
# given
checkout = checkout_with_voucher_free_shipping
- expected_undiscounted_shipping_price = shipping_method.channel_listings.get(
- channel=checkout.channel
- ).price
+ expected_undiscounted_shipping_price = checkout.assigned_delivery.price
expected_base_shipping_price = zero_money(checkout.currency)
expected_shipping_price = zero_taxed_money(checkout.currency)
expected_shipping_tax_rate = Decimal("0.0")
@@ -804,13 +782,12 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(
def test_note_in_created_order_checkout_line_deleted_in_the_meantime(
- checkout_with_item, address, shipping_method, app, voucher_percentage
+ checkout_with_item, address, app, voucher_percentage
):
# given
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.shipping_address = address
checkout_with_item.billing_address = address
- checkout_with_item.shipping_method = shipping_method
checkout_with_item.tracking_code = "tracking_code"
checkout_with_item.redirect_url = "https://www.example.com"
checkout_with_item.save()
@@ -839,13 +816,12 @@ def test_note_in_created_order_checkout_line_deleted_in_the_meantime(
def test_note_in_created_order_checkout_deleted_in_the_meantime(
- checkout_with_item, address, shipping_method, app, voucher_percentage
+ checkout_with_item, address, app, voucher_percentage
):
# given
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.shipping_address = address
checkout_with_item.billing_address = address
- checkout_with_item.shipping_method = shipping_method
checkout_with_item.tracking_code = "tracking_code"
checkout_with_item.redirect_url = "https://www.example.com"
checkout_with_item.save()
@@ -879,7 +855,6 @@ def test_create_order_from_checkout_update_undiscounted_prices_match(
mock_unit,
mock_total,
checkout_with_items_and_shipping,
- shipping_method,
customer_user,
app,
):
@@ -930,7 +905,6 @@ def test_create_order_from_checkout_update_undiscounted_prices_match(
def test_create_order_product_on_promotion(
checkout_with_item_on_promotion,
customer_user,
- shipping_method,
app,
catalogue_promotion_without_rules,
):
@@ -939,7 +913,6 @@ def test_create_order_product_on_promotion(
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -974,7 +947,6 @@ def test_create_order_product_on_promotion(
def test_create_order_with_voucher_0_total(
checkout_with_item,
customer_user,
- shipping_method,
app,
voucher_percentage,
django_capture_on_commit_callbacks,
@@ -985,7 +957,6 @@ def test_create_order_with_voucher_0_total(
checkout.user = customer_user
checkout.billing_address = customer_user.default_billing_address
checkout.shipping_address = customer_user.default_billing_address
- checkout.shipping_method = shipping_method
checkout.tracking_code = "tracking_code"
checkout.redirect_url = "https://www.example.com"
checkout.save()
@@ -994,10 +965,6 @@ def test_create_order_with_voucher_0_total(
voucher_listing.discount_value = 100
voucher_listing.save(update_fields=["discount_value"])
- shipping_listing = shipping_method.channel_listings.get(channel=checkout.channel)
- shipping_listing.price_amount = 0
- shipping_listing.save(update_fields=["price_amount"])
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 1938fa3b22..ac0ac599d0 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -2,7 +2,7 @@
from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Optional, Union, cast
+from typing import TYPE_CHECKING, Optional, cast
from uuid import UUID
import graphene
@@ -14,7 +14,6 @@ from django.utils import timezone
from prices import Money
from ..account.models import User
-from ..checkout.fetch import update_delivery_method_lists_for_checkout_info
from ..core.db.connection import allow_writer
from ..core.exceptions import (
NonExistingCheckout,
@@ -69,18 +68,16 @@ from .lock_objects import (
checkout_lines_qs_select_for_update,
checkout_qs_select_for_update,
)
-from .models import Checkout, CheckoutLine, CheckoutMetadata
+from .models import Checkout, CheckoutDelivery, CheckoutLine, CheckoutMetadata
if TYPE_CHECKING:
from measurement.measures import Weight
from ..account.models import Address
- from ..core.models import ModelWithMetadata
from ..core.pricing.interface import LineInfo
- from ..order.models import Order, OrderLine
+ from ..order.models import OrderLine
from .fetch import CheckoutInfo, CheckoutLineInfo
-
PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"
@@ -522,8 +519,6 @@ def change_shipping_address_in_checkout(
checkout_info: "CheckoutInfo",
address: "Address",
store_in_user_addresses: bool,
- lines: list["CheckoutLineInfo"],
- shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
):
"""Save shipping address in checkout if changed.
@@ -540,14 +535,7 @@ def change_shipping_address_in_checkout(
if remove and checkout.shipping_address:
checkout.shipping_address.delete()
checkout.shipping_address = address
- update_delivery_method_lists_for_checkout_info(
- checkout_info=checkout_info,
- shipping_method=checkout_info.checkout.shipping_method,
- collection_point=checkout_info.checkout.collection_point,
- shipping_address=address,
- lines=lines,
- shipping_channel_listings=shipping_channel_listings,
- )
+ checkout_info.shipping_address = address
updated_fields = ["shipping_address", "last_change"]
if checkout.save_shipping_address != store_in_user_addresses:
checkout.save_shipping_address = store_in_user_addresses
@@ -998,9 +986,15 @@ def get_valid_internal_shipping_methods_for_checkout_info(
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 checkout_info.shipping_channel_listings
+ listing.shipping_method_id: listing for listing in shipping_channel_listings
}
internal_methods: list[ShippingMethodData] = []
@@ -1042,23 +1036,17 @@ def get_valid_collection_points_for_checkout(
)
-def clear_delivery_method(
+def clear_cc_delivery_method(
checkout_info: "CheckoutInfo", save: bool = True
) -> list[str]:
checkout = checkout_info.checkout
- updated_fields = remove_delivery_method_from_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
- update_delivery_method_lists_for_checkout_info(
- checkout_info=checkout_info,
- shipping_method=None,
- collection_point=None,
- shipping_address=checkout_info.shipping_address,
- lines=checkout_info.lines,
- shipping_channel_listings=checkout_info.shipping_channel_listings,
- )
if updated_fields:
updated_fields.append("last_change")
if save:
@@ -1110,31 +1098,6 @@ def is_shipping_required(lines: list["CheckoutLineInfo"]):
return any(line_info.product_type.is_shipping_required for line_info in lines)
-def validate_variants_in_checkout_lines(lines: list["CheckoutLineInfo"]):
- variants_listings_map = {line.variant.id: line.channel_listing for line in lines}
-
- not_available_variants = [
- variant_id
- for variant_id, channel_listing in variants_listings_map.items()
- if channel_listing is None or channel_listing.price is None
- ]
- if not_available_variants:
- not_available_variants_ids = {
- graphene.Node.to_global_id("ProductVariant", pk)
- for pk in not_available_variants
- }
- error_code = CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value
- raise ValidationError(
- {
- "lines": ValidationError(
- "Cannot add lines with unavailable variants.",
- code=error_code,
- params={"variants": not_available_variants_ids},
- )
- }
- )
-
-
def _remove_external_shipping_from_metadata(checkout: Checkout):
metadata = get_checkout_metadata(checkout)
if not metadata:
@@ -1154,30 +1117,11 @@ def _remove_undiscounted_base_shipping_price(checkout: Checkout):
return []
-def remove_external_shipping_from_checkout(
- checkout: Checkout, save: bool = False
-) -> list[str]:
- fields_to_update = []
- if checkout.external_shipping_method_id:
- checkout.external_shipping_method_id = None
- fields_to_update.append("external_shipping_method_id")
- if checkout.shipping_method_name is not None:
- checkout.shipping_method_name = None
- fields_to_update.append("shipping_method_name")
-
- if save:
- fields_to_update.append("last_change")
- checkout.save(update_fields=fields_to_update)
-
- _remove_external_shipping_from_metadata(checkout)
- return fields_to_update
-
-
-def remove_built_in_shipping_from_checkout(checkout: Checkout) -> list[str]:
+def remove_shipping_method_from_checkout(checkout: Checkout) -> list[str]:
fields_to_update = []
- if checkout.shipping_method_id:
- checkout.shipping_method_id = None
- fields_to_update.append("shipping_method_id")
+ 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")
@@ -1200,75 +1144,53 @@ def remove_click_and_collect_from_checkout(checkout: Checkout) -> list[str]:
def remove_delivery_method_from_checkout(checkout: Checkout) -> list[str]:
fields_to_update = []
fields_to_update += _remove_undiscounted_base_shipping_price(checkout)
- fields_to_update += remove_built_in_shipping_from_checkout(checkout)
+ fields_to_update += remove_shipping_method_from_checkout(checkout)
fields_to_update += remove_click_and_collect_from_checkout(checkout)
- fields_to_update += remove_external_shipping_from_checkout(checkout)
return fields_to_update
def _assign_undiscounted_base_shipping_price_to_checkout(
- checkout, shipping_method_data: ShippingMethodData
+ checkout, checkout_delivery: CheckoutDelivery
):
current_shipping_price = quantize_price(
checkout.undiscounted_base_shipping_price, checkout.currency
)
- new_shipping_price = quantize_price(shipping_method_data.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_external_shipping_to_checkout(
- checkout: Checkout, external_shipping_method_data: ShippingMethodData
+def assign_shipping_method_to_checkout(
+ checkout: Checkout, checkout_delivery: CheckoutDelivery
) -> list[str]:
fields_to_update = []
- fields_to_update += remove_built_in_shipping_from_checkout(checkout)
fields_to_update += remove_click_and_collect_from_checkout(checkout)
fields_to_update += _assign_undiscounted_base_shipping_price_to_checkout(
- checkout, external_shipping_method_data
+ 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.external_shipping_method_id != external_shipping_method_data.id:
- checkout.external_shipping_method_id = external_shipping_method_data.id
- fields_to_update.append("external_shipping_method_id")
- if checkout.shipping_method_name != external_shipping_method_data.name:
- checkout.shipping_method_name = external_shipping_method_data.name
+ 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_built_in_shipping_to_checkout(
- checkout: Checkout, shipping_method_data: ShippingMethodData
-) -> list[str]:
- fields_to_update = []
- fields_to_update += remove_external_shipping_from_checkout(checkout)
- fields_to_update += remove_click_and_collect_from_checkout(checkout)
- fields_to_update += _assign_undiscounted_base_shipping_price_to_checkout(
- checkout, shipping_method_data
- )
-
- if checkout.shipping_method_id != int(shipping_method_data.id):
- checkout.shipping_method_id = shipping_method_data.id
- fields_to_update.append("shipping_method_id")
- if checkout.shipping_method_name != shipping_method_data.name:
- checkout.shipping_method_name = shipping_method_data.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_external_shipping_from_checkout(checkout)
- fields_to_update += remove_built_in_shipping_from_checkout(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")
@@ -1280,25 +1202,6 @@ def assign_collection_point_to_checkout(
return fields_to_update
-def get_external_shipping_id(container: Union["Checkout", "Order"]):
- if isinstance(container, Checkout):
- if container.external_shipping_method_id:
- return container.external_shipping_method_id
- # For order & fallback to previous checkout storage method
- return _get_external_shipping_id_from_meta(container)
-
-
-def _get_external_shipping_id_from_meta(container: Union["Checkout", "Order"]):
- metadata_object: ModelWithMetadata | None
- if isinstance(container, Checkout):
- metadata_object = get_checkout_metadata(container)
- else:
- metadata_object = container
- if not metadata_object:
- return None
- return metadata_object.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)
-
-
@allow_writer()
def create_checkout_metadata(
checkout: "Checkout",
diff --git a/saleor/graphql/checkout/dataloaders/checkout_delivery.py b/saleor/graphql/checkout/dataloaders/checkout_delivery.py
new file mode 100644
index 0000000000..d253c86907
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/checkout_delivery.py
@@ -0,0 +1,30 @@
+from collections import defaultdict
+from uuid import UUID
+
+from ....checkout.models import CheckoutDelivery
+from ...core.dataloaders import DataLoader
+
+
+class CheckoutDeliveryByIdLoader(DataLoader[UUID, CheckoutDelivery]):
+ context_key = "checkout_delivery_by_id"
+
+ def batch_load(self, keys):
+ shipping_methods = CheckoutDelivery.objects.using(
+ self.database_connection_name
+ ).in_bulk(keys)
+ return [shipping_methods.get(key) for key in keys]
+
+
+class CheckoutDeliveriesOnlyValidByCheckoutIdLoader(
+ DataLoader[UUID, list[CheckoutDelivery]]
+):
+ context_key = "checkout_deliveries_by_checkout_id"
+
+ def batch_load(self, keys):
+ shipping_methods = CheckoutDelivery.objects.using(
+ self.database_connection_name
+ ).filter(checkout_id__in=keys, is_valid=True)
+ shipping_methods_map: dict[UUID, list[CheckoutDelivery]] = defaultdict(list)
+ for shipping_method in shipping_methods:
+ shipping_methods_map[shipping_method.checkout_id].append(shipping_method)
+ return [shipping_methods_map[key] for key in keys]
diff --git a/saleor/graphql/checkout/dataloaders/checkout_infos.py b/saleor/graphql/checkout/dataloaders/checkout_infos.py
index 98b36f5c5e..b76af2a8f2 100644
--- a/saleor/graphql/checkout/dataloaders/checkout_infos.py
+++ b/saleor/graphql/checkout/dataloaders/checkout_infos.py
@@ -24,12 +24,9 @@ from ...product.dataloaders import (
ProductVariantByIdLoader,
VariantChannelListingByVariantIdAndChannelIdLoader,
)
-from ...shipping.dataloaders import (
- ShippingMethodByIdLoader,
- ShippingMethodChannelListingByChannelSlugLoader,
-)
from ...tax.dataloaders import TaxClassByVariantIdLoader, TaxConfigurationByChannelId
from ...warehouse.dataloaders import WarehouseByIdLoader
+from .checkout_delivery import CheckoutDeliveryByIdLoader
from .models import CheckoutByTokenLoader, CheckoutLinesByCheckoutTokenLoader
from .promotion_rule_infos import VariantPromotionRuleInfoByCheckoutLineIdLoader
@@ -65,20 +62,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
users = UserByUserIdLoader(self.context).load_many(
[checkout.user_id for checkout in checkouts if checkout.user_id]
)
- shipping_method_ids = [
- checkout.shipping_method_id
- for checkout in checkouts
- if checkout.shipping_method_id
- ]
- shipping_methods = ShippingMethodByIdLoader(self.context).load_many(
- shipping_method_ids
- )
- channel_slugs = [channel.slug for channel in channels]
- shipping_method_channel_listings = (
- ShippingMethodChannelListingByChannelSlugLoader(
- self.context
- ).load_many(channel_slugs)
- )
+
collection_point_ids = [
checkout.collection_point_id
for checkout in checkouts
@@ -101,22 +85,27 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
self.context
).load_many(channel_ids)
+ assigned_deliveries_ids = [
+ checkout.assigned_delivery_id
+ for checkout in checkouts
+ if checkout.assigned_delivery_id
+ ]
+ assigned_deliveries_loader = CheckoutDeliveryByIdLoader(
+ self.context
+ ).load_many(assigned_deliveries_ids)
+
def with_checkout_info(results):
(
addresses,
users,
- shipping_methods,
- listings_for_channels,
collection_points,
voucher_codes,
tax_configurations,
+ assigned_deliveries,
) = results
address_map = {address.id: address for address in addresses}
user_map = {user.id: user for user in users}
- shipping_method_map = {
- shipping_method.id: shipping_method
- for shipping_method in shipping_methods
- }
+
collection_points_map = {
collection_point.id: collection_point
for collection_point in collection_points
@@ -131,6 +120,11 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
tax_configuration.channel_id: tax_configuration
for tax_configuration in tax_configurations
}
+ assigned_deliveries_map = {
+ delivery.id: delivery
+ for delivery in assigned_deliveries
+ if delivery
+ }
checkout_info_map = {}
for (
@@ -147,21 +141,14 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
checkout_discounts,
strict=False,
):
- shipping_method = shipping_method_map.get(
- checkout.shipping_method_id
+ assigned_delivery = assigned_deliveries_map.get(
+ checkout.assigned_delivery_id
)
collection_point = collection_points_map.get(
checkout.collection_point_id
)
voucher_code = voucher_code_map.get(checkout.voucher_code)
- shipping_channel_listings = [
- listing
- for channel_listings in listings_for_channels
- for listing in channel_listings
- if listing.channel_id == channel.id
- ]
-
checkout_info = CheckoutInfo(
checkout=checkout,
user=user_map.get(checkout.user_id),
@@ -178,9 +165,8 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
discounts=discounts,
lines=checkout_lines,
manager=manager,
- shipping_channel_listings=shipping_channel_listings,
- shipping_method=shipping_method,
collection_point=collection_point,
+ assigned_delivery=assigned_delivery,
voucher=voucher_code.voucher if voucher_code else None,
voucher_code=voucher_code,
database_connection_name=self.database_connection_name,
@@ -193,11 +179,10 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
[
addresses,
users,
- shipping_methods,
- shipping_method_channel_listings,
collection_points,
voucher_codes,
tax_configurations,
+ assigned_deliveries_loader,
]
).then(with_checkout_info)
diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
index 94f1c1c0c8..8a80719c7d 100644
--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
@@ -6,9 +6,11 @@ from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
- update_delivery_method_lists_for_checkout_info,
)
-from ....checkout.utils import add_promo_code_to_checkout, invalidate_checkout
+from ....checkout.utils import (
+ add_promo_code_to_checkout,
+ invalidate_checkout,
+)
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
@@ -20,7 +22,10 @@ from ...core.types import CheckoutError
from ...core.utils import WebhookEventInfo
from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Checkout
-from .utils import get_checkout, update_checkout_shipping_method_if_invalid
+from .utils import (
+ get_checkout,
+ mark_checkout_deliveries_as_stale_if_needed,
+)
class CheckoutAddPromoCode(BaseMutation):
@@ -93,10 +98,7 @@ class CheckoutAddPromoCode(BaseMutation):
}
)
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- checkout_info = fetch_checkout_info(
- checkout, lines, manager, shipping_channel_listings
- )
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
add_promo_code_to_checkout(
manager,
@@ -105,18 +107,10 @@ class CheckoutAddPromoCode(BaseMutation):
promo_code,
)
- update_delivery_method_lists_for_checkout_info(
- checkout_info=checkout_info,
- shipping_method=checkout_info.checkout.shipping_method,
- collection_point=checkout_info.checkout.collection_point,
- shipping_address=checkout_info.shipping_address,
- lines=lines,
- shipping_channel_listings=shipping_channel_listings,
+ shipping_update_fields = mark_checkout_deliveries_as_stale_if_needed(
+ checkout_info.checkout, lines
)
- shipping_update_fields = update_checkout_shipping_method_if_invalid(
- checkout_info, lines
- )
invalidate_update_fields = invalidate_checkout(
checkout_info,
lines,
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index ca294acdf9..440a9b2ac5 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -13,6 +13,7 @@ from ....checkout.fetch import (
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
@@ -185,6 +186,9 @@ class CheckoutComplete(BaseMutation, I18nMixin):
billing_address = checkout_info.billing_address
if is_shipping_required(lines):
+ if checkout_info.assigned_delivery:
+ # Refresh stale shipping if needed
+ get_or_fetch_checkout_deliveries(checkout_info)
clean_checkout_shipping(checkout_info, lines, CheckoutErrorCode)
if shipping_address:
shipping_address_data = shipping_address.as_data()
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index de9e9c2c72..eacad8c6ad 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -9,12 +9,10 @@ from ....checkout.fetch import (
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 ....shipping import interface as shipping_interface
-from ....shipping import models as shipping_models
-from ....shipping.interface import ShippingMethodData
-from ....shipping.utils import convert_to_shipping_method_data
from ....warehouse import models as warehouse_models
from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -27,13 +25,10 @@ from ...core.scalars import UUID
from ...core.types import CheckoutError
from ...core.utils import WebhookEventInfo, from_global_id_or_error
from ...plugins.dataloaders import get_plugin_manager_promise
-from ...shipping.types import ShippingMethod
-from ...warehouse.types import Warehouse
from ..types import Checkout
from .utils import (
ERROR_DOES_NOT_SHIP,
assign_delivery_method_to_checkout,
- clean_delivery_method,
get_checkout,
)
@@ -83,94 +78,21 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
]
@classmethod
- def get_collection_point_as_delivery_method_data(
+ def get_collection_point(
cls,
checkout_info: CheckoutInfo,
- delivery_method_id: str,
- info: ResolveInfo,
+ internal_delivery_method_id: str,
) -> warehouse_models.Warehouse:
- collection_point = cls.get_node_or_error(
- info,
- delivery_method_id,
- only_type=Warehouse,
- field="delivery_method_id",
- qs=warehouse_models.Warehouse.objects.select_related("address"),
- )
- return collection_point
-
- @classmethod
- def get_built_in_shipping_method_as_delivery_method_data(
- cls,
- checkout_info: CheckoutInfo,
- shipping_method_id: str,
- info: ResolveInfo,
- ) -> ShippingMethodData:
- shipping_method: shipping_models.ShippingMethod = cls.get_node_or_error(
- info,
- shipping_method_id,
- only_type=ShippingMethod,
- field="delivery_method_id",
- qs=shipping_models.ShippingMethod.objects.prefetch_related(
- "postal_code_rules"
- ),
+ collection_point = (
+ warehouse_models.Warehouse.objects.select_related("address")
+ .filter(pk=internal_delivery_method_id)
+ .first()
)
-
- listing = shipping_models.ShippingMethodChannelListing.objects.filter(
- shipping_method=shipping_method,
- channel=checkout_info.channel,
- ).first()
- if not listing:
- raise ValidationError(
- {
- "delivery_method_id": ValidationError(
- "This shipping method is not applicable in the given channel.",
- code=CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
- delivery_method = convert_to_shipping_method_data(shipping_method, listing)
- return delivery_method
-
- @classmethod
- def get_external_shipping_method_as_delivery_method_data(
- cls,
- checkout_info: CheckoutInfo,
- shipping_method_id: str,
- manager: "PluginsManager",
- ) -> ShippingMethodData:
- delivery_method = manager.get_shipping_method(
- checkout=checkout_info.checkout,
- channel_slug=checkout_info.channel.slug,
- shipping_method_id=shipping_method_id,
- )
-
- if delivery_method is None:
- raise ValidationError(
- {
- "delivery_method_id": ValidationError(
- f"Couldn't resolve to a node: ${shipping_method_id}",
- code=CheckoutErrorCode.NOT_FOUND.value,
- )
- }
- )
- return delivery_method
-
- @staticmethod
- def _check_delivery_method(
- checkout_info,
- lines,
- delivery_method_data: ShippingMethodData | warehouse_models.Warehouse,
- ) -> None:
- delivery_method = delivery_method_data
- if isinstance(delivery_method, warehouse_models.Warehouse):
+ if (
+ not collection_point
+ or collection_point not in checkout_info.valid_pick_up_points
+ ):
error_msg = "This pick up point is not applicable."
- else:
- error_msg = "This shipping method is not applicable."
-
- delivery_method_is_valid = clean_delivery_method(
- checkout_info=checkout_info, method=delivery_method
- )
- if not delivery_method_is_valid:
raise ValidationError(
{
"delivery_method_id": ValidationError(
@@ -179,11 +101,12 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
)
}
)
+ return collection_point
@staticmethod
- def _resolve_delivery_method_type(id_) -> str | None:
+ def _resolve_delivery_method_type(id_) -> tuple[str | None, str | None]:
if id_ is None:
- return None
+ return None, None
possible_types = ("Warehouse", "ShippingMethod", APP_ID_PREFIX)
type_, id_ = from_global_id_or_error(id_)
@@ -199,7 +122,30 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
}
)
- return str_type
+ return str_type, id_
+
+ @classmethod
+ def get_checkout_delivery(
+ cls, checkout_info: CheckoutInfo, internal_shipping_method_id: str | None
+ ) -> CheckoutDelivery | None:
+ if internal_shipping_method_id is None:
+ return None
+
+ checkout_deliveries = get_or_fetch_checkout_deliveries(checkout_info)
+ for method in checkout_deliveries:
+ if not method.active:
+ continue
+ if method.shipping_method_id == internal_shipping_method_id:
+ return method
+
+ raise ValidationError(
+ {
+ "delivery_method_id": ValidationError(
+ "This shipping method is not applicable.",
+ code=CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.value,
+ )
+ }
+ )
@classmethod
def get_delivery_method_data(
@@ -209,34 +155,20 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
delivery_method_id: str,
manager: "PluginsManager",
info: ResolveInfo,
- ) -> shipping_interface.ShippingMethodData | warehouse_models.Warehouse | None:
+ ) -> CheckoutDelivery | warehouse_models.Warehouse | None:
if delivery_method_id is None:
return None
- delivery_method_data: ShippingMethodData | warehouse_models.Warehouse | None = (
+ delivery_method_data: CheckoutDelivery | warehouse_models.Warehouse | None = (
None
)
- type_name = cls._resolve_delivery_method_type(delivery_method_id)
+ type_name, internal_id = cls._resolve_delivery_method_type(delivery_method_id)
+ if internal_id is None:
+ return None
if type_name == "Warehouse":
- delivery_method_data = cls.get_collection_point_as_delivery_method_data(
- checkout_info, delivery_method_id, info
- )
- elif type_name == "ShippingMethod":
- delivery_method_data = (
- cls.get_built_in_shipping_method_as_delivery_method_data(
- checkout_info, delivery_method_id, info
- )
- )
- elif type_name == APP_ID_PREFIX:
- delivery_method_data = (
- cls.get_external_shipping_method_as_delivery_method_data(
- checkout_info, delivery_method_id, manager
- )
- )
-
- if delivery_method_data:
- cls._check_delivery_method(checkout_info, lines_info, delivery_method_data)
-
+ delivery_method_data = cls.get_collection_point(checkout_info, internal_id)
+ else:
+ delivery_method_data = cls.get_checkout_delivery(checkout_info, internal_id)
return delivery_method_data
@classmethod
diff --git a/saleor/graphql/checkout/mutations/checkout_line_delete.py b/saleor/graphql/checkout/mutations/checkout_line_delete.py
index d2a7581645..ad67c005cd 100644
--- a/saleor/graphql/checkout/mutations/checkout_line_delete.py
+++ b/saleor/graphql/checkout/mutations/checkout_line_delete.py
@@ -15,7 +15,10 @@ from ...core.types import CheckoutError
from ...core.utils import WebhookEventInfo, raise_validation_error
from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Checkout, CheckoutLine
-from .utils import get_checkout, update_checkout_shipping_method_if_invalid
+from .utils import (
+ get_checkout,
+ mark_checkout_deliveries_as_stale_if_needed,
+)
class CheckoutLineDelete(BaseMutation):
@@ -81,8 +84,9 @@ class CheckoutLineDelete(BaseMutation):
manager = get_plugin_manager_promise(info.context).get()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_update_fields = update_checkout_shipping_method_if_invalid(
- checkout_info, lines
+
+ shipping_update_fields = mark_checkout_deliveries_as_stale_if_needed(
+ checkout_info.checkout, lines
)
invalidate_update_fields = invalidate_checkout(
checkout_info, lines, manager, save=False
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index 70c02dd31d..600810bd9b 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -6,7 +6,6 @@ from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
- update_delivery_method_lists_for_checkout_info,
)
from ....checkout.utils import add_variants_to_checkout, invalidate_checkout
from ....core.exceptions import NonExistingCheckout
@@ -35,8 +34,7 @@ from .utils import (
get_checkout,
get_variants_and_total_quantities,
group_lines_input_on_add,
- update_checkout_external_shipping_method_if_invalid,
- update_checkout_shipping_method_if_invalid,
+ mark_checkout_deliveries_as_stale_if_needed,
validate_variants_are_published,
validate_variants_available_for_purchase,
)
@@ -148,15 +146,7 @@ class CheckoutLinesAdd(BaseMutation):
) from e
lines, _ = fetch_checkout_lines(checkout)
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- update_delivery_method_lists_for_checkout_info(
- checkout_info=checkout_info,
- shipping_method=checkout_info.checkout.shipping_method,
- collection_point=checkout_info.checkout.collection_point,
- shipping_address=checkout_info.shipping_address,
- lines=lines,
- shipping_channel_listings=shipping_channel_listings,
- )
+ checkout_info.lines = lines
return lines
@classmethod
@@ -238,10 +228,7 @@ class CheckoutLinesAdd(BaseMutation):
checkout = get_checkout(cls, info, checkout_id=checkout_id, token=token, id=id)
manager = get_plugin_manager_promise(info.context).get()
variants = cls._get_variants_from_lines_input(lines)
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- checkout_info = fetch_checkout_info(
- checkout, [], manager, shipping_channel_listings
- )
+ checkout_info = fetch_checkout_info(checkout, [], manager)
existing_lines_info, _ = fetch_checkout_lines(
checkout, skip_lines_with_unavailable_variants=False
)
@@ -262,9 +249,8 @@ class CheckoutLinesAdd(BaseMutation):
checkout_info,
)
- update_checkout_external_shipping_method_if_invalid(checkout_info, lines)
- shipping_update_fields = update_checkout_shipping_method_if_invalid(
- checkout_info, lines
+ shipping_update_fields = mark_checkout_deliveries_as_stale_if_needed(
+ checkout_info.checkout, lines
)
invalidate_update_fields = invalidate_checkout(
checkout_info, lines, manager, save=False
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_delete.py b/saleor/graphql/checkout/mutations/checkout_lines_delete.py
index 90ff2442d0..486ab70f21 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_delete.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_delete.py
@@ -17,7 +17,7 @@ from ...core.utils import WebhookEventInfo
from ...plugins.dataloaders import get_plugin_manager_promise
from ...utils import resolve_global_ids_to_primary_keys
from ..types import Checkout
-from .utils import get_checkout, update_checkout_shipping_method_if_invalid
+from .utils import get_checkout, mark_checkout_deliveries_as_stale_if_needed
class CheckoutLinesDelete(BaseMutation):
@@ -100,8 +100,8 @@ class CheckoutLinesDelete(BaseMutation):
manager = get_plugin_manager_promise(info.context).get()
checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_update_fields = update_checkout_shipping_method_if_invalid(
- checkout_info, lines
+ shipping_update_fields = mark_checkout_deliveries_as_stale_if_needed(
+ checkout_info.checkout, lines
)
invalidate_update_fields = invalidate_checkout(
checkout_info, lines, manager, save=False
diff --git a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
index 243bfcb30d..d693236fd0 100644
--- a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
@@ -25,7 +25,7 @@ from ...discount.types import Voucher
from ...giftcard.types import GiftCard
from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Checkout
-from .utils import get_checkout
+from .utils import get_checkout, mark_checkout_deliveries_as_stale_if_needed
class CheckoutRemovePromoCode(BaseMutation):
@@ -101,13 +101,20 @@ class CheckoutRemovePromoCode(BaseMutation):
)
# if this step is reached, it means promo code was removed
lines, _ = fetch_checkout_lines(checkout)
- invalidate_checkout(
+
+ fields_to_update = mark_checkout_deliveries_as_stale_if_needed(
+ checkout_info.checkout, lines
+ )
+ fields_to_update += invalidate_checkout(
checkout_info,
lines,
manager,
recalculate_discount=True,
- save=True,
+ save=False,
)
+ if fields_to_update:
+ checkout.save(update_fields=fields_to_update)
+
call_checkout_info_event(
manager,
event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
index 39d5d870d7..97a4287988 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
@@ -36,7 +36,7 @@ from .utils import (
ERROR_CC_ADDRESS_CHANGE_FORBIDDEN,
check_lines_quantity,
get_checkout,
- update_checkout_shipping_method_if_invalid,
+ mark_checkout_deliveries_as_stale_if_needed,
)
if TYPE_CHECKING:
@@ -177,10 +177,7 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixi
),
)
manager = get_plugin_manager_promise(info.context).get()
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- checkout_info = fetch_checkout_info(
- checkout, lines, manager, shipping_channel_listings
- )
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
country = shipping_address_instance.country.code
checkout.set_country(country, commit=True)
@@ -202,12 +199,10 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixi
checkout_info,
shipping_address_instance,
save_address,
- lines,
- shipping_channel_listings,
)
- shipping_update_fields = update_checkout_shipping_method_if_invalid(
- checkout_info, lines
+ shipping_update_fields = mark_checkout_deliveries_as_stale_if_needed(
+ checkout_info.checkout, lines
)
invalidate_prices_updated_fields = invalidate_checkout(
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index 33cf0a7ad6..68001c38d0 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -1,21 +1,17 @@
-from typing import TYPE_CHECKING
-
import graphene
from django.core.exceptions import ValidationError
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 ....shipping import interface as shipping_interface
-from ....shipping import models as shipping_models
-from ....shipping.utils import convert_to_shipping_method_data
from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...core import ResolveInfo
@@ -27,18 +23,13 @@ from ...core.scalars import UUID
from ...core.types import CheckoutError
from ...core.utils import WebhookEventInfo, from_global_id_or_error
from ...plugins.dataloaders import get_plugin_manager_promise
-from ...shipping.types import ShippingMethod
from ..types import Checkout
from .utils import (
ERROR_DOES_NOT_SHIP,
assign_delivery_method_to_checkout,
- clean_delivery_method,
get_checkout,
)
-if TYPE_CHECKING:
- from ....plugins.manager import PluginsManager
-
class CheckoutShippingMethodUpdate(BaseMutation):
checkout = graphene.Field(Checkout, description="An updated checkout.")
@@ -82,7 +73,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
]
@staticmethod
- def _resolve_delivery_method_type(id_) -> str | None:
+ def _resolve_delivery_method_id(id_) -> str | None:
if id_ is None:
return None
@@ -100,110 +91,35 @@ class CheckoutShippingMethodUpdate(BaseMutation):
}
)
- return str_type
-
- @staticmethod
- def _check_delivery_method(
- checkout_info, lines, delivery_method: shipping_interface.ShippingMethodData
- ) -> None:
- delivery_method_is_valid = clean_delivery_method(
- checkout_info=checkout_info,
- method=delivery_method,
- )
- if not delivery_method_is_valid:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "This shipping method is not applicable.",
- code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
-
- @classmethod
- def get_built_in_shipping_method_as_delivery_method_data(
- cls,
- checkout_info,
- shipping_method_id,
- info: ResolveInfo,
- ) -> shipping_interface.ShippingMethodData:
- shipping_method: shipping_models.ShippingMethod = cls.get_node_or_error(
- info,
- shipping_method_id,
- only_type=ShippingMethod,
- field="shipping_method_id",
- qs=shipping_models.ShippingMethod.objects.prefetch_related(
- "postal_code_rules"
- ),
- )
- listing = shipping_models.ShippingMethodChannelListing.objects.filter(
- shipping_method=shipping_method,
- channel=checkout_info.channel,
- ).first()
- if not listing:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method not found for this channel.",
- code=CheckoutErrorCode.NOT_FOUND.value,
- )
- }
- )
- return convert_to_shipping_method_data(shipping_method, listing)
+ return id_
@classmethod
- def get_external_shipping_method_as_delivery_method_data(
- cls,
- checkout_info: CheckoutInfo,
- shipping_method_id: str,
- manager: "PluginsManager",
- ):
- delivery_method = manager.get_shipping_method(
- checkout=checkout_info.checkout,
- channel_slug=checkout_info.channel.slug,
- shipping_method_id=shipping_method_id,
- )
- if delivery_method is None:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "This shipping method is not applicable.",
- code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
- return delivery_method
-
- @classmethod
- def get_delivery_method_data(
- cls,
- checkout_info: CheckoutInfo,
- lines_info: list[CheckoutLineInfo],
- shipping_method_id: str,
- manager: "PluginsManager",
- info: ResolveInfo,
- ) -> shipping_interface.ShippingMethodData | None:
+ def get_checkout_delivery(
+ cls, checkout_info: CheckoutInfo, shipping_method_id: str | None
+ ) -> CheckoutDelivery | None:
if shipping_method_id is None:
return None
+ checkout_deliveries = get_or_fetch_checkout_deliveries(checkout_info)
+ internal_shipping_method_id = cls._resolve_delivery_method_id(
+ shipping_method_id
+ )
+ if internal_shipping_method_id is None:
+ return None
- type_name = cls._resolve_delivery_method_type(shipping_method_id)
- if type_name == "ShippingMethod":
- delivery_method_data = (
- cls.get_built_in_shipping_method_as_delivery_method_data(
- checkout_info, shipping_method_id, info
- )
- )
- else:
- delivery_method_data = (
- cls.get_external_shipping_method_as_delivery_method_data(
- checkout_info, shipping_method_id, manager
+ for method in checkout_deliveries:
+ if not method.active:
+ continue
+ if method.shipping_method_id == internal_shipping_method_id:
+ return method
+
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "This shipping method is not applicable.",
+ code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
- )
-
- if delivery_method_data:
- cls._check_delivery_method(checkout_info, lines_info, delivery_method_data)
-
- return delivery_method_data
+ }
+ )
@classmethod
def perform_mutation(
@@ -250,14 +166,13 @@ class CheckoutShippingMethodUpdate(BaseMutation):
)
}
)
- delivery_method_data = cls.get_delivery_method_data(
- checkout_info, lines, shipping_method_id, manager, info
- )
+
+ checkout_delivery = cls.get_checkout_delivery(checkout_info, shipping_method_id)
assign_delivery_method_to_checkout(
checkout_info,
lines,
manager,
- delivery_method_data,
+ checkout_delivery,
)
return CheckoutShippingMethodUpdate(
checkout=SyncWebhookControlContext(checkout_info.checkout)
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index 3e1a0d220b..fe6152e585 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -3,7 +3,14 @@ from django.core.exceptions import ValidationError
from ....checkout.checkout_cleaner import validate_checkout
from ....checkout.complete_checkout import create_order_from_checkout
-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+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
@@ -146,6 +153,24 @@ class OrderCreateFromCheckout(BaseMutation):
return app.has_perms(permissions)
return False
+ @classmethod
+ def validate_checkout(
+ cls,
+ checkout_info: CheckoutInfo,
+ checkout_lines: list[CheckoutLineInfo],
+ unavailable_variant_pks: list[int],
+ manager,
+ ):
+ if is_shipping_required(checkout_lines) and checkout_info.assigned_delivery:
+ # Refresh stale shipping if needed
+ get_or_fetch_checkout_deliveries(checkout_info)
+ validate_checkout(
+ checkout_info=checkout_info,
+ lines=checkout_lines,
+ unavailable_variant_pks=unavailable_variant_pks,
+ manager=manager,
+ )
+
@classmethod
def perform_mutation( # type: ignore[override]
cls,
@@ -182,11 +207,8 @@ class OrderCreateFromCheckout(BaseMutation):
checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
- validate_checkout(
- checkout_info=checkout_info,
- lines=checkout_lines,
- unavailable_variant_pks=unavailable_variant_pks,
- manager=manager,
+ cls.validate_checkout(
+ checkout_info, checkout_lines, unavailable_variant_pks, manager
)
app = get_app_promise(info.context).get()
try:
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 7245e0d511..d4364b2fbc 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -11,6 +11,7 @@ from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from django.db.models import Exists, OuterRef, Q, QuerySet
+from django.utils import timezone
from prices import Money
from ....checkout import models
@@ -18,16 +19,11 @@ from ....checkout.actions import call_checkout_info_event
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ....checkout.utils import (
- assign_built_in_shipping_to_checkout,
assign_collection_point_to_checkout,
- assign_external_shipping_to_checkout,
- calculate_checkout_quantity,
- clear_delivery_method,
- get_external_shipping_id,
+ assign_shipping_method_to_checkout,
invalidate_checkout,
is_shipping_required,
remove_delivery_method_from_checkout,
- remove_external_shipping_from_checkout,
)
from ....core.exceptions import InsufficientStock, PermissionDenied
from ....discount import DiscountType, DiscountValueType
@@ -41,7 +37,6 @@ from ....discount.utils.promotion import (
from ....permission.enums import CheckoutPermissions
from ....product import models as product_models
from ....product.models import ProductChannelListing, ProductVariant
-from ....shipping import interface as shipping_interface
from ....warehouse import models as warehouse_models
from ....warehouse.availability import check_stock_and_preorder_quantity_bulk
from ....webhook.event_types import WebhookEventAsyncType
@@ -72,68 +67,13 @@ class CheckoutLineData:
metadata_list: list = field(default_factory=list)
-def clean_delivery_method(
- checkout_info: "CheckoutInfo",
- method: shipping_interface.ShippingMethodData | warehouse_models.Warehouse | None,
-) -> bool:
- """Check if current shipping method is valid."""
- if not method:
- # no shipping method was provided, it is valid
- return True
-
- if not checkout_info.shipping_address and isinstance(
- method, shipping_interface.ShippingMethodData
- ):
- raise ValidationError(
- "Cannot choose a shipping method for a checkout without the "
- "shipping address.",
- code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET.value,
- )
-
- if isinstance(method, shipping_interface.ShippingMethodData):
- return method in checkout_info.valid_shipping_methods
-
- return method in checkout_info.valid_pick_up_points
-
-
-def _is_external_shipping_valid(checkout_info: "CheckoutInfo") -> bool:
- if external_shipping_id := get_external_shipping_id(checkout_info.checkout):
- return external_shipping_id in [
- method.id for method in checkout_info.valid_delivery_methods
- ]
- return True
-
-
-def update_checkout_external_shipping_method_if_invalid(
- checkout_info: "CheckoutInfo", lines: list[CheckoutLineInfo]
-):
- if not _is_external_shipping_valid(checkout_info):
- remove_external_shipping_from_checkout(checkout_info.checkout, save=True)
-
-
-def update_checkout_shipping_method_if_invalid(
- checkout_info: "CheckoutInfo", lines: list[CheckoutLineInfo]
+def mark_checkout_deliveries_as_stale_if_needed(
+ checkout: models.Checkout, lines: list[CheckoutLineInfo]
) -> list[str]:
- """Check if current shipping method is valid and clean it if not.
-
- The method is not saving the applied changes on checkout.
- """
- quantity = calculate_checkout_quantity(lines)
- update_fields = []
-
- # remove shipping method when empty checkout
- if quantity == 0 or not is_shipping_required(lines):
- update_fields = clear_delivery_method(checkout_info)
-
- is_valid = clean_delivery_method(
- checkout_info=checkout_info,
- method=checkout_info.get_delivery_method_info().delivery_method,
- )
-
- if not is_valid:
- update_fields = clear_delivery_method(checkout_info)
-
- return update_fields
+ if not is_shipping_required(lines):
+ return []
+ checkout.delivery_methods_stale_at = timezone.now()
+ return ["delivery_methods_stale_at"]
def get_variants_and_total_quantities(
@@ -618,39 +558,30 @@ def assign_delivery_method_to_checkout(
checkout_info: CheckoutInfo,
lines_info: list[CheckoutLineInfo],
manager: "PluginsManager",
- delivery_method_data: (
- shipping_interface.ShippingMethodData | warehouse_models.Warehouse | None
- ),
+ delivery_method: models.CheckoutDelivery | warehouse_models.Warehouse | None,
):
fields_to_update = []
checkout = checkout_info.checkout
with transaction.atomic():
- if delivery_method_data is None:
+ if delivery_method is None:
fields_to_update = remove_delivery_method_from_checkout(
checkout=checkout_info.checkout
)
- checkout_info.shipping_method = None
checkout_info.collection_point = None
+ checkout_info.assigned_delivery = None
- elif isinstance(delivery_method_data, shipping_interface.ShippingMethodData):
- if delivery_method_data.is_external:
- fields_to_update = assign_external_shipping_to_checkout(
- checkout, delivery_method_data
- )
- checkout_info.shipping_method = None
- checkout_info.collection_point = None
- else:
- fields_to_update = assign_built_in_shipping_to_checkout(
- checkout, delivery_method_data
- )
- checkout_info.shipping_method = checkout.shipping_method
- checkout_info.collection_point = None
- elif isinstance(delivery_method_data, warehouse_models.Warehouse):
+ 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_data
+ checkout, delivery_method
)
checkout_info.shipping_address = checkout.shipping_address
- checkout_info.shipping_method = None
+ checkout_info.assigned_delivery = None
if not fields_to_update:
return
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 98b5e03521..e3e634702f 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -4,14 +4,12 @@ from unittest.mock import patch
import graphene
import pytest
from graphene import Node
-from prices import Money
from .....checkout import calculations
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.models import Checkout
+from .....checkout.models import Checkout, CheckoutDelivery
from .....checkout.utils import (
add_variants_to_checkout,
- assign_external_shipping_to_checkout,
)
from .....discount import RewardValueType
from .....discount.models import CheckoutLineDiscount, PromotionRule
@@ -19,7 +17,6 @@ from .....plugins.manager import get_plugins_manager
from .....product.models import Product, ProductVariant, ProductVariantChannelListing
from .....product.utils.variant_prices import update_discounted_prices_for_promotion
from .....product.utils.variants import fetch_variants_for_promotion_rules
-from .....shipping.interface import ShippingMethodData
from .....warehouse.models import Stock
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -422,7 +419,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(90):
+ with django_assert_num_queries(88):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -440,7 +437,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(90):
+ with django_assert_num_queries(88):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -572,7 +569,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(96):
+ with django_assert_num_queries(102):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -828,7 +825,7 @@ def test_update_checkout_lines_with_reservations(
)
user_api_client.ensure_access_token()
- with django_assert_num_queries(112):
+ with django_assert_num_queries(107):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -842,7 +839,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(112):
+ with django_assert_num_queries(107):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -990,16 +987,19 @@ def test_add_checkout_lines_with_external_shipping(
external_shipping_method_id = Node.to_global_id(
"app", f"{shipping_app.id}:{response_method_id}"
)
- external_shipping_method = ShippingMethodData(
- id=external_shipping_method_id,
+ checkout_with_single_item.shipping_address = address
+
+ checkout_with_single_item.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout_with_single_item,
+ external_shipping_method_id=external_shipping_method_id,
name=shipping_name,
- price=Money(shipping_price, currency),
+ price_amount=shipping_price,
+ currency="USD",
+ maximum_delivery_days=7,
)
checkout_with_single_item.shipping_address = address
- assign_external_shipping_to_checkout(
- checkout_with_single_item, external_shipping_method
- )
+
checkout_with_single_item.save()
checkout_with_single_item.metadata_storage.save()
@@ -1050,11 +1050,7 @@ def test_add_checkout_lines_with_external_shipping(
# then
assert not response["data"]["checkoutLinesAdd"]["errors"]
- # Two api calls :
- # - post-mutate() logic used to validate currently selected method
- # - fetch_checkout_prices_if_expired - calculating all prices for checkout
- # - (cached) in check_stock_quantity_bulk to check if the shipping method is set
- assert mock_send_request.call_count == 2
+ assert not mock_send_request.called
@pytest.mark.django_db
@@ -1103,7 +1099,7 @@ def test_add_checkout_lines_with_reservations(
user_api_client.ensure_access_token()
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(109):
+ with django_assert_num_queries(104):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1116,7 +1112,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(109):
+ with django_assert_num_queries(104):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1167,7 +1163,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(100):
+ with django_assert_num_queries(95):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1253,7 +1249,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(100):
+ with django_assert_num_queries(95):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1289,7 +1285,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(106):
+ with django_assert_num_queries(101):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1324,7 +1320,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(138):
+ with django_assert_num_queries(133):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
index d02c9f774e..61da03a420 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
@@ -3,10 +3,9 @@ from unittest.mock import patch
import pytest
from django.utils import timezone
-from prices import Money
-from .....checkout.utils import assign_external_shipping_to_checkout
-from .....shipping.interface import ShippingMethodData
+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
@@ -157,6 +156,7 @@ def test_user_checkout_details_with_external_shipping_method(
customer_checkout,
shipping_app,
settings,
+ address,
):
# given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
@@ -174,13 +174,20 @@ def test_user_checkout_details_with_external_shipping_method(
}
]
- external_shipping_method = ShippingMethodData(
- id=external_id, name=shipping_name, price=Money(shipping_price, currency)
+ checkout = customer_checkout
+
+ assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=external_id,
+ name=shipping_name,
+ price_amount=shipping_price,
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
)
- checkout = customer_checkout
- checkout.shipping_method = None
- assign_external_shipping_to_checkout(checkout, external_shipping_method)
+ checkout.shipping_address = address
+ assign_shipping_method_to_checkout(checkout, assigned_delivery)
checkout.save()
mock_send_request.return_value = mock_json_response
query = """
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
index 9de0323c69..cadc0a7700 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
@@ -72,14 +72,14 @@ def test_checkout_complete(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -139,7 +139,9 @@ def test_checkout_complete(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -237,14 +239,14 @@ def test_checkout_complete_for_token_as_input(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -303,7 +305,9 @@ def test_checkout_complete_for_token_as_input(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_line_delete.py
index 984d5c7141..c698da5078 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_line_delete.py
@@ -7,7 +7,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import calculate_checkout_quantity
from .....plugins.manager import get_plugins_manager
from ....tests.utils import get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINES_DELETE = """
mutation checkoutLineDelete($checkoutId: ID, $token: UUID, $lineId: ID!) {
@@ -33,8 +33,8 @@ MUTATION_CHECKOUT_LINES_DELETE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_line_delete_by_id(
mocked_update_shipping_method, user_api_client, checkout_with_item
@@ -61,13 +61,13 @@ def test_checkout_line_delete_by_id(
assert calculate_checkout_quantity(lines) == 0
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_line_delete_by_token(
mocked_update_shipping_method, user_api_client, checkout_with_item
@@ -93,7 +93,7 @@ def test_checkout_line_delete_by_token(
assert calculate_checkout_quantity(lines) == 0
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
def test_checkout_line_delete_neither_token_and_id_given(
@@ -135,8 +135,8 @@ def test_checkout_line_delete_both_token_and_id_given(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_line_delete_by_old_line_id(
mocked_update_shipping_method, user_api_client, checkout_with_item
@@ -164,4 +164,4 @@ def test_checkout_line_delete_by_old_line_id(
assert calculate_checkout_quantity(lines) == 0
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_add.py
index 0897b70625..465b496b3e 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_add.py
@@ -7,7 +7,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import calculate_checkout_quantity
from .....plugins.manager import get_plugins_manager
from ....tests.utils import get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINES_ADD = """
mutation checkoutLinesAdd(
@@ -35,8 +35,8 @@ MUTATION_CHECKOUT_LINES_ADD = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_add_by_checkout_id(
mocked_update_shipping_method, user_api_client, checkout_with_item, stock
@@ -68,13 +68,13 @@ def test_checkout_lines_add_by_checkout_id(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_add_by_checkout_token(
mocked_update_shipping_method, user_api_client, checkout_with_item, stock
@@ -109,7 +109,7 @@ def test_checkout_lines_add_by_checkout_token(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
def test_checkout_lines_add_neither_token_and_id_given(
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py
index cee53ed26e..258384fbb1 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py
@@ -7,7 +7,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import calculate_checkout_quantity
from .....plugins.manager import get_plugins_manager
from ....tests.utils import get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINES_UPDATE = """
mutation checkoutLinesUpdate(
@@ -36,8 +36,8 @@ MUTATION_CHECKOUT_LINES_UPDATE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_update(
mocked_update_shipping_method, user_api_client, checkout_with_item
@@ -73,13 +73,13 @@ def test_checkout_lines_update(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_update_with_token(
mocked_update_shipping_method, user_api_client, checkout_with_item
@@ -114,7 +114,7 @@ def test_checkout_lines_update_with_token(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
def test_checkout_lines_update_neither_token_and_id_given(
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_address_update.py
index b56d0a24c8..3339dd4b3a 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_address_update.py
@@ -6,7 +6,7 @@ from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....plugins.manager import get_plugins_manager
from ....tests.utils import get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """
mutation checkoutShippingAddressUpdate(
@@ -31,8 +31,8 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_shipping_address_update_by_id(
mocked_update_shipping_method,
@@ -69,13 +69,13 @@ def test_checkout_shipping_address_update_by_id(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_shipping_address_update_by_token(
mocked_update_shipping_method,
@@ -115,7 +115,7 @@ def test_checkout_shipping_address_update_by_token(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info.checkout, lines)
def test_checkout_shipping_address_update_neither_token_and_id_given(
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py
index b461bff3c0..0476ef9b9e 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py
@@ -1,14 +1,6 @@
-from unittest.mock import patch
-
import graphene
from .....checkout.error_codes import CheckoutErrorCode
-from .....checkout.fetch import (
- fetch_checkout_info,
- fetch_checkout_lines,
-)
-from .....plugins.manager import get_plugins_manager
-from .....shipping.utils import convert_to_shipping_method_data
from ....tests.utils import get_graphql_content
MUTATION_UPDATE_SHIPPING_METHOD = """
@@ -33,59 +25,41 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
"""
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_shipping_method_update_by_id(
- mock_clean_shipping,
staff_api_client,
shipping_method,
checkout_with_item_and_shipping_method,
):
+ # given
checkout = checkout_with_item_and_shipping_method
query = MUTATION_UPDATE_SHIPPING_METHOD
- mock_clean_shipping.return_value = True
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ # when
response = staff_api_client.post_graphql(
query, {"checkoutId": checkout_id, "shippingMethodId": method_id}
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
checkout.refresh_from_db()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- mock_clean_shipping.assert_called_once_with(
- checkout_info=checkout_info,
- method=convert_to_shipping_method_data(
- shipping_method, shipping_method.channel_listings.first()
- ),
- )
errors = data["errors"]
assert not errors
assert data["checkout"]["id"] == checkout_id
- assert checkout.shipping_method == shipping_method
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_shipping_method_update_by_token(
- mock_clean_shipping,
staff_api_client,
shipping_method,
checkout_with_item_and_shipping_method,
):
checkout = checkout_with_item_and_shipping_method
query = MUTATION_UPDATE_SHIPPING_METHOD
- mock_clean_shipping.return_value = True
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
@@ -97,31 +71,16 @@ def test_checkout_shipping_method_update_by_token(
checkout.refresh_from_db()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- mock_clean_shipping.assert_called_once_with(
- checkout_info=checkout_info,
- method=convert_to_shipping_method_data(
- shipping_method, shipping_method.channel_listings.first()
- ),
- )
errors = data["errors"]
assert not errors
assert data["checkout"]["id"] == checkout_id
- assert checkout.shipping_method == shipping_method
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_shipping_method_update_neither_token_and_id_given(
- mock_clean_shipping, staff_api_client, checkout_with_item, shipping_method
+ staff_api_client, checkout_with_item, shipping_method
):
query = MUTATION_UPDATE_SHIPPING_METHOD
- mock_clean_shipping.return_value = True
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
@@ -132,16 +91,11 @@ def test_checkout_shipping_method_update_neither_token_and_id_given(
assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_shipping_method_update_both_token_and_id_given(
- mock_clean_shipping, staff_api_client, checkout_with_item, shipping_method
+ staff_api_client, checkout_with_item, shipping_method
):
checkout = checkout_with_item
query = MUTATION_UPDATE_SHIPPING_METHOD
- mock_clean_shipping.return_value = True
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
@@ -161,12 +115,7 @@ def test_checkout_shipping_method_update_both_token_and_id_given(
assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_shipping_method_update_by_id_no_checkout_metadata(
- mock_clean_shipping,
staff_api_client,
shipping_method,
checkout_with_item_and_shipping_method,
@@ -174,7 +123,6 @@ def test_checkout_shipping_method_update_by_id_no_checkout_metadata(
# given
checkout = checkout_with_item_and_shipping_method
query = MUTATION_UPDATE_SHIPPING_METHOD
- mock_clean_shipping.return_value = True
checkout.metadata_storage.delete()
@@ -191,17 +139,7 @@ def test_checkout_shipping_method_update_by_id_no_checkout_metadata(
checkout.refresh_from_db()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- mock_clean_shipping.assert_called_once_with(
- checkout_info=checkout_info,
- method=convert_to_shipping_method_data(
- shipping_method, shipping_method.channel_listings.first()
- ),
- )
errors = data["errors"]
assert not errors
assert data["checkout"]["id"] == checkout_id
- assert checkout.shipping_method == shipping_method
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 6fedd263da..7b1909953b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -1,12 +1,12 @@
import datetime
from decimal import Decimal
-from unittest import mock
from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
from django.utils import timezone
+from freezegun import freeze_time
from prices import Money
from .....checkout import base_calculations, calculations
@@ -15,7 +15,6 @@ from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import (
add_variant_to_checkout,
- assign_external_shipping_to_checkout,
)
from .....core.models import EventDelivery
from .....discount import DiscountValueType, VoucherType
@@ -25,10 +24,9 @@ from .....product.models import (
ProductChannelListing,
ProductVariantChannelListing,
)
-from .....shipping.interface import ShippingMethodData
from .....tests import race_condition
from .....warehouse.models import Stock
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -167,70 +165,6 @@ def test_checkout_add_already_applied_voucher_for_entire_order(
assert checkout_data["discount"]["amount"] == net.amount
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_checkout_add_voucher_code_by_token_with_external_shipment(
- mock_send_request,
- api_client,
- checkout_with_item,
- voucher,
- shipping_app,
- address,
- settings,
-):
- # given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- response_method_id = "abcd"
- shipping_name = "Provider - Economy"
- shipping_price = Decimal(10)
- currency = "USD"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": shipping_name,
- "amount": shipping_price,
- "currency": currency,
- "maximum_delivery_days": "7",
- }
- ]
- mock_send_request.return_value = mock_json_response
-
- external_shipping_method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
-
- external_shipping_method = ShippingMethodData(
- id=external_shipping_method_id,
- name=shipping_name,
- price=Money(shipping_price, currency),
- )
-
- checkout = checkout_with_item
- checkout.shipping_address = address
- assign_external_shipping_to_checkout(checkout, external_shipping_method)
- checkout.save(
- update_fields=[
- "shipping_address",
- "external_shipping_method_id",
- "shipping_method_name",
- ]
- )
- checkout.metadata_storage.save(update_fields=["private_metadata"])
-
- variables = {
- "id": to_global_id_or_none(checkout_with_item),
- "promoCode": voucher.code,
- }
-
- # when
- data = _mutate_checkout_add_promo_code(api_client, variables)
-
- # then
- assert not data["errors"]
- assert data["checkout"]["token"] == str(checkout_with_item.token)
- assert data["checkout"]["voucherCode"] == voucher.code
- assert data["checkout"]["shippingMethod"]["id"] == external_shipping_method_id
-
-
def test_checkout_add_voucher_code_with_display_gross_prices(
api_client, checkout_with_item, voucher, site_settings, monkeypatch
):
@@ -1086,27 +1020,36 @@ def test_checkout_add_promo_code_invalid_promo_code(api_client, checkout_with_it
assert data["errors"][0]["field"] == "promoCode"
-def test_checkout_add_promo_code_invalidate_shipping_method(
+@freeze_time("2022-01-01 12:00:00")
+def test_checkout_add_promo_code_marks_shipping_methods_as_stale(
api_client,
checkout,
variant_with_many_stocks_different_shipping_zones,
gift_card_created_by_staff,
address_usa,
- shipping_method,
+ checkout_delivery,
+ shipping_zone,
channel_USD,
voucher,
+ settings,
):
+ # given
Stock.objects.update(quantity=5)
+ voucher.start_date = timezone.now()
+ voucher.save()
# Free shipping for 50 USD
- shipping_channel_listing = shipping_method.channel_listings.first()
- shipping_channel_listing.minimum_order_price = Money(50, "USD")
+ shipping_method = shipping_zone.shipping_methods.first()
+ shipping_channel_listing = shipping_method.channel_listings.filter(
+ channel_id=checkout.channel_id
+ ).first()
+ shipping_channel_listing.minimum_order_price = Money(150, "USD")
shipping_channel_listing.price = Money(0, "USD")
shipping_channel_listing.save()
# Setup checkout with items worth $50
checkout.shipping_address = address_usa
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address_usa
checkout.save()
@@ -1117,15 +1060,24 @@ def test_checkout_add_promo_code_invalidate_shipping_method(
add_variant_to_checkout(checkout_info, variant, 5)
checkout.save()
- # Apply voucher
variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}
- data = _mutate_checkout_add_promo_code(api_client, variables)
+ # when
+ new_time = timezone.now() + datetime.timedelta(hours=1)
+ with freeze_time(new_time):
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+ # then
+ checkout.refresh_from_db()
shipping_method_id = graphene.Node.to_global_id(
"ShippingMethodType", shipping_method.pk
)
assert data["checkout"]["shippingMethod"] is None
assert shipping_method_id not in data["checkout"]["availableShippingMethods"]
+ assert checkout.assigned_delivery
+ assert (
+ checkout.delivery_methods_stale_at
+ == new_time + settings.CHECKOUT_DELIVERY_OPTIONS_TTL
+ )
def test_checkout_add_promo_code_without_checkout_email(
@@ -1224,12 +1176,14 @@ def test_checkout_add_free_shipping_voucher_do_not_invalidate_shipping_method(
api_client,
checkout_with_item,
voucher_free_shipping,
- shipping_method,
+ checkout_delivery,
+ shipping_zone,
address_usa,
):
- checkout_with_item.shipping_method = shipping_method
+ shipping_method = shipping_zone.shipping_methods.first()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.shipping_address = address_usa
- checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])
+ checkout_with_item.save(update_fields=["assigned_delivery", "shipping_address"])
channel = checkout_with_item.channel
@@ -1267,16 +1221,24 @@ def test_checkout_add_shipping_voucher_do_not_invalidate_shipping_method(
api_client,
checkout_with_item,
voucher_shipping_type,
- shipping_method,
+ checkout_delivery,
+ shipping_zone,
address_usa,
):
"""Ensure that adding shipping voucher do not invalidate current shipping method."""
- checkout_with_item.shipping_method = shipping_method
- checkout_with_item.shipping_address = address_usa
- checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])
-
+ # set minimal price similar to order subtotal price;
channel = checkout_with_item.channel
+ shipping_method = shipping_zone.shipping_methods.first()
+ shipping_listing = shipping_method.channel_listings.get(channel=channel)
+ shipping_listing.price = Money(20, "USD")
+ shipping_listing.minimum_order_price = Money(8, "USD")
+ shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])
+
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.shipping_address = address_usa
+ checkout_with_item.save(update_fields=["assigned_delivery", "shipping_address"])
+
line = checkout_with_item.lines.first()
line.quantity = 1
line.save(update_fields=["quantity"])
@@ -1285,12 +1247,6 @@ def test_checkout_add_shipping_voucher_do_not_invalidate_shipping_method(
variant_listing.price = Money(10, "USD")
variant_listing.save(update_fields=["price_amount"])
- # set minimal price similar to order subtotal price;
- shipping_listing = shipping_method.channel_listings.get(channel=channel)
- shipping_listing.price = Money(20, "USD")
- shipping_listing.minimum_order_price = Money(8, "USD")
- shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])
-
# set shipping voucher price so big, that in case the discount will be
# substracted from subtotal price the shipping method will be not valid anymore
voucher_listing = voucher_shipping_type.channel_listings.get(channel=channel)
@@ -1366,6 +1322,23 @@ def test_with_active_problems_flow(
assert not content["data"]["checkoutAddPromoCode"]["errors"]
+MUTATION_CHECKOUT_ADD_PROMO_CODE_WITH_ONLY_ID = """
+ mutation($id: ID, $promoCode: String!) {
+ checkoutAddPromoCode(
+ id: $id, promoCode: $promoCode) {
+ errors {
+ field
+ message
+ code
+ }
+ checkout {
+ id
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_add_promo_code.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -1374,8 +1347,12 @@ def test_with_active_problems_flow(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_add_voucher_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1407,7 +1384,9 @@ def test_checkout_add_voucher_triggers_webhooks(
checkout_with_item.save()
# when
- response = api_client.post_graphql(MUTATION_CHECKOUT_ADD_PROMO_CODE, variables)
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_ADD_PROMO_CODE_WITH_ONLY_ID, variables
+ )
# then
content = get_graphql_content(response)
@@ -1419,42 +1398,25 @@ def test_checkout_add_voucher_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
- )
-
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ bind=True,
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
def test_add_promo_code_with_price_override_set(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
index 822c9c4c6d..2b361eba97 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
@@ -3,12 +3,14 @@ from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_info_event
from .....checkout.utils import invalidate_checkout
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ..utils import assert_address_data
@@ -664,8 +666,12 @@ def test_checkout_billing_address_skip_validation_by_app(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_billing_address_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -710,46 +716,30 @@ def test_checkout_billing_address_triggers_webhooks(
assert wrapped_call_checkout_info_event.called
- # confirm that event delivery was generated for each webhook.
+ # confirm that event delivery was generated for each async webhook.
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
- )
-
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ bind=True,
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
def test_checkout_billing_address_update_reset_the_save_address_flag_to_default_value(
@@ -860,3 +850,46 @@ def test_checkout_billing_address_update_change_save_address_option_to_true(
assert_address_data(checkout.billing_address, graphql_address_data)
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is False
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_billing_address_do_not_mark_shipping_as_stale(
+ user_api_client,
+ checkout_with_item,
+ graphql_address_data,
+ checkout_delivery,
+ address,
+):
+ # given
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+ checkout = checkout_with_item
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
+ )
+
+ query = MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE
+ billing_address = graphql_address_data
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "billingAddress": billing_address,
+ }
+
+ # when
+ new_now = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index 961d065614..45886ebe47 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -1,3 +1,4 @@
+from datetime import timedelta
from unittest import mock
import graphene
@@ -218,8 +219,6 @@ def test_checkout_complete_0_total_value_no_payment(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -285,8 +284,6 @@ def test_checkout_complete_0_total_value_from_voucher(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -349,8 +346,6 @@ def test_checkout_complete_0_total_value_from_giftcard(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -669,27 +664,33 @@ def test_checkout_complete_existing_user_address_save_address_options_off(
assert order.draft_save_shipping_address is None
+@freeze_time("2023-01-01 12:00:00")
@pytest.mark.integration
def test_checkout_complete_builtin_shipping_method_metadata_denormalization(
user_api_client,
checkout_with_item_total_0,
shipping_method_price_0,
+ checkout_delivery,
address,
):
# given
checkout = checkout_with_item_total_0
- checkout.billing_address = address
- checkout.shipping_address = address
- checkout.shipping_method = shipping_method_price_0
- checkout.save()
expected_metadata_key = "AnyKey"
expected_metadata_value = "AnyValue"
expected_shipping_metadata = {
expected_metadata_key: expected_metadata_value,
}
- shipping_method_price_0.metadata = expected_shipping_metadata
- shipping_method_price_0.save()
+
+ assigned_delivery = checkout_delivery(checkout, shipping_method_price_0)
+ assigned_delivery.metadata = expected_shipping_metadata
+ assigned_delivery.save()
+
+ checkout.billing_address = address
+ checkout.shipping_address = address
+ checkout.assigned_delivery = assigned_delivery
+ checkout.delivery_methods_stale_at = timezone.now() + timedelta(minutes=5)
+ checkout.save()
orders_count = Order.objects.count()
variables = {
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py
index e1f8ab3cc9..19968b9c1d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py
@@ -39,12 +39,13 @@ def test_checkout_complete_price_override(
user_api_client,
checkout_with_item,
address,
+ checkout_delivery,
shipping_method,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -98,11 +99,12 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_fixed(
checkout_with_item_on_promotion,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_on_promotion
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -177,11 +179,12 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_percentag
checkout_with_item_on_promotion,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_on_promotion
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -257,6 +260,7 @@ def test_checkout_complete_with_price_override_and_voucher_entire_order(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
voucher,
):
# given
@@ -267,7 +271,7 @@ def test_checkout_complete_with_price_override_and_voucher_entire_order(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.voucher_code = voucher_code
@@ -333,6 +337,7 @@ def test_checkout_complete_with_price_override_and_voucher_free_shipping(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
voucher_free_shipping,
):
# given
@@ -340,7 +345,7 @@ def test_checkout_complete_with_price_override_and_voucher_free_shipping(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.voucher_code = voucher_code
@@ -410,6 +415,7 @@ def test_checkout_complete_with_price_override_and_voucher_specific_product(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
voucher_specific_product_type,
):
# given
@@ -421,7 +427,7 @@ def test_checkout_complete_with_price_override_and_voucher_specific_product(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.voucher_code = voucher_code
@@ -495,6 +501,7 @@ def test_checkout_complete_with_price_override_and_order_promotion(
order_promotion_with_rule,
address,
shipping_method,
+ checkout_delivery,
):
# given
promotion = order_promotion_with_rule
@@ -509,7 +516,7 @@ def test_checkout_complete_with_price_override_and_order_promotion(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -574,6 +581,7 @@ def test_checkout_complete_with_price_override_and_gift_promotion(
gift_promotion_rule,
address,
shipping_method,
+ checkout_delivery,
digital_content,
):
# given
@@ -589,7 +597,7 @@ def test_checkout_complete_with_price_override_and_gift_promotion(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -655,6 +663,7 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_and_entir
checkout_with_item_on_promotion,
address,
shipping_method,
+ checkout_delivery,
voucher,
):
# given
@@ -669,7 +678,7 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_and_entir
checkout = checkout_with_item_on_promotion
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
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 98af094516..802507682d 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
@@ -13,8 +13,13 @@ from django.utils import timezone
from .....account.models import Address
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.models import Checkout, CheckoutLine
+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
@@ -31,6 +36,7 @@ from .....payment.interface import GatewayResponse
from .....payment.model_helpers import get_subtotal
from .....plugins.manager import PluginsManager, get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
+from .....shipping.models import ShippingMethod
from .....tests import race_condition
from .....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
from .....warehouse.tests.utils import get_available_quantity_for_stock
@@ -126,7 +132,7 @@ def test_checkout_complete_with_inactive_channel(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
assert not gift_card.last_used_on
@@ -135,7 +141,7 @@ def test_checkout_complete_with_inactive_channel(
channel.is_active = False
channel.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -190,7 +196,8 @@ def test_checkout_complete(
address,
address_usa,
customer_user,
- shipping_method,
+ checkout_delivery,
+ shipping_zone,
caplog,
):
# given
@@ -199,7 +206,7 @@ def test_checkout_complete(
checkout = checkout_with_gift_card
checkout.user = customer_user
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address_usa
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -219,7 +226,8 @@ def test_checkout_complete(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- shipping_price = checkout.shipping_method.channel_listings.get(
+ shipping_method = shipping_zone.shipping_methods.first()
+ shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
).price
@@ -286,7 +294,9 @@ def test_checkout_complete(
assert order.billing_address.id == address_usa.id
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.shipping_tax_rate is not None
assert order.shipping_tax_class_name == shipping_tax_class.name
assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
@@ -350,14 +360,14 @@ def test_checkout_complete_with_metadata(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -428,14 +438,14 @@ def test_checkout_complete_with_metadata_updates_existing_keys(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
meta_key = "testKey"
new_meta_value = "newValue"
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={meta_key: "oldValue"})
checkout.save()
@@ -491,14 +501,14 @@ def test_checkout_complete_with_metadata_checkout_without_metadata(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -568,13 +578,13 @@ def test_checkout_complete_by_app(
permission_impersonate_user,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
mocked_complete_checkout.return_value = (None, True, {})
checkout = checkout_with_item
checkout.user = customer_user
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -631,13 +641,13 @@ def test_checkout_complete_by_app_with_missing_permission(
permission_manage_users,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
mocked_complete_checkout.return_value = (None, True, {})
checkout = checkout_with_item
checkout.user = customer_user
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -694,13 +704,13 @@ def test_checkout_complete_gift_card_bought(
user_api_client,
checkout_with_gift_card_items,
address,
- shipping_method,
+ checkout_delivery,
payment_txn_captured,
):
# given
checkout = checkout_with_gift_card_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -770,11 +780,11 @@ def test_checkout_complete_with_variant_without_sku(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -828,11 +838,11 @@ def test_checkout_complete_with_variant_without_price(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -872,11 +882,11 @@ def test_checkout_complete_with_line_without_channel_listing(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -957,7 +967,7 @@ def test_checkout_with_voucher_complete(
voucher_percentage,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
channel = checkout_with_voucher_percentage.channel
@@ -971,7 +981,7 @@ def test_checkout_with_voucher_complete(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1035,7 +1045,9 @@ def test_checkout_with_voucher_complete(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1078,7 +1090,7 @@ def test_checkout_with_order_promotion_complete(
checkout_with_item_and_order_discount,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_and_order_discount
@@ -1088,7 +1100,7 @@ def test_checkout_with_order_promotion_complete(
channel.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1147,7 +1159,9 @@ def test_checkout_with_order_promotion_complete(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1185,7 +1199,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
voucher_percentage,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
# given
@@ -1207,7 +1221,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
checkout_line_variant = checkout_line.variant
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1269,7 +1283,9 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1305,7 +1321,7 @@ def test_checkout_with_voucher_complete_product_on_promotion(
voucher_percentage,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
catalogue_promotion_without_rules,
):
# given
@@ -1316,7 +1332,7 @@ def test_checkout_with_voucher_complete_product_on_promotion(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1437,7 +1453,9 @@ def test_checkout_with_voucher_complete_product_on_promotion(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1473,7 +1491,7 @@ def test_checkout_with_voucher_on_specific_product_complete(
voucher_specific_product_type,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
# given
@@ -1489,7 +1507,7 @@ def test_checkout_with_voucher_on_specific_product_complete(
checkout = checkout_with_item_and_voucher_specific_products
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1553,7 +1571,9 @@ def test_checkout_with_voucher_on_specific_product_complete(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1590,7 +1610,7 @@ def test_checkout_complete_with_voucher_single_use(
voucher_percentage,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
code = voucher_percentage.codes.first()
@@ -1601,7 +1621,7 @@ def test_checkout_complete_with_voucher_single_use(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1665,7 +1685,9 @@ def test_checkout_complete_with_voucher_single_use(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1697,6 +1719,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card_and_payment(
gift_card,
payment_dummy,
address,
+ checkout_delivery,
shipping_method,
):
# given
@@ -1708,7 +1731,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card_and_payment(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1731,6 +1754,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card_and_payment(
manager, checkout_info, lines, address
)
gift_card_initial_balance = gift_card.initial_balance_amount
+
shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
).price
@@ -1777,7 +1801,9 @@ def test_checkout_complete_with_voucher_paid_with_gift_card_and_payment(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -1819,6 +1845,7 @@ def test_checkout_complete_with_voucher_paid_by_gift_card(
voucher_percentage,
gift_card,
address,
+ checkout_delivery,
shipping_method,
):
# given
@@ -1829,7 +1856,7 @@ def test_checkout_complete_with_voucher_paid_by_gift_card(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.save()
@@ -1893,7 +1920,9 @@ def test_checkout_complete_with_voucher_paid_by_gift_card(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert (
order_line.unit_discount_amount
@@ -1928,6 +1957,7 @@ def test_checkout_complete_free_shipping_voucher_and_gift_card(
gift_card,
payment_dummy,
address,
+ checkout_delivery,
shipping_method,
):
# given
@@ -1947,7 +1977,7 @@ def test_checkout_complete_free_shipping_voucher_and_gift_card(
checkout.discount = shipping_listing.price
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2014,7 +2044,9 @@ def test_checkout_complete_free_shipping_voucher_and_gift_card(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2047,12 +2079,12 @@ def test_checkout_complete_product_on_promotion(
catalogue_promotion_without_rules,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2172,7 +2204,9 @@ def test_checkout_complete_product_on_promotion(
assert checkout_line_variant == order_line.variant
assert order_line.is_price_overridden is False
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2189,12 +2223,12 @@ def test_checkout_complete_product_on_promotion_deleted_promotion_instance(
catalogue_promotion_without_rules,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2312,7 +2346,9 @@ def test_checkout_complete_product_on_promotion_deleted_promotion_instance(
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2329,12 +2365,12 @@ def test_checkout_complete_price_override(
catalogue_promotion_without_rules,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2402,7 +2438,9 @@ def test_checkout_complete_price_override(
assert checkout_line_variant == order_line.variant
assert order_line.is_price_overridden is True
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2418,12 +2456,12 @@ def test_checkout_complete_product_on_old_sale(
catalogue_promotion_without_rules,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2546,7 +2584,9 @@ def test_checkout_complete_product_on_old_sale(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2578,7 +2618,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
catalogue_promotion_without_rules,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
# given
@@ -2603,7 +2643,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
checkout = checkout_with_item_and_voucher_specific_products
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2737,7 +2777,9 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
)
assert order_line.unit_discount_reason == unit_discount_reason
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2764,7 +2806,7 @@ def test_checkout_with_voucher_not_increase_uses_on_preprocess_order_creation_fa
voucher_percentage,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
code = voucher_percentage.codes.first()
mocked_preprocess_order_creation.side_effect = TaxError("tax error!")
@@ -2775,7 +2817,7 @@ def test_checkout_with_voucher_not_increase_uses_on_preprocess_order_creation_fa
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -2813,11 +2855,9 @@ def test_checkout_complete_without_inventory_tracking(
checkout_with_variant_without_inventory_tracking,
payment_dummy,
address,
- shipping_method,
):
checkout = checkout_with_variant_without_inventory_tracking
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2875,7 +2915,9 @@ def test_checkout_complete_without_inventory_tracking(
assert checkout_line_variant == order_line.variant
assert not order_line.allocations.all()
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -2892,11 +2934,11 @@ def test_checkout_complete_checkout_without_lines(
checkout,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2953,13 +2995,13 @@ def test_checkout_complete_error_in_gateway_response_for_dummy_credit_card(
gift_card,
payment_dummy_credit_card,
address,
- shipping_method,
+ checkout_delivery,
):
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -3036,14 +3078,14 @@ def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
voucher,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
mocked_process_payment.side_effect = error_side_effect
code = voucher.codes.first()
expected_voucher_usage_count = code.used
checkout = checkout_with_voucher
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3103,11 +3145,11 @@ def test_checkout_complete_invalid_id(user_api_client):
def test_checkout_complete_no_payment(
- user_api_client, checkout_with_item, address, shipping_method
+ user_api_client, checkout_with_item, address, checkout_delivery
):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
variables = {
@@ -3133,7 +3175,7 @@ def test_checkout_complete_confirmation_needed(
checkout_with_item,
address,
payment_dummy,
- shipping_method,
+ checkout_delivery,
action_required_gateway_response,
):
# given
@@ -3141,7 +3183,7 @@ def test_checkout_complete_confirmation_needed(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3195,7 +3237,7 @@ def test_checkout_confirm(
checkout_with_item,
payment_txn_to_confirm,
address,
- shipping_method,
+ checkout_delivery,
action_required_gateway_response,
):
response = action_required_gateway_response
@@ -3204,7 +3246,7 @@ def test_checkout_confirm(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3242,7 +3284,11 @@ def test_checkout_confirm(
def test_checkout_complete_insufficient_stock(
- user_api_client, checkout_with_item, address, payment_dummy, shipping_method
+ user_api_client,
+ checkout_with_item,
+ address,
+ payment_dummy,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout_line = checkout.lines.first()
@@ -3251,7 +3297,7 @@ def test_checkout_complete_insufficient_stock(
checkout_line.quantity = quantity_available + 1
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3289,7 +3335,7 @@ def test_checkout_complete_insufficient_stock_payment_refunded(
gateway_refund_mock,
checkout_with_item,
address,
- shipping_method,
+ checkout_delivery,
payment_dummy,
user_api_client,
):
@@ -3302,7 +3348,7 @@ def test_checkout_complete_insufficient_stock_payment_refunded(
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3351,7 +3397,7 @@ def test_checkout_complete_insufficient_stock_payment_voided(
gateway_void_mock,
checkout_with_item,
address,
- shipping_method,
+ checkout_delivery,
payment_txn_preauth,
user_api_client,
):
@@ -3364,7 +3410,7 @@ def test_checkout_complete_insufficient_stock_payment_voided(
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3414,7 +3460,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
checkout_with_item,
address,
payment_dummy,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
checkout = checkout_with_item
@@ -3440,7 +3486,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
checkout_line.quantity = 1
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3478,7 +3524,7 @@ def test_checkout_complete_own_reservation(
checkout_with_item,
address,
payment_dummy,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
checkout = checkout_with_item
@@ -3489,7 +3535,7 @@ def test_checkout_complete_own_reservation(
checkout_line.quantity = quantity_available
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3551,13 +3597,13 @@ def test_checkout_complete_without_redirect_url(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3600,7 +3646,9 @@ def test_checkout_complete_without_redirect_url(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
@@ -3622,12 +3670,12 @@ def test_checkout_complete_payment_payment_total_different_than_checkout(
payment_dummy,
user_api_client,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -3897,7 +3945,7 @@ def test_checkout_complete_0_total_value(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
assert not gift_card.last_used_on
@@ -3922,8 +3970,6 @@ def test_checkout_complete_0_total_value(
checkout_line_variant.price_amount = Decimal(0)
checkout_line_variant.save()
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -4325,12 +4371,12 @@ def test_checkout_complete_with_preorder_variant(
checkout_with_item_and_preorder_item,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_and_preorder_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -4386,7 +4432,9 @@ def test_checkout_complete_with_preorder_variant(
for variant_id, quantity in variants_and_quantities.items():
assert order.lines.get(variant_id=variant_id).quantity == quantity
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.payments.exists()
assert payment.transactions.count() == 1
@@ -4482,12 +4530,12 @@ def test_checkout_complete_variant_channel_listing_does_not_exist(
checkout_with_items,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -4546,12 +4594,12 @@ def test_checkout_complete_variant_channel_listing_no_price(
checkout_with_items,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -4615,12 +4663,12 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
checkout_with_items,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -4684,13 +4732,13 @@ def test_checkout_complete_product_channel_listing_not_available_for_purchase(
checkout_with_items,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
available_for_purchase,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -4753,7 +4801,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_
gift_card,
payment_dummy_credit_card,
address,
- shipping_method,
+ checkout_delivery,
):
# given
shipping_address = Address.objects.create(
@@ -4768,7 +4816,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_
checkout = checkout_with_item
checkout.shipping_address = shipping_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -4815,7 +4863,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fie
gift_card,
payment_dummy_credit_card,
address,
- shipping_method,
+ checkout_delivery,
):
# given
shipping_address = Address.objects.create(
@@ -4831,7 +4879,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fie
checkout = checkout_with_item
checkout.shipping_address = shipping_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -4878,7 +4926,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_f
gift_card,
payment_dummy_credit_card,
address,
- shipping_method,
+ checkout_delivery,
):
# given
billing_address = Address.objects.create(
@@ -4893,7 +4941,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_f
checkout = checkout_with_item
checkout.billing_address = billing_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.shipping_address = address
checkout.save()
@@ -4939,7 +4987,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fiel
gift_card,
payment_dummy_credit_card,
address,
- shipping_method,
+ checkout_delivery,
):
# given
billing_address = Address.objects.create(
@@ -4955,7 +5003,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fiel
checkout = checkout_with_item
checkout.billing_address = billing_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.shipping_address = address
checkout.save()
@@ -5003,7 +5051,7 @@ def test_checkout_complete_with_not_normalized_shipping_address(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
@@ -5017,7 +5065,7 @@ def test_checkout_complete_with_not_normalized_shipping_address(
postal_code="20500",
)
checkout.shipping_address = shipping_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -5066,7 +5114,7 @@ def test_checkout_complete_with_not_normalized_billing_address(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
@@ -5080,7 +5128,7 @@ def test_checkout_complete_with_not_normalized_billing_address(
postal_code="20500",
)
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = billing_address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -5129,7 +5177,7 @@ def test_checkout_complete_check_reservations_create(
checkout_with_item,
address,
payment_dummy,
- shipping_method,
+ checkout_delivery,
action_required_gateway_response,
):
# given
@@ -5137,7 +5185,7 @@ def test_checkout_complete_check_reservations_create(
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -5188,14 +5236,14 @@ def test_checkout_complete_reservations_drop(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -5237,13 +5285,13 @@ def test_checkout_complete_saving_addresses_off(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
customer_user,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save_shipping_address = False
checkout.save_billing_address = False
@@ -5311,14 +5359,14 @@ def test_checkout_complete_saving_addresses_on(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
customer_user,
address_usa,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address_usa
checkout.save_shipping_address = True
checkout.save_billing_address = True
@@ -5395,12 +5443,12 @@ def test_checkout_complete_payment_create_create_run_in_meantime(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_without_shipping_required
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -5478,12 +5526,12 @@ def test_checkout_complete_payment_payment_deactivated_in_meantime(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_without_shipping_required
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -5540,14 +5588,14 @@ def test_checkout_complete_line_deleted_in_the_meantime(
gift_card,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
):
# given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -5603,7 +5651,7 @@ def test_checkout_complete_with_invalid_address(
checkout_with_item,
address,
payment_dummy,
- shipping_method,
+ checkout_delivery,
customer_user,
):
"""Check if checkout can be completed with invalid address.
@@ -5625,10 +5673,15 @@ def test_checkout_complete_with_invalid_address(
checkout.billing_address = address
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.user = customer_user
checkout.save(
- update_fields=["billing_address", "shipping_address", "shipping_method", "user"]
+ update_fields=[
+ "billing_address",
+ "shipping_address",
+ "assigned_delivery",
+ "user",
+ ]
)
customer_user.addresses.clear()
@@ -5674,7 +5727,7 @@ def test_checkout_complete_log_unknown_discount_reason(
voucher_specific_product_type,
payment_dummy,
address,
- shipping_method,
+ checkout_delivery,
caplog,
):
# given
@@ -5682,10 +5735,14 @@ def test_checkout_complete_log_unknown_discount_reason(
checkout = checkout_with_item_and_voucher_specific_products
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save(
- update_fields=["shipping_address", "shipping_method", "billing_address"]
+ update_fields=[
+ "shipping_address",
+ "assigned_delivery",
+ "billing_address",
+ ]
)
manager = get_plugins_manager(allow_replica=False)
@@ -5734,6 +5791,7 @@ def test_checkout_complete_empty_product_translation(
gift_card,
payment_dummy,
address,
+ checkout_delivery,
shipping_method,
caplog,
):
@@ -5742,10 +5800,14 @@ def test_checkout_complete_empty_product_translation(
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.save(
- update_fields=["shipping_address", "shipping_method", "billing_address"]
+ update_fields=[
+ "shipping_address",
+ "assigned_delivery",
+ "billing_address",
+ ]
)
checkout_line = checkout.lines.first()
@@ -5756,9 +5818,7 @@ def test_checkout_complete_empty_product_translation(
checkout_line_product.translations.create(language_code="en")
checkout_line_variant.translations.create(language_code="en")
- shipping_price = checkout.shipping_method.channel_listings.get(
- channel=checkout.channel
- ).price
+ shipping_price = checkout.assigned_delivery.price
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
@@ -5817,7 +5877,9 @@ def test_checkout_complete_empty_product_translation(
assert order_line.translated_variant_name == ""
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.shipping_price_gross_amount == shipping_price.amount
assert order.base_shipping_price_amount == shipping_price.amount
assert order.undiscounted_base_shipping_price_amount == shipping_price.amount
@@ -5881,8 +5943,17 @@ def test_checkout_complete_with_external_shipping(
mocked_sync_webhook.return_value = mock_json_response
checkout = checkout_with_item
- checkout.external_shipping_method_id = graphql_external_method_id
- checkout.shipping_method_name = external_shipping_name
+
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=graphql_external_method_id,
+ name=external_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
+
checkout.shipping_address = address
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
@@ -6014,8 +6085,15 @@ def test_checkout_complete_with_external_shipping_private_metadata(
mocked_sync_webhook.return_value = mock_json_response
checkout = checkout_with_item
- checkout.external_shipping_method_id = graphql_external_method_id
- checkout.shipping_method_name = external_shipping_name
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=graphql_external_method_id,
+ name=external_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_address = address
checkout.billing_address = address
checkout.save()
@@ -6159,3 +6237,199 @@ def test_checkout_complete_sets_product_type_id_for_all_order_lines(
assert (
line.product_type_id == variant_id_to_product_type_id_map[line.variant_id]
)
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_complete."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+def test_complete_refreshes_shipping_methods_when_stale(
+ mocked_get_or_fetch_checkout_deliveries,
+ user_api_client,
+ checkout_ready_to_complete,
+ payment_dummy,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save()
+
+ checkout.gift_cards.all().delete()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert mocked_get_or_fetch_checkout_deliveries.called
+
+
+@patch(
+ "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+def test_complete_do_not_refresh_shipping_methods_when_not_stale(
+ mocked_fetch_shipping_methods_for_checkout,
+ user_api_client,
+ checkout_ready_to_complete,
+ payment_dummy,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now() + datetime.timedelta(hours=1)
+ checkout.save()
+
+ checkout.gift_cards.all().delete()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert not mocked_fetch_shipping_methods_for_checkout.called
+
+
+@patch(
+ "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+def test_complete_do_not_refresh_shipping_methods_when_cc_is_used(
+ mocked_fetch_shipping_methods_for_checkout,
+ user_api_client,
+ checkout_with_delivery_method_for_cc,
+ payment_dummy,
+ address,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+ checkout.billing_address = address
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert not mocked_fetch_shipping_methods_for_checkout.called
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_complete."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+def test_complete_refreshes_shipping_methods_when_stale_and_invalid(
+ mocked_get_or_fetch_checkout_deliveries,
+ user_api_client,
+ checkout_ready_to_complete,
+ payment_dummy,
+):
+ # given
+
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save()
+ checkout.gift_cards.all().delete()
+
+ # Shipping is not available anymore
+ ShippingMethod.objects.all().delete()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ Order.objects.all().delete()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert data["errors"]
+ assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID_SHIPPING_METHOD.name
+
+ assert Order.objects.count() == 0
+ assert mocked_get_or_fetch_checkout_deliveries.called
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 81f505b969..ec597a42bd 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
@@ -14,8 +14,13 @@ from .....account.models import Address
from .....channel import MarkAsPaidStrategy
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.models import Checkout, CheckoutLine
+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 .....core.taxes import TaxError, zero_money, zero_taxed_money
@@ -39,6 +44,7 @@ from .....product.models import (
ProductVariantChannelListing,
VariantChannelListingPromotionRule,
)
+from .....shipping.models import ShippingMethod
from .....tests import race_condition
from .....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
from .....warehouse.tests.utils import get_available_quantity_for_stock
@@ -126,7 +132,7 @@ def prepare_checkout_for_test(
checkout,
shipping_address,
billing_address,
- shipping_method,
+ checkout_delivery,
transaction_item_generator,
transaction_events_generator,
voucher=None,
@@ -135,7 +141,7 @@ def prepare_checkout_for_test(
save_billing_address=None,
):
checkout.shipping_address = shipping_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery
checkout.billing_address = billing_address
if save_shipping_address is not None:
checkout.save_shipping_address = save_shipping_address
@@ -189,12 +195,12 @@ def test_checkout_without_any_transaction(
gift_card,
transaction_item_generator,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -237,11 +243,12 @@ def test_checkout_without_any_transaction_allow_to_create_order(
transaction_item_generator,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -296,13 +303,14 @@ def test_checkout_with_total_0(
address,
shipping_method,
channel_USD,
+ checkout_delivery,
):
# given
shipping_method.channel_listings.update(price_amount=Decimal(0))
checkout = checkout_with_item_total_0
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -355,13 +363,14 @@ def test_checkout_with_authorized(
gift_card,
transaction_item_generator,
address,
- shipping_method,
customer_user,
+ checkout_delivery,
+ shipping_method,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -382,7 +391,7 @@ def test_checkout_with_authorized(
channel.automatically_confirm_all_new_orders = True
channel.save()
- shipping_price = checkout.shipping_method.channel_listings.get(
+ shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
).price
@@ -443,7 +452,9 @@ def test_checkout_with_authorized(
assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.shipping_tax_rate is not None
assert order.shipping_tax_class_name == shipping_tax_class.name
assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
@@ -469,13 +480,13 @@ def test_checkout_with_charged(
gift_card,
transaction_item_generator,
address,
- shipping_method,
customer_user,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -542,8 +553,8 @@ def test_checkout_with_charged(
order_line = order.lines.first()
line_tax_class = order_line.tax_class
- shipping_tax_class = shipping_method.tax_class
+ assigned_checkout_shipping = checkout.assigned_delivery
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
@@ -554,12 +565,18 @@ def test_checkout_with_charged(
assert order_line.is_price_overridden is False
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method_id == int(
+ assigned_checkout_shipping.shipping_method_id
+ )
assert order.shipping_tax_rate is not None
- assert order.shipping_tax_class_name == shipping_tax_class.name
- assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert order.shipping_tax_class_name == assigned_checkout_shipping.tax_class_name
assert (
- order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ order.shipping_tax_class_metadata
+ == assigned_checkout_shipping.tax_class_metadata
+ )
+ assert (
+ order.shipping_tax_class_private_metadata
+ == assigned_checkout_shipping.tax_class_private_metadata
)
assert order.lines_count == len(lines)
@@ -577,11 +594,12 @@ def test_checkout_price_override(
transaction_item_generator,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -647,7 +665,8 @@ def test_checkout_price_override(
order_line = order.lines.first()
line_tax_class = order_line.tax_class
- shipping_tax_class = shipping_method.tax_class
+
+ assigned_delivery = checkout.assigned_delivery
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
@@ -662,12 +681,14 @@ def test_checkout_price_override(
)
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(assigned_delivery.shipping_method_id)
assert order.shipping_tax_rate is not None
- assert order.shipping_tax_class_name == shipping_tax_class.name
- assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert order.shipping_tax_class.id == assigned_delivery.tax_class_id
+ assert order.shipping_tax_class_name == assigned_delivery.tax_class_name
+ assert order.shipping_tax_class_metadata == assigned_delivery.tax_class_metadata
assert (
- order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ order.shipping_tax_class_private_metadata
+ == assigned_delivery.tax_class_private_metadata
)
assert order.lines_count == len(lines)
@@ -682,11 +703,12 @@ def test_checkout_paid_with_multiple_transactions(
transaction_item_generator,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.save()
@@ -744,11 +766,12 @@ def test_checkout_partially_paid(
transaction_item_generator,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -796,11 +819,12 @@ def test_checkout_partially_paid_allow_unpaid_order(
transaction_item_generator,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.save()
@@ -854,11 +878,12 @@ def test_checkout_with_pending_charged(
address,
shipping_method,
transaction_events_generator,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.save()
@@ -922,11 +947,12 @@ def test_checkout_with_pending_authorized(
address,
shipping_method,
transaction_events_generator,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1012,7 +1038,9 @@ def test_checkout_with_pending_authorized(
assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.shipping_tax_rate is not None
assert order.shipping_tax_class_name == shipping_tax_class.name
assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
@@ -1029,16 +1057,16 @@ def test_checkout_with_voucher_not_applicable(
checkout_with_item_and_voucher,
voucher,
address,
- shipping_method,
transaction_item_generator,
transaction_events_generator,
+ checkout_delivery,
):
# given
checkout = prepare_checkout_for_test(
checkout_with_item_and_voucher,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item_and_voucher),
transaction_item_generator,
transaction_events_generator,
)
@@ -1073,9 +1101,9 @@ def test_checkout_with_voucher_inactive_code(
checkout_with_item_and_voucher,
voucher,
address,
- shipping_method,
transaction_item_generator,
transaction_events_generator,
+ checkout_delivery,
):
# given
code = voucher.codes.first()
@@ -1083,7 +1111,7 @@ def test_checkout_with_voucher_inactive_code(
checkout_with_item_and_voucher,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item_and_voucher),
transaction_item_generator,
transaction_events_generator,
)
@@ -1118,7 +1146,7 @@ def test_checkout_with_insufficient_stock(
user_api_client,
checkout_with_item,
address,
- shipping_method,
+ checkout_delivery,
transaction_item_generator,
transaction_events_generator,
):
@@ -1127,7 +1155,7 @@ def test_checkout_with_insufficient_stock(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -1155,7 +1183,7 @@ def test_checkout_with_gift_card_not_applicable(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_item_generator,
transaction_events_generator,
):
@@ -1169,7 +1197,7 @@ def test_checkout_with_gift_card_not_applicable(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -1193,7 +1221,7 @@ def test_checkout_with_variant_without_price(
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1202,7 +1230,7 @@ def test_checkout_with_variant_without_price(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -1243,7 +1271,7 @@ def test_checkout_with_line_without_channel_listing(
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1252,7 +1280,7 @@ def test_checkout_with_line_without_channel_listing(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -1285,7 +1313,7 @@ def test_checkout_complete_with_inactive_channel(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1294,7 +1322,7 @@ def test_checkout_complete_with_inactive_channel(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -1334,7 +1362,7 @@ def test_checkout_complete(
gift_card,
address,
address_usa,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
caplog,
@@ -1345,7 +1373,7 @@ def test_checkout_complete(
checkout_with_gift_card,
address,
address_usa,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
user=customer_user,
@@ -1410,7 +1438,7 @@ def test_checkout_complete(
order_line = order.lines.first()
line_tax_class = order_line.tax_class
- shipping_tax_class = shipping_method.tax_class
+ assigned_delivery = checkout.assigned_delivery
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
@@ -1424,12 +1452,14 @@ def test_checkout_complete(
assert order.shipping_address == address
assert order.draft_save_billing_address is None
assert order.draft_save_shipping_address is None
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(assigned_delivery.shipping_method_id)
assert order.shipping_tax_rate is not None
- assert order.shipping_tax_class_name == shipping_tax_class.name
- assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert order.shipping_tax_class.id == assigned_delivery.tax_class_id
+ assert order.shipping_tax_class_name == assigned_delivery.tax_class_name
+ assert order.shipping_tax_class_metadata == assigned_delivery.tax_class_metadata
assert (
- order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ order.shipping_tax_class_private_metadata
+ == assigned_delivery.tax_class_private_metadata
)
assert order.search_vector
@@ -1477,7 +1507,7 @@ def test_checkout_complete_with_metadata(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1486,7 +1516,7 @@ def test_checkout_complete_with_metadata(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -1543,7 +1573,7 @@ def test_checkout_complete_with_metadata_updates_existing_keys(
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1552,7 +1582,7 @@ def test_checkout_complete_with_metadata_updates_existing_keys(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -1597,7 +1627,7 @@ def test_checkout_complete_with_metadata_checkout_without_metadata(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1606,7 +1636,7 @@ def test_checkout_complete_with_metadata_checkout_without_metadata(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -1660,7 +1690,7 @@ def test_checkout_complete_by_app(
customer_user,
permission_impersonate_user,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1669,7 +1699,7 @@ def test_checkout_complete_by_app(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -1717,7 +1747,7 @@ def test_checkout_complete_by_app_with_missing_permission(
customer_user,
permission_manage_users,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1726,7 +1756,7 @@ def test_checkout_complete_by_app_with_missing_permission(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -1773,7 +1803,7 @@ def test_checkout_complete_gift_card_bought(
user_api_client,
checkout_with_gift_card_items,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1782,7 +1812,7 @@ def test_checkout_complete_gift_card_bought(
checkout_with_gift_card_items,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card_items),
transaction_item_generator,
transaction_events_generator,
)
@@ -1839,6 +1869,7 @@ def test_checkout_complete_with_shipping_voucher_and_gift_card(
gift_card,
address,
shipping_method,
+ checkout_delivery,
voucher_free_shipping,
transaction_events_generator,
transaction_item_generator,
@@ -1854,7 +1885,7 @@ def test_checkout_complete_with_shipping_voucher_and_gift_card(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card, shipping_method),
transaction_item_generator,
transaction_events_generator,
voucher=voucher_free_shipping,
@@ -1922,7 +1953,7 @@ def test_checkout_complete_with_shipping_voucher_and_gift_card(
order_line = order.lines.first()
line_tax_class = order_line.tax_class
- shipping_tax_class = shipping_method.tax_class
+ assigned_delivery = checkout.assigned_delivery
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
@@ -1933,12 +1964,14 @@ def test_checkout_complete_with_shipping_voucher_and_gift_card(
assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(assigned_delivery.shipping_method_id)
assert order.shipping_tax_rate is not None
- assert order.shipping_tax_class_name == shipping_tax_class.name
- assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert order.shipping_tax_class.id == assigned_delivery.tax_class_id
+ assert order.shipping_tax_class_name == assigned_delivery.tax_class_name
+ assert order.shipping_tax_class_metadata == assigned_delivery.tax_class_metadata
assert (
- order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ order.shipping_tax_class_private_metadata
+ == assigned_delivery.tax_class_private_metadata
)
assert order.search_vector
@@ -1962,7 +1995,7 @@ def test_checkout_complete_with_variant_without_sku(
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -1971,7 +2004,7 @@ def test_checkout_complete_with_variant_without_sku(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -2028,6 +2061,7 @@ def test_checkout_with_voucher_complete(
voucher_percentage,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2041,7 +2075,7 @@ def test_checkout_with_voucher_complete(
checkout_with_voucher_percentage,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_voucher_percentage, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2132,6 +2166,7 @@ def test_checkout_with_order_promotion_complete(
checkout_with_item_and_order_discount,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2146,7 +2181,7 @@ def test_checkout_with_order_promotion_complete(
checkout,
address,
address,
- shipping_method,
+ checkout_delivery(checkout, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2211,6 +2246,7 @@ def test_checkout_complete_with_entire_order_voucher_paid_with_gift_card_and_tra
gift_card,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2228,7 +2264,7 @@ def test_checkout_complete_with_entire_order_voucher_paid_with_gift_card_and_tra
checkout_with_voucher_percentage,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_voucher_percentage, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2322,6 +2358,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card(
gift_card,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2330,7 +2367,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card(
checkout_with_voucher_percentage,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_voucher_percentage, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2437,6 +2474,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
voucher_percentage,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
channel_USD,
@@ -2469,7 +2507,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
checkout,
address,
address,
- shipping_method,
+ checkout_delivery(checkout, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2538,6 +2576,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order_and_gift_card(
gift_card,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2572,7 +2611,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order_and_gift_card(
checkout,
address,
address,
- shipping_method,
+ checkout_delivery(checkout, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2650,6 +2689,7 @@ def test_checkout_complete_with_voucher_single_use(
voucher_percentage,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2659,7 +2699,7 @@ def test_checkout_complete_with_voucher_single_use(
checkout_with_voucher_percentage,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_voucher_percentage, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2732,6 +2772,7 @@ def test_checkout_complete_with_shipping_voucher(
checkout_with_voucher_free_shipping,
address,
shipping_method,
+ checkout_delivery,
voucher_free_shipping,
transaction_events_generator,
transaction_item_generator,
@@ -2750,7 +2791,7 @@ def test_checkout_complete_with_shipping_voucher(
checkout,
address,
address,
- shipping_method,
+ checkout_delivery(checkout, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2824,7 +2865,9 @@ def test_checkout_complete_with_shipping_voucher(
assert not order_line.unit_discount_amount
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.shipping_tax_rate is not None
assert order.shipping_tax_class_name == shipping_tax_class.name
assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
@@ -2848,6 +2891,7 @@ def test_checkout_with_voucher_complete_product_on_sale(
catalogue_promotion_without_rules,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -2856,7 +2900,7 @@ def test_checkout_with_voucher_complete_product_on_sale(
checkout_with_voucher_percentage,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_voucher_percentage, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -2990,6 +3034,7 @@ def test_checkout_with_voucher_on_specific_product_complete(
voucher_specific_product_type,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
channel_USD,
@@ -3004,7 +3049,9 @@ def test_checkout_with_voucher_on_specific_product_complete(
checkout_with_item_and_voucher_specific_products,
address,
address,
- shipping_method,
+ checkout_delivery(
+ checkout_with_item_and_voucher_specific_products, shipping_method
+ ),
transaction_item_generator,
transaction_events_generator,
)
@@ -3081,6 +3128,7 @@ def test_checkout_complete_with_voucher_on_specific_product_and_gift_card(
gift_card,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
django_capture_on_commit_callbacks,
@@ -3098,7 +3146,9 @@ def test_checkout_complete_with_voucher_on_specific_product_and_gift_card(
checkout_with_item_and_voucher_specific_products,
address,
address,
- shipping_method,
+ checkout_delivery(
+ checkout_with_item_and_voucher_specific_products, shipping_method
+ ),
transaction_item_generator,
transaction_events_generator,
)
@@ -3188,6 +3238,7 @@ def test_checkout_complete_product_on_promotion(
catalogue_promotion_without_rules,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -3196,7 +3247,7 @@ def test_checkout_complete_product_on_promotion(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -3295,6 +3346,7 @@ def test_checkout_complete_multiple_rules_applied(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
catalogue_promotion_without_rules,
transaction_events_generator,
transaction_item_generator,
@@ -3304,7 +3356,7 @@ def test_checkout_complete_multiple_rules_applied(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -3469,6 +3521,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
catalogue_promotion_with_single_rule,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
channel_USD,
@@ -3483,7 +3536,9 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
checkout_with_item_and_voucher_specific_products,
address,
address,
- shipping_method,
+ checkout_delivery(
+ checkout_with_item_and_voucher_specific_products, shipping_method
+ ),
transaction_item_generator,
transaction_events_generator,
)
@@ -3573,6 +3628,7 @@ def test_checkout_with_voucher_not_increase_uses_on_preprocess_order_creation_fa
voucher_percentage,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -3581,7 +3637,7 @@ def test_checkout_with_voucher_not_increase_uses_on_preprocess_order_creation_fa
checkout_with_voucher_percentage,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_voucher_percentage, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -3620,6 +3676,7 @@ def test_checkout_complete_without_inventory_tracking(
checkout_with_variant_without_inventory_tracking,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -3628,7 +3685,9 @@ def test_checkout_complete_without_inventory_tracking(
checkout_with_variant_without_inventory_tracking,
address,
address,
- shipping_method,
+ checkout_delivery(
+ checkout_with_variant_without_inventory_tracking, shipping_method
+ ),
transaction_item_generator,
transaction_events_generator,
)
@@ -3669,6 +3728,7 @@ def test_checkout_complete_checkout_without_lines(
checkout,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -3677,7 +3737,7 @@ def test_checkout_complete_checkout_without_lines(
checkout,
address,
address,
- shipping_method,
+ checkout_delivery(checkout, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -3714,6 +3774,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
channel_USD,
transaction_events_generator,
transaction_item_generator,
@@ -3723,7 +3784,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -3768,6 +3829,7 @@ def test_checkout_complete_own_reservation(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
channel_USD,
transaction_events_generator,
transaction_item_generator,
@@ -3785,7 +3847,7 @@ def test_checkout_complete_own_reservation(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -3836,6 +3898,7 @@ def test_checkout_complete_without_redirect_url(
gift_card,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -3844,7 +3907,7 @@ def test_checkout_complete_without_redirect_url(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4327,6 +4390,7 @@ def test_checkout_complete_with_preorder_variant(
checkout_with_item_and_preorder_item,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4335,7 +4399,7 @@ def test_checkout_complete_with_preorder_variant(
checkout_with_item_and_preorder_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item_and_preorder_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4464,6 +4528,7 @@ def test_checkout_complete_variant_channel_listing_does_not_exist(
checkout_with_items,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4472,7 +4537,7 @@ def test_checkout_complete_variant_channel_listing_does_not_exist(
checkout_with_items,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_items, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4507,6 +4572,7 @@ def test_checkout_complete_variant_channel_listing_no_price(
checkout_with_items,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4515,7 +4581,7 @@ def test_checkout_complete_variant_channel_listing_no_price(
checkout_with_items,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_items, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4556,6 +4622,7 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
checkout_with_items,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4564,7 +4631,7 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
checkout_with_items,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_items, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4605,6 +4672,7 @@ def test_checkout_complete_product_channel_listing_not_available_for_purchase(
checkout_with_items,
address,
shipping_method,
+ checkout_delivery,
available_for_purchase,
transaction_events_generator,
transaction_item_generator,
@@ -4614,7 +4682,7 @@ def test_checkout_complete_product_channel_listing_not_available_for_purchase(
checkout_with_items,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_items, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4654,6 +4722,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_
gift_card,
address,
shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4672,7 +4741,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_
checkout_with_item,
shipping_address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -4700,7 +4769,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fie
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4720,7 +4789,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fie
checkout_with_item,
shipping_address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -4748,7 +4817,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_f
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4767,7 +4836,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_f
checkout_with_item,
address,
billing_address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -4794,7 +4863,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fiel
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4814,7 +4883,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fiel
checkout_with_item,
address,
billing_address,
- shipping_method,
+ checkout_delivery(checkout_with_item),
transaction_item_generator,
transaction_events_generator,
)
@@ -4843,7 +4912,7 @@ def test_checkout_complete_with_not_normalized_shipping_address(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4860,7 +4929,7 @@ def test_checkout_complete_with_not_normalized_shipping_address(
checkout_with_gift_card,
shipping_address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -4889,7 +4958,7 @@ def test_checkout_complete_with_not_normalized_billing_address(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4905,7 +4974,7 @@ def test_checkout_complete_with_not_normalized_billing_address(
checkout_with_gift_card,
address,
billing_address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -4934,7 +5003,7 @@ def test_checkout_complete_reservations_drop(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4943,7 +5012,7 @@ def test_checkout_complete_reservations_drop(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -4967,7 +5036,7 @@ def test_checkout_complete_line_deleted_in_the_meantime(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
):
@@ -4976,7 +5045,7 @@ def test_checkout_complete_line_deleted_in_the_meantime(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -5008,6 +5077,7 @@ def test_checkout_complete_with_invalid_address(
checkout_with_item,
address,
shipping_method,
+ checkout_delivery,
customer_user,
):
"""Check if checkout can be completed with invalid address.
@@ -5024,7 +5094,7 @@ def test_checkout_complete_with_invalid_address(
address.save(update_fields=["validation_skipped", "postal_code"])
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.tax_exemption = True
checkout.user = customer_user
@@ -5080,7 +5150,7 @@ def test_checkout_complete_log_unknown_discount_reason(
checkout_with_item_and_voucher_specific_products,
voucher_specific_product_type,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
caplog,
@@ -5092,7 +5162,7 @@ def test_checkout_complete_log_unknown_discount_reason(
checkout_with_item_and_voucher_specific_products,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item_and_voucher_specific_products),
transaction_item_generator,
transaction_events_generator,
)
@@ -5126,7 +5196,7 @@ def test_checkout_complete_empty_product_translation(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
caplog,
@@ -5136,7 +5206,7 @@ def test_checkout_complete_empty_product_translation(
checkout_with_gift_card,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_gift_card),
transaction_item_generator,
transaction_events_generator,
)
@@ -5199,7 +5269,9 @@ def test_checkout_complete_empty_product_translation(
assert order_line.translated_variant_name == ""
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
assert order.search_vector
gift_card.refresh_from_db()
@@ -5297,8 +5369,15 @@ def test_checkout_complete_with_external_shipping_method(
mocked_sync_webhook.return_value = mock_json_response
checkout = checkout_with_item
- checkout.external_shipping_method_id = graphql_external_method_id
- checkout.shipping_method_name = external_shipping_name
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=graphql_external_method_id,
+ name=external_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_address = address
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
@@ -5426,8 +5505,15 @@ def test_checkout_complete_with_external_shipping_method_private_metadata(
mocked_sync_webhook.return_value = mock_json_response
checkout = checkout_with_item
- checkout.external_shipping_method_id = graphql_external_method_id
- checkout.shipping_method_name = external_shipping_name
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=graphql_external_method_id,
+ name=external_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_address = address
checkout.billing_address = address
checkout.save()
@@ -5483,7 +5569,7 @@ def test_checkout_complete_saving_addresses_off(
user_api_client,
checkout_with_item_and_voucher_specific_products,
address,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
customer_user,
@@ -5493,7 +5579,7 @@ def test_checkout_complete_saving_addresses_off(
checkout_with_item_and_voucher_specific_products,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item_and_voucher_specific_products),
transaction_item_generator,
transaction_events_generator,
user=customer_user,
@@ -5528,7 +5614,7 @@ def test_checkout_complete_saving_addresses_on(
checkout_with_item_and_voucher_specific_products,
address,
address_usa,
- shipping_method,
+ checkout_delivery,
transaction_events_generator,
transaction_item_generator,
customer_user,
@@ -5538,7 +5624,7 @@ def test_checkout_complete_saving_addresses_on(
checkout_with_item_and_voucher_specific_products,
address,
address_usa,
- shipping_method,
+ checkout_delivery(checkout_with_item_and_voucher_specific_products),
transaction_item_generator,
transaction_events_generator,
user=customer_user,
@@ -5582,7 +5668,6 @@ def test_checkout_complete_with_different_email_than_user_email(
checkout_ready_to_complete,
address,
address_usa,
- shipping_method,
transaction_events_generator,
transaction_item_generator,
customer_user,
@@ -5592,7 +5677,7 @@ def test_checkout_complete_with_different_email_than_user_email(
checkout_ready_to_complete,
address,
address_usa,
- shipping_method,
+ checkout_ready_to_complete.assigned_delivery,
transaction_item_generator,
transaction_events_generator,
user=customer_user,
@@ -5629,7 +5714,6 @@ def test_checkout_complete_sets_product_type_id_for_all_order_lines(
checkout_ready_to_complete,
address,
address_usa,
- shipping_method,
transaction_events_generator,
transaction_item_generator,
customer_user,
@@ -5639,7 +5723,7 @@ def test_checkout_complete_sets_product_type_id_for_all_order_lines(
checkout_ready_to_complete,
address,
address_usa,
- shipping_method,
+ checkout_ready_to_complete.assigned_delivery,
transaction_item_generator,
transaction_events_generator,
user=customer_user,
@@ -5673,6 +5757,55 @@ def test_checkout_complete_sets_product_type_id_for_all_order_lines(
)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_complete."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+def test_complete_refreshes_shipping_methods_when_stale(
+ mocked_get_or_fetch_checkout_deliveries,
+ user_api_client,
+ checkout_ready_to_complete,
+ transaction_item_generator,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+ checkout.gift_cards.all().delete()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert mocked_get_or_fetch_checkout_deliveries.called
+
+
def test_checkout_complete_race_condition_on_preparing_checkout(
user_api_client,
checkout_with_item,
@@ -5681,13 +5814,14 @@ def test_checkout_complete_race_condition_on_preparing_checkout(
transaction_events_generator,
transaction_item_generator,
order,
+ checkout_delivery,
):
# given
checkout = prepare_checkout_for_test(
checkout_with_item,
address,
address,
- shipping_method,
+ checkout_delivery(checkout_with_item, shipping_method),
transaction_item_generator,
transaction_events_generator,
)
@@ -5712,3 +5846,154 @@ def test_checkout_complete_race_condition_on_preparing_checkout(
assert not data["errors"]
assert data["order"]
+
+
+@patch(
+ "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+def test_complete_do_not_refresh_shipping_methods_when_not_stale(
+ mocked_fetch_checkout_deliveries,
+ user_api_client,
+ checkout_ready_to_complete,
+ transaction_item_generator,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now() + datetime.timedelta(hours=1)
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+ checkout.gift_cards.all().delete()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert not mocked_fetch_checkout_deliveries.called
+
+
+@patch(
+ "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+def test_complete_do_not_refresh_shipping_methods_when_cc_is_used(
+ mocked_fetch_checkout_deliveries,
+ user_api_client,
+ checkout_with_delivery_method_for_cc,
+ transaction_item_generator,
+ checkout_delivery,
+ address,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+ checkout.billing_address = address
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert not mocked_fetch_checkout_deliveries.called
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_complete."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+def test_complete_refreshes_shipping_methods_when_stale_and_invalid(
+ mocked_get_or_fetch_checkout_deliveries,
+ user_api_client,
+ checkout_ready_to_complete,
+ transaction_item_generator,
+ checkout_delivery,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+ checkout.gift_cards.all().delete()
+
+ # Shipping is not available anymore
+ ShippingMethod.objects.all().delete()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, None
+ )
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert data["errors"]
+ assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID_SHIPPING_METHOD.name
+
+ assert Order.objects.count() == 0
+ assert mocked_get_or_fetch_checkout_deliveries.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index 1ee8a7f94d..f2a0fa2c17 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -18,7 +18,7 @@ from .....checkout.utils import calculate_checkout_quantity
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
from .....warehouse.models import Reservation, Stock
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import (
assert_no_permission,
get_graphql_content,
@@ -2724,6 +2724,24 @@ def test_checkout_create_skip_validation_billing_address_by_app(
assert new_checkout.billing_address.validation_skipped is True
+MUTATION_CHECKOUT_CREATE_WITH_ONLY_ID = """
+ mutation createCheckout($checkoutInput: CheckoutCreateInput!) {
+ checkoutCreate(input: $checkoutInput) {
+ checkout {
+ id
+ }
+ errors {
+ field
+ message
+ code
+ variants
+ addressType
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_create.call_checkout_event",
wraps=call_checkout_event,
@@ -2732,8 +2750,12 @@ def test_checkout_create_skip_validation_billing_address_by_app(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_create_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_event,
@@ -2774,53 +2796,37 @@ def test_checkout_create_triggers_webhooks(
}
# when
- response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE_WITH_ONLY_ID, variables)
# then
+ checkout = Checkout.objects.first()
content = get_graphql_content(response)
assert not content["data"]["checkoutCreate"]["errors"]
- assert wrapped_call_checkout_event.called
-
# confirm that event delivery was generated for each async webhook.
checkout_create_delivery = EventDelivery.objects.get(
webhook_id=checkout_created_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_create_delivery.id,
+ "event_delivery_ids": [checkout_create_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_created_webhook.id
- ).exists()
-
- sync_deliveries = {
- call.args[0].event_type: call.args[0]
- for call in mocked_send_webhook_request_sync.mock_calls
- }
-
- assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
- shipping_methods_delivery = sync_deliveries[
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
- filter_shipping_delivery = sync_deliveries[
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- ]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
@pytest.mark.parametrize(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
index d7dd9a85bf..4f51ddbb83 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
@@ -3,13 +3,15 @@ from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....account.models import User
from .....checkout.actions import call_checkout_event
from .....checkout.error_codes import CheckoutErrorCode
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -296,8 +298,12 @@ def test_with_active_problems_flow(user_api_client, checkout_with_problems):
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_customer_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_event,
@@ -346,39 +352,69 @@ def test_checkout_customer_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_customer_attach_do_not_mark_shipping_as_stale(
+ user_api_client,
+ checkout_with_item,
+ customer_user2,
+ permission_impersonate_user,
+ checkout_delivery,
+ address,
+):
+ # given
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+
+ checkout = checkout_with_item
+ checkout.email = "[email protected]"
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH
+ customer_id = graphene.Node.to_global_id("User", customer_user2.pk)
+ variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}
+
+ # when
+ new_now = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(
+ query, variables, permissions=[permission_impersonate_user]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutCustomerAttach"]
+ assert not data["errors"]
+ assert data["checkout"]["email"] == customer_user2.email
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
index ab5dde260a..d58906f581 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
@@ -2,12 +2,14 @@ from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....account.models import User
from .....checkout.actions import call_checkout_event
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -166,8 +168,12 @@ def test_with_active_problems_flow(user_api_client, checkout_with_problems):
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_customer_detach_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_event,
@@ -179,7 +185,6 @@ def test_checkout_customer_detach_triggers_webhooks(
address,
):
# given
- mocked_send_webhook_request_sync.return_value = []
(
tax_webhook,
shipping_webhook,
@@ -213,39 +218,62 @@ def test_checkout_customer_detach_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+def test_checkout_customer_detach_do_not_mark_shipping_as_stale(
+ user_api_client,
+ checkout_with_item,
+ customer_user,
+ checkout_delivery,
+ address,
+):
+ # given
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+
+ checkout = checkout_with_item
+ checkout.user = customer_user
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ new_now = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCustomerDetach"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
index 0a6b9b9add..1162b2f361 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
@@ -2,11 +2,13 @@ from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_event
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -127,8 +129,12 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_customer_note_update_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_event,
@@ -175,39 +181,60 @@ def test_checkout_customer_note_update_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_customer_note_update_do_not_mark_shipping_as_stale(
+ user_api_client, checkout_with_item, checkout_delivery, address
+):
+ # given
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+
+ checkout = checkout_with_item
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ customer_note = "New customer note value"
+ variables = {"id": to_global_id_or_none(checkout), "customerNote": customer_note}
+
+ # when
+ new_now = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(
+ CHECKOUT_CUSTOMER_NOTE_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCustomerNoteUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
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 2b585399fc..8399c0eb91 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
@@ -10,19 +10,18 @@ from .....account.models import Address
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout
+from .....checkout.models import CheckoutDelivery
+from .....checkout.utils import invalidate_checkout
from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
from .....shipping import models as shipping_models
from .....shipping.models import ShippingZone
-from .....shipping.utils import convert_to_shipping_method_data
from .....warehouse import WarehouseClickAndCollectOption
from .....warehouse.models import Stock, Warehouse
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
-from ...mutations.utils import clean_delivery_method
MUTATION_UPDATE_DELIVERY_METHOD = """
mutation checkoutDeliveryMethodUpdate($id: ID, $deliveryMethodId: ID) {
@@ -75,18 +74,12 @@ MUTATION_UPDATE_DELIVERY_METHOD = """
],
indirect=("delivery_method",),
)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method",
- wraps=clean_delivery_method,
-)
@patch(
"saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_not_applicable_delivery_method(
mocked_invalidate_checkout,
- mocked_clean_delivery_method,
api_client,
delivery_method,
node_name,
@@ -121,37 +114,33 @@ def test_checkout_delivery_method_update_not_applicable_delivery_method(
assert checkout.shipping_method is None
assert checkout.collection_point is None
mocked_invalidate_checkout.assert_not_called()
- mocked_clean_delivery_method.assert_called_once()
@pytest.mark.parametrize(
("delivery_method", "node_name", "attribute_name"),
[
("warehouse", "Warehouse", "collection_point"),
- ("shipping_method", "ShippingMethod", "shipping_method"),
+ ("shipping_method", "ShippingMethod", "assigned_delivery"),
],
indirect=("delivery_method",),
)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method",
- wraps=clean_delivery_method,
-)
@patch(
"saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update(
mocked_invalidate_checkout,
- mocked_clean_delivery_method,
api_client,
delivery_method,
node_name,
attribute_name,
checkout_with_item_for_cc,
+ address,
):
# given
checkout = checkout_with_item_for_cc
+ checkout.shipping_address = address
+ checkout.save()
method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
@@ -167,9 +156,8 @@ def test_checkout_delivery_method_update(
errors = data["errors"]
assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
+ assert getattr(checkout, attribute_name)
mocked_invalidate_checkout.assert_called_once()
- mocked_clean_delivery_method.assert_called_once()
@pytest.mark.parametrize(
@@ -230,18 +218,12 @@ def test_checkout_delivery_method_update_when_line_without_channel_listing(
],
indirect=("delivery_method",),
)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method",
- wraps=clean_delivery_method,
-)
@patch(
"saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_missing_checkout_metadata_when_not_applicable_method(
mocked_invalidate_checkout,
- mocked_clean_delivery_method,
api_client,
delivery_method,
node_name,
@@ -277,29 +259,22 @@ def test_checkout_delivery_method_update_missing_checkout_metadata_when_not_appl
assert checkout.shipping_method is None
assert checkout.collection_point is None
mocked_invalidate_checkout.assert_not_called()
- mocked_clean_delivery_method.assert_called_once()
@pytest.mark.parametrize(
("delivery_method", "node_name", "attribute_name"),
[
("warehouse", "Warehouse", "collection_point"),
- ("shipping_method", "ShippingMethod", "shipping_method"),
+ ("shipping_method", "ShippingMethod", "assigned_delivery"),
],
indirect=("delivery_method",),
)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method",
- wraps=clean_delivery_method,
-)
@patch(
"saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_checkout_without_metadata(
mocked_invalidate_checkout,
- mocked_clean_delivery_method,
api_client,
delivery_method,
node_name,
@@ -323,18 +298,12 @@ def test_checkout_delivery_method_update_checkout_without_metadata(
errors = data["errors"]
assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
+ assert getattr(checkout, attribute_name)
mocked_invalidate_checkout.assert_called_once()
- mocked_clean_delivery_method.assert_called_once()
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
def test_checkout_delivery_method_update_external_shipping(
- mock_clean_delivery,
mock_send_request,
api_client,
checkout_with_item_for_cc,
@@ -344,7 +313,6 @@ def test_checkout_delivery_method_update_external_shipping(
):
checkout = checkout_with_item_for_cc
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
@@ -374,10 +342,7 @@ def test_checkout_delivery_method_update_external_shipping(
errors = data["errors"]
assert not errors
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id
+ assert checkout.assigned_delivery
assert checkout.shipping_method_name == response_shipping_name
assert checkout.undiscounted_base_shipping_price_amount == Decimal(
response_shipping_price
@@ -386,12 +351,7 @@ def test_checkout_delivery_method_update_external_shipping(
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
def test_checkout_delivery_method_update_external_shipping_long_external_id(
- mock_clean_delivery,
mock_send_request,
api_client,
checkout_with_item_for_cc,
@@ -401,7 +361,6 @@ def test_checkout_delivery_method_update_external_shipping_long_external_id(
):
checkout = checkout_with_item_for_cc
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "A" * 700 # External ID longer than 512 characters
@@ -431,20 +390,13 @@ def test_checkout_delivery_method_update_external_shipping_long_external_id(
errors = data["errors"]
assert not errors
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id == method_id
- assert len(checkout.external_shipping_method_id) > 900
+ assert checkout.assigned_delivery
+ assert checkout.assigned_delivery.external_shipping_method_id == method_id
+ assert len(checkout.assigned_delivery.external_shipping_method_id) > 900
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
def test_checkout_delivery_method_update_external_shipping_when_invalid(
- mock_clean_delivery,
mock_send_request,
api_client,
checkout_with_item_for_cc,
@@ -455,22 +407,10 @@ def test_checkout_delivery_method_update_external_shipping_when_invalid(
# given
checkout = checkout_with_item_for_cc
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = False
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
- response_shipping_name = "Provider - Economy"
- response_shipping_price = "10"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": response_shipping_name,
- "amount": response_shipping_price,
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- mock_send_request.return_value = mock_json_response
+ mock_send_request.return_value = []
method_id = graphene.Node.to_global_id(
"app", f"{shipping_app.id}:{response_method_id}"
@@ -489,64 +429,50 @@ def test_checkout_delivery_method_update_external_shipping_when_invalid(
assert len(errors) == 1
assert errors[0]["field"] == "deliveryMethodId"
assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.shipping_method_name is None
assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
-def test_checkout_delivery_method_update_deletes_external_shipping_when_not_valid(
- mock_clean_delivery,
+def test_checkout_delivery_method_update_keeps_shipping_when_invalid(
mock_send_request,
api_client,
checkout_with_item_for_cc,
settings,
shipping_app,
- channel_USD,
- shipping_method,
):
# given
checkout = checkout_with_item_for_cc
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- mock_send_request.return_value = mock_json_response
- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ mock_send_request.return_value = []
- checkout.external_shipping_method_id = graphene.Node.to_global_id(
+ external_shipping_method_id = graphene.Node.to_global_id(
"app", f"{shipping_app.id}:{response_method_id}"
)
- checkout.save(update_fields=["external_shipping_method_id"])
- checkout.metadata_storage.private_metadata = {
- PRIVATE_META_APP_SHIPPING_ID: graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
- }
- checkout.metadata_storage.save()
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout_id=checkout.pk,
+ external_shipping_method_id=external_shipping_method_id,
+ name="External",
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
+ checkout.save()
# when
response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ query,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": external_shipping_method_id,
+ },
)
# then
@@ -555,61 +481,15 @@ def test_checkout_delivery_method_update_deletes_external_shipping_when_not_vali
errors = data["errors"]
- assert not errors
- assert (
- PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
- )
- assert checkout.external_shipping_method_id is None
- assert data["checkout"]["deliveryMethod"]["id"] == method_id
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_checkout_delivery_method_update_external_shipping_invalid_currency(
- mock_send_request,
- api_client,
- checkout_with_item_for_cc,
- settings,
- shipping_app,
-):
- # given
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- checkout = checkout_with_item_for_cc
- response_method_id = "abcd"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "AUD", # checkout currency is USD
- "maximum_delivery_days": "7",
- }
- ]
- mock_send_request.return_value = mock_json_response
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
- query = MUTATION_UPDATE_DELIVERY_METHOD
-
- # when
- response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
- )
-
- # then
- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
- errors = data["errors"]
+ assert errors
assert len(errors) == 1
assert errors[0]["field"] == "deliveryMethodId"
- assert errors[0]["code"] == CheckoutErrorCode.NOT_FOUND.name
- assert errors[0]["message"] == f"Couldn't resolve to a node: ${method_id}"
+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+
+ assert checkout.assigned_delivery
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_error(
- mock_clean_delivery,
api_client,
checkout_with_item,
address,
@@ -618,7 +498,7 @@ def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_er
checkout.shipping_address = address
checkout.save(update_fields=["shipping_address"])
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
+
invalid_method_id = graphene.Node.to_global_id("Address", address.id)
response = api_client.post_graphql(
@@ -639,24 +519,21 @@ def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_er
assert checkout.collection_point is None
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
-def test_checkout_delivery_method_with_nonexistant_id_results_not_found(
- mock_clean_delivery,
+def test_checkout_delivery_method_with_nonexistant_id_results_not_applicable(
api_client,
warehouse_for_cc,
checkout_with_item,
address,
):
+ # given
checkout = checkout_with_item
checkout.shipping_address = address
checkout.save(update_fields=["shipping_address"])
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
nonexistant_id = "YXBwOjEyMzQ6c29tZS1pZA=="
+
+ # when
response = api_client.post_graphql(
query,
{
@@ -664,45 +541,46 @@ def test_checkout_delivery_method_with_nonexistant_id_results_not_found(
"deliveryMethodId": nonexistant_id,
},
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
assert not data["checkout"]
assert data["errors"][0]["field"] == "deliveryMethodId"
- assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name
- assert checkout.shipping_method is None
+ assert (
+ data["errors"][0]["code"]
+ == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+ )
+ assert checkout.assigned_delivery is None
assert checkout.collection_point is None
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_delivery_method_with_empty_fields_results_None(
- mock_clean_delivery,
- api_client,
- warehouse_for_cc,
- checkout_with_item,
- address,
+ api_client, checkout_with_item, address, checkout_delivery
):
+ # given
checkout = checkout_with_item
checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save(update_fields=["shipping_address"])
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
+ # when
response = api_client.post_graphql(
query,
{
"id": to_global_id_or_none(checkout),
},
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
assert not data["errors"]
assert data["checkout"]["deliveryMethod"] is None
- assert checkout.shipping_method is None
+ assert checkout.assigned_delivery is None
assert checkout.collection_point is None
@@ -714,6 +592,7 @@ def test_checkout_delivery_method_update_excluded_postal_code(
checkout_with_item,
address,
):
+ # given
checkout = checkout_with_item
checkout.shipping_address = address
checkout.save(update_fields=["shipping_address"])
@@ -722,9 +601,12 @@ def test_checkout_delivery_method_update_excluded_postal_code(
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ # when
response = staff_api_client.post_graphql(
query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
@@ -733,7 +615,7 @@ def test_checkout_delivery_method_update_excluded_postal_code(
assert len(errors) == 1
assert errors[0]["field"] == "deliveryMethodId"
assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
+ assert checkout.assigned_delivery is None
assert (
mock_is_shipping_method_available.call_count
== shipping_models.ShippingMethod.objects.count()
@@ -746,6 +628,7 @@ def test_checkout_delivery_method_update_shipping_zone_without_channel(
checkout_with_item,
address,
):
+ # given
shipping_method.shipping_zone.channels.clear()
shipping_method.channel_listings.all().delete()
checkout = checkout_with_item
@@ -755,9 +638,12 @@ def test_checkout_delivery_method_update_shipping_zone_without_channel(
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ # when
response = api_client.post_graphql(
query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
@@ -766,7 +652,7 @@ def test_checkout_delivery_method_update_shipping_zone_without_channel(
assert len(errors) == 1
assert errors[0]["field"] == "deliveryMethodId"
assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
+ assert checkout.assigned_delivery is None
def test_checkout_delivery_method_update_shipping_zone_with_channel(
@@ -793,40 +679,23 @@ def test_checkout_delivery_method_update_shipping_zone_with_channel(
errors = data["errors"]
assert not errors
- assert checkout.shipping_method == shipping_method
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
- ("delivery_method", "node_name", "attribute_name"),
- [
- ("shipping_method", "ShippingMethod", "shipping_method"),
- ],
- indirect=("delivery_method",),
-)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method",
- wraps=clean_delivery_method,
-)
def test_checkout_delivery_method_update_valid_method_not_all_shipping_data(
- mock_clean_delivery,
api_client,
- delivery_method,
- node_name,
- attribute_name,
+ shipping_method,
checkout_with_item_for_cc,
):
# given
- mock_clean_delivery.return_value = True
checkout = checkout_with_item_for_cc
checkout.shipping_address = Address.objects.create(country="US")
checkout.save()
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
# when
response = api_client.post_graphql(
@@ -840,32 +709,15 @@ def test_checkout_delivery_method_update_valid_method_not_all_shipping_data(
errors = data["errors"]
assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
- mock_clean_delivery.assert_called_once()
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
- "delivery_method, node_name, attribute_name", # noqa: PT006
- [
- ("warehouse", "Warehouse", "collection_point"),
- ],
- indirect=("delivery_method",),
-)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
def test_checkout_delivery_method_update_valid_method_not_all_shipping_data_for_cc(
- mock_clean_delivery,
api_client,
- delivery_method,
- node_name,
- attribute_name,
checkout_with_item_for_cc,
warehouse_for_cc,
):
# given
- mock_clean_delivery.return_value = True
checkout_address = Address.objects.create(country="US")
checkout = checkout_with_item_for_cc
checkout.shipping_address = checkout_address
@@ -874,255 +726,11 @@ def test_checkout_delivery_method_update_valid_method_not_all_shipping_data_for_
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_method_data = delivery_method
- checkout_info.shipping_address = shipping_method_data.address
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
-
- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
-
- # when
- response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
- )
-
- # then
- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
- checkout.refresh_from_db()
-
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
- )
- errors = data["errors"]
- assert checkout.shipping_address == delivery_method.address
- assert checkout.shipping_address_id != delivery_method.address.id
- assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
-
-
- ("delivery_method", "node_name", "attribute_name"),
- [
- ("warehouse", "Warehouse", "collection_point"),
- ("shipping_method", "ShippingMethod", "shipping_method"),
- ],
- indirect=("delivery_method",),
-)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
-def test_checkout_delivery_method_update_invalid_method_not_all_shipping_data(
- mock_clean_delivery,
- api_client,
- delivery_method,
- node_name,
- attribute_name,
- checkout_with_item_for_cc,
-):
- # given
- mock_clean_delivery.return_value = False
-
- checkout = checkout_with_item_for_cc
- checkout.shipping_address = Address.objects.create(country="US")
- checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- shipping_method_data = delivery_method
- if attribute_name == "shipping_method":
- shipping_method_data = convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.get(),
- )
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = False
-
- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
-
- # when
- response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
- )
-
- # then
- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
- checkout.refresh_from_db()
-
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
- )
- errors = data["errors"]
-
- assert len(errors) == 1
- assert errors[0]["field"] == "deliveryMethodId"
- assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
- assert checkout.collection_point is None
-
-
- "delivery_method, node_name, attribute_name", # noqa: PT006
- [
- ("warehouse", "Warehouse", "collection_point"),
- ("shipping_method", "ShippingMethod", "shipping_method"),
- ],
- indirect=("delivery_method",),
-)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
-def test_checkout_delivery_method_update_invalid_with_not_valid_address_data(
- mock_clean_delivery,
- api_client,
- delivery_method,
- node_name,
- attribute_name,
- checkout_with_item_for_cc,
-):
- # given
- mock_clean_delivery.return_value = False
-
- checkout = checkout_with_item_for_cc
- checkout.shipping_address = Address.objects.create(
- country="US",
- city="New York",
- city_area="ABC",
- street_address_1="New street",
- postal_code="53-601",
- )
- checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- shipping_method_data = delivery_method
- if attribute_name == "shipping_method":
- shipping_method_data = convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.get(),
- )
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = False
-
- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
-
- # when
- response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
- )
-
- # then
- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
- checkout.refresh_from_db()
-
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
- )
- errors = data["errors"]
-
- assert len(errors) == 1
- assert errors[0]["field"] == "deliveryMethodId"
- assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
- assert checkout.collection_point is None
-
-
- "delivery_method, node_name, attribute_name", # noqa: PT006
- [
- ("shipping_method", "ShippingMethod", "shipping_method"),
- ],
- indirect=("delivery_method",),
-)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method",
- wraps=clean_delivery_method,
-)
-def test_checkout_delivery_method_update_valid_with_not_valid_address_data(
- mock_clean_delivery,
- api_client,
- delivery_method,
- node_name,
- attribute_name,
- checkout_with_item_for_cc,
-):
- # given
- mock_clean_delivery.return_value = True
-
- checkout = checkout_with_item_for_cc
- checkout.shipping_address = Address.objects.create(
- country="US",
- city="New York",
- city_area="ABC",
- street_address_1="New street",
- postal_code="53-601",
- )
- checkout.save()
-
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
-
- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
-
- # when
- response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
- )
-
- # then
- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
- checkout.refresh_from_db()
- errors = data["errors"]
- assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
- mock_clean_delivery.assert_called_once()
-
-
- "delivery_method, node_name, attribute_name", # noqa: PT006
- [
- ("warehouse", "Warehouse", "collection_point"),
- ],
- indirect=("delivery_method",),
-)
-@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
-)
-def test_checkout_delivery_method_update_valid_with_not_valid_address_data_for_cc(
- mock_clean_delivery,
- api_client,
- delivery_method,
- node_name,
- attribute_name,
- checkout_with_item_for_cc,
-):
- # given
- mock_clean_delivery.return_value = True
-
- checkout = checkout_with_item_for_cc
- checkout.shipping_address = Address.objects.create(
- country="US",
- city="New York",
- city_area="ABC",
- street_address_1="New street",
- postal_code="53-601",
- )
- checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_info.shipping_address = warehouse_for_cc.address
- shipping_method_data = delivery_method
- checkout_info.shipping_address = shipping_method_data.address
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+ method_id = graphene.Node.to_global_id("Warehouse", warehouse_for_cc.id)
# when
response = api_client.post_graphql(
@@ -1133,13 +741,11 @@ def test_checkout_delivery_method_update_valid_with_not_valid_address_data_for_c
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
- )
errors = data["errors"]
-
+ assert checkout.shipping_address == warehouse_for_cc.address
+ assert checkout.shipping_address_id != warehouse_for_cc.address.id
assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
+ assert checkout.collection_point == warehouse_for_cc
def test_with_active_problems_flow(
@@ -1278,6 +884,22 @@ def test_checkout_delivery_method_update_from_cc_to_all_warehouses_disabled_cc(
assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+MUTATION_UPDATE_DELIVERY_METHOD_WITH_ONLY_ID = """
+ mutation checkoutDeliveryMethodUpdate($id: ID, $deliveryMethodId: ID) {
+ checkoutDeliveryMethodUpdate(id: $id, deliveryMethodId: $deliveryMethodId) {
+ checkout {
+ id
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -1286,8 +908,12 @@ def test_checkout_delivery_method_update_from_cc_to_all_warehouses_disabled_cc(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_delivery_method_update_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1310,13 +936,13 @@ def test_checkout_delivery_method_update_triggers_webhooks(
checkout = checkout_with_item
checkout.shipping_address = address
checkout.save(update_fields=["shipping_address"])
- query = MUTATION_UPDATE_DELIVERY_METHOD
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
# when
response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ MUTATION_UPDATE_DELIVERY_METHOD_WITH_ONLY_ID,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
# then
@@ -1329,20 +955,25 @@ def test_checkout_delivery_method_update_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 4
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the async actions
+ assert not mocked_send_webhook_request_async.called
sync_deliveries = {
call.args[0].event_type: call.args[0]
@@ -1361,9 +992,7 @@ def test_checkout_delivery_method_update_triggers_webhooks(
]
assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES not in sync_deliveries
@patch(
@@ -1374,8 +1003,12 @@ def test_checkout_delivery_method_update_triggers_webhooks(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_delivery_method_update_cc_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1406,12 +1039,12 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
product_variant=checkout.lines.first().variant,
quantity=1,
)
+ method_id = graphene.Node.to_global_id("Warehouse", warehouse_cc_all.id)
# when
- query = MUTATION_UPDATE_DELIVERY_METHOD
- method_id = graphene.Node.to_global_id("Warehouse", warehouse_cc_all.id)
response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ MUTATION_UPDATE_DELIVERY_METHOD_WITH_ONLY_ID,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
# then
@@ -1423,45 +1056,26 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # Shipping sync webhooks are called twice - first call before saving the changes in
- # the checkout instance, second when generating the payload. In the second call
- # checkout instance has different data and cache cannot be used.
- assert mocked_send_webhook_request_sync.call_count == 3
-
- # confirm each sync webhook was called without saving event delivery
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- sync_deliveries = {
- call.args[0].event_type: call.args[0]
- for call in mocked_send_webhook_request_sync.mock_calls
- }
-
- assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
- shipping_methods_delivery = sync_deliveries[
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
- filter_shipping_delivery = sync_deliveries[
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- ]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
@patch(
@@ -1472,13 +1086,12 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
)
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
- mock_clean_delivery,
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1496,8 +1109,6 @@ def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
checkout = checkout_with_item_for_cc
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = True
response_method_id = "abcd"
mock_json_response = [
@@ -1521,7 +1132,8 @@ def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
# when
response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ MUTATION_UPDATE_DELIVERY_METHOD_WITH_ONLY_ID,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
# then
@@ -1530,46 +1142,47 @@ def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
assert wrapped_call_checkout_info_event.called
- # confirm that event delivery was generated for each async webhook.
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the async actions
+ assert not mocked_send_webhook_request_async.called
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
+ sync_deliveries = {
+ call.args[0].event_type: call.args[0]
+ for call in mocked_send_webhook_request_sync.mock_calls
+ }
+
+ assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
+ shipping_methods_delivery = sync_deliveries[
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
+ ]
assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- filter_shipping_delivery = filter_shipping_call.args[0]
+ assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
+ filter_shipping_delivery = sync_deliveries[
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ ]
assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- )
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES not in sync_deliveries
@mock.patch(
@@ -1632,7 +1245,7 @@ def test_checkout_delivery_method_update_from_cc_to_external_shipping(
assert checkout.collection_point_id is None
assert checkout.shipping_address_id is None
assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == method_id
assert checkout.shipping_method_name == response_shipping_name
assert checkout.save_billing_address is True
# should be reset to the default value as the shipping address is cleared
@@ -1677,8 +1290,7 @@ def test_checkout_delivery_method_update_from_cc_to_none(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
assert checkout.shipping_address_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
assert checkout.save_billing_address is True
# should be reset to the default value as the shipping address is cleared
@@ -1730,8 +1342,7 @@ def test_checkout_delivery_method_update_from_cc_to_built_in_shipping(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
assert checkout.shipping_address_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
assert checkout.shipping_method_name == shipping_method.name
assert checkout.save_billing_address is True
# should be reset to the default value as the shipping address is cleared
@@ -1785,8 +1396,7 @@ def test_checkout_delivery_method_update_from_cc_to_the_same_cc(
assert checkout.collection_point_id == collection_point.id
assert checkout.shipping_address_id != collection_point.address.id
assert checkout.shipping_address == collection_point.address
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
assert checkout.save_billing_address is True
# the flag remain unchanged as the address stay the same
@@ -1848,8 +1458,7 @@ def test_checkout_delivery_method_update_from_cc_to_different_cc(
assert checkout.collection_point_id == collection_point.id
assert checkout.shipping_address_id != collection_point.address.id
assert checkout.shipping_address == collection_point.address
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
assert checkout.save_billing_address is True
# set the save_shipping_address setting to False for CC
@@ -1913,8 +1522,7 @@ def test_checkout_delivery_method_update_from_external_shipping_to_cc(
assert checkout.collection_point_id == collection_point.id
assert checkout.shipping_address_id != collection_point.address.id
assert checkout.shipping_address == collection_point.address
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
assert checkout.save_billing_address is True
# set the save_shipping_address setting to False for CC
@@ -1966,8 +1574,7 @@ def test_checkout_delivery_method_update_from_external_shipping_to_built_in_ship
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
assert checkout.shipping_method_name == shipping_method.name
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
@@ -2035,8 +1642,7 @@ def test_checkout_delivery_method_update_from_external_shipping_to_different_ext
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == str(method_id)
assert checkout.shipping_method_name == response_shipping_name
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
@@ -2080,8 +1686,7 @@ def test_checkout_delivery_method_update_from_external_shipping_to_none(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
# the flags should not be changed as shipping address is not reset
assert checkout.save_billing_address is True
@@ -2133,7 +1738,15 @@ def test_checkout_delivery_method_update_from_external_shipping_to_the_same_exte
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.external_shipping_method_id = method_id
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=method_id,
+ name=response_shipping_name,
+ price_amount=response_shipping_price,
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_method_name = response_shipping_name
checkout.undiscounted_base_shipping_price_amount = Decimal(response_shipping_price)
checkout.save_billing_address = True
@@ -2156,8 +1769,7 @@ def test_checkout_delivery_method_update_from_external_shipping_to_the_same_exte
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == str(method_id)
assert checkout.shipping_method_name == response_shipping_name
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
@@ -2219,8 +1831,7 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_cc(
assert checkout.collection_point_id == collection_point.id
assert checkout.shipping_address_id != collection_point.address.id
assert checkout.shipping_address == collection_point.address
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
assert checkout.save_billing_address is True
# set the save_shipping_address setting to False for CC
@@ -2290,7 +1901,7 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_external_ship
checkout.refresh_from_db()
assert checkout.collection_point_id is None
assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == str(method_id)
assert checkout.shipping_method_name == response_shipping_name
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
@@ -2340,8 +1951,9 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_differnt_buil
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == other_shipping_method.id
+ assert checkout.assigned_delivery.shipping_method_id == str(
+ other_shipping_method.id
+ )
assert checkout.shipping_method_name == other_shipping_method.name
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
@@ -2362,13 +1974,17 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_the_same_ship
mocked_invalidate_checkout,
mocked_call_checkout_info_event,
checkout_with_shipping_method,
+ checkout_delivery,
+ shipping_method,
api_client,
):
# given
checkout = checkout_with_shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.shipping_method_name = shipping_method.name
checkout.save_billing_address = True
checkout.save_shipping_address = True
- shipping_method = checkout.shipping_method
+
price = shipping_method.channel_listings.get().price
checkout.undiscounted_base_shipping_price_amount = price.amount
checkout.save()
@@ -2393,8 +2009,7 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_the_same_ship
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
assert checkout.shipping_method_name == shipping_method.name
assert checkout.save_billing_address is True
assert checkout.save_shipping_address is True
@@ -2437,8 +2052,7 @@ def test_checkout_delivery_method_update_from_built_in_shipping_to_none(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
# the flags should not be changed as shipping address is not reset
assert checkout.save_billing_address is True
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
index 3f2c3e8829..62362a33c8 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
@@ -2,12 +2,14 @@ from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_event
from .....checkout.error_codes import CheckoutErrorCode
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -165,8 +167,12 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_email_update_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_event,
@@ -177,7 +183,6 @@ def test_checkout_email_update_triggers_webhooks(
address,
):
# given
- mocked_send_webhook_request_sync.return_value = []
(
tax_webhook,
shipping_webhook,
@@ -210,39 +215,62 @@ def test_checkout_email_update_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_email_update_do_not_mark_shipping_as_stale(
+ user_api_client, checkout_with_item, checkout_delivery, address
+):
+ # given
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+
+ checkout = checkout_with_item
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ email = "[email protected]"
+ variables = {"id": to_global_id_or_none(checkout), "email": email}
+
+ # when
+ # when
+ new_now = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(
+ CHECKOUT_EMAIL_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutEmailUpdate"]
+ assert not data["errors"]
+ assert data["checkout"]["email"] == email
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
index cb586379a8..18c7433b63 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
@@ -2,11 +2,13 @@ from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_event
from .....core.models import EventDelivery
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -122,8 +124,12 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_update_language_code_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_event,
@@ -168,39 +174,61 @@ def test_checkout_update_language_code_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_update_language_code_do_not_mark_shipping_as_stale(
+ user_api_client, checkout_with_item, checkout_delivery, address
+):
+ # given
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+
+ checkout = checkout_with_item
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ language_code = "PL"
+ variables = {"id": to_global_id_or_none(checkout), "languageCode": language_code}
+
+ # when
+ new_now = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE, variables
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLanguageCodeUpdate"]
+ assert not data["errors"]
+
+ assert data["checkout"]["languageCode"] == language_code
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
index f3c30dc1e1..4b1105de52 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
@@ -4,6 +4,8 @@ from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....checkout import base_calculations
from .....checkout.actions import call_checkout_info_event
@@ -19,10 +21,10 @@ from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
from .....warehouse.models import Reservation
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINE_DELETE = """
mutation checkoutLineDelete($id: ID, $lineId: ID!) {
@@ -48,8 +50,8 @@ MUTATION_CHECKOUT_LINE_DELETE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout",
@@ -57,10 +59,11 @@ MUTATION_CHECKOUT_LINE_DELETE = """
)
def test_checkout_line_delete(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_method_as_stale,
user_api_client,
checkout_line_with_reservation_in_many_stocks,
):
+ # given
assert Reservation.objects.count() == 2
checkout = checkout_line_with_reservation_in_many_stocks.checkout
previous_last_change = checkout.last_change
@@ -73,9 +76,12 @@ def test_checkout_line_delete(
line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}
+
+ # when
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)
- content = get_graphql_content(response)
+ # then
+ content = get_graphql_content(response)
data = content["data"]["checkoutLineDelete"]
assert not data["errors"]
checkout.refresh_from_db()
@@ -85,7 +91,9 @@ def test_checkout_line_delete(
assert Reservation.objects.count() == 0
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_method_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -99,8 +107,8 @@ def test_checkout_line_delete(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout",
@@ -108,7 +116,7 @@ def test_checkout_line_delete(
)
def test_checkout_line_delete_when_variant_without_channel_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_method_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -147,7 +155,9 @@ def test_checkout_line_delete_when_variant_without_channel_listing(
assert Reservation.objects.count() == 0
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_method_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -161,8 +171,8 @@ def test_checkout_line_delete_when_variant_without_channel_listing(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout",
@@ -170,7 +180,7 @@ def test_checkout_line_delete_when_variant_without_channel_listing(
)
def test_checkout_line_delete_when_checkout_has_line_without_channel_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_method_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -208,7 +218,9 @@ def test_checkout_line_delete_when_checkout_has_line_without_channel_listing(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_method_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -248,14 +260,20 @@ def test_checkout_lines_delete_with_not_applicable_voucher(
assert checkout_with_item.voucher_code is None
-def test_checkout_line_delete_remove_shipping_if_removed_product_with_shipping(
- user_api_client, checkout_with_item, digital_content, address, shipping_method
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_line_marks_shipping_as_stale_if_removed_product_with_shipping(
+ user_api_client,
+ checkout_with_item,
+ digital_content,
+ address,
+ checkout_delivery,
):
checkout = checkout_with_item
digital_variant = digital_content.product_variant
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
+
checkout_info = fetch_checkout_info(
checkout, [], get_plugins_manager(allow_replica=False)
)
@@ -272,7 +290,8 @@ def test_checkout_line_delete_remove_shipping_if_removed_product_with_shipping(
assert not data["errors"]
checkout.refresh_from_db()
assert checkout.lines.count() == 1
- assert not checkout.shipping_method
+ assert checkout.assigned_delivery
+ assert checkout.delivery_methods_stale_at == timezone.now()
def test_with_active_problems_flow(
@@ -330,6 +349,28 @@ def test_checkout_line_delete_non_removable_gift(user_api_client, checkout_line)
assert errors[0]["code"] == CheckoutErrorCode.NON_REMOVABLE_GIFT_LINE.name
+MUTATION_CHECKOUT_LINE_DELETE_WITH_ONLY_ID = """
+ mutation checkoutLineDelete($id: ID, $lineId: ID!) {
+ checkoutLineDelete(id: $id, lineId: $lineId) {
+ checkout {
+ token
+ lines {
+ quantity
+ variant {
+ id
+ }
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_line_delete.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -338,8 +379,12 @@ def test_checkout_line_delete_non_removable_gift(user_api_client, checkout_line)
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_line_delete_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -351,7 +396,6 @@ def test_checkout_line_delete_triggers_webhooks(
address,
):
# given
- mocked_send_webhook_request_sync.return_value = []
(
tax_webhook,
shipping_webhook,
@@ -381,7 +425,7 @@ def test_checkout_line_delete_triggers_webhooks(
# when
response = api_client.post_graphql(
- MUTATION_CHECKOUT_LINE_DELETE,
+ MUTATION_CHECKOUT_LINE_DELETE_WITH_ONLY_ID,
variables,
)
@@ -395,39 +439,23 @@ def test_checkout_line_delete_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_items.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
- )
-
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ bind=True,
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 66e615841f..53a4e46d28 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -1,20 +1,19 @@
import datetime
from decimal import Decimal
from unittest import mock
-from unittest.mock import patch
+from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
from django.utils import timezone
-from prices import Money
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
from .....checkout.utils import (
- PRIVATE_META_APP_SHIPPING_ID,
add_variants_to_checkout,
calculate_checkout_quantity,
invalidate_checkout,
@@ -24,14 +23,12 @@ from .....core.models import EventDelivery
from .....discount import RewardType, RewardValueType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....shipping.interface import ShippingMethodData
from .....tests import race_condition
from .....warehouse import WarehouseClickAndCollectOption
from .....warehouse.models import Reservation, Stock
from .....warehouse.tests.utils import get_available_quantity_for_stock
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.transport.asynchronous.transport import send_webhook_request_async
-from .....webhook.transport.utils import WebhookResponse
from ....core.mutations import MISSING_NODE_ERROR_MESSAGE_PREFIX
from ....core.utils import to_global_id_or_none
from ....tests.utils import (
@@ -39,7 +36,7 @@ from ....tests.utils import (
get_graphql_content,
get_graphql_content_from_response,
)
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINES_ADD = """
mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {
@@ -93,8 +90,8 @@ mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
@@ -102,7 +99,7 @@ mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {
)
def test_checkout_lines_add(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
checkout_with_item,
stock,
@@ -141,7 +138,9 @@ def test_checkout_lines_add(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -155,8 +154,8 @@ def test_checkout_lines_add(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
@@ -164,7 +163,7 @@ def test_checkout_lines_add(
)
def test_checkout_lines_add_when_checkout_has_line_without_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -210,15 +209,17 @@ def test_checkout_lines_add_when_checkout_has_line_without_listing(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
@@ -226,7 +227,7 @@ def test_checkout_lines_add_when_checkout_has_line_without_listing(
)
def test_add_to_existing_line_with_sale_when_checkout_has_voucher(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
checkout_with_item,
stock,
@@ -329,6 +330,10 @@ def test_add_to_existing_line_with_sale_when_checkout_has_voucher(
== expected_discount_per_single_item * line.quantity
)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
+
def test_add_to_existing_line_catalogue_and_order_discount_applies(
user_api_client,
@@ -909,11 +914,14 @@ def test_checkout_lines_add_with_empty_metadata_and_old_exist(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_add_only_stock_in_cc_warehouse(
- mocked_update_shipping_method, user_api_client, checkout_with_item, warehouse_for_cc
+ mocked_mark_shipping_methods_as_stale,
+ user_api_client,
+ checkout_with_item,
+ warehouse_for_cc,
):
"""Test that click-and-collect quantities are available if no shipping method is set."""
# given
@@ -956,12 +964,14 @@ def test_checkout_lines_add_only_stock_in_cc_warehouse(
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
def test_checkout_lines_add_only_stock_in_cc_warehouse_delivery_method_set(
- user_api_client, checkout_with_item, warehouse_for_cc, shipping_method
+ user_api_client, checkout_with_item, warehouse_for_cc, checkout_delivery
):
"""Test that click-and-collect quantities are unavailable if a non-C&C shipping method is set."""
@@ -977,8 +987,8 @@ def test_checkout_lines_add_only_stock_in_cc_warehouse_delivery_method_set(
warehouse=warehouse_for_cc, product_variant=variant, quantity=10
)
- checkout.shipping_method = shipping_method
- checkout.save(update_fields=["shipping_method"])
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save(update_fields=["assigned_delivery"])
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
@@ -1353,64 +1363,22 @@ def test_checkout_lines_add_custom_price_and_catalogue_promotion(
assert line_discount.value_type == promotion_rule.reward_value_type
+@freeze_time("2024-05-31 12:00:01")
@mock.patch("saleor.plugins.manager.PluginsManager.list_shipping_methods_for_checkout")
-def test_checkout_lines_add_deletes_external_shipping_method_if_invalid(
- mocked_webhook, app_api_client, checkout_with_item, permission_handle_checkouts
-):
- # given
- mocked_webhook.return_value = []
- checkout = checkout_with_item
- line = checkout.lines.first()
- metadata = checkout.metadata_storage
- metadata.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: "QXBwOjEzMzc="}
- metadata.save(update_fields=["private_metadata"])
-
- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)
- price = Decimal("13.11")
-
- variables = {
- "id": to_global_id_or_none(checkout),
- "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],
- "channelSlug": checkout.channel.slug,
- }
-
- # when
- response = app_api_client.post_graphql(
- MUTATION_CHECKOUT_LINES_ADD,
- variables,
- permissions=[permission_handle_checkouts],
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["checkoutLinesAdd"]
- assert not data["errors"]
- metadata.refresh_from_db()
- assert metadata.private_metadata == {}
-
-
[email protected]("saleor.plugins.manager.PluginsManager.list_shipping_methods_for_checkout")
-def test_checkout_lines_add_doesnt_delete_external_shipping_method_if_valid(
+def test_checkout_lines_marks_shipping_methods_as_stale(
mocked_webhook,
app_api_client,
checkout_with_item,
permission_handle_checkouts,
- address,
+ checkout_delivery,
):
# given
- external_method_data = ShippingMethodData(
- id=graphene.Node.to_global_id("App", app_api_client.app.id),
- price=Money(Decimal(10), checkout_with_item.currency),
- active=True,
- )
- mocked_webhook.return_value = [external_method_data]
+ mocked_webhook.return_value = []
checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save(update_fields=["assigned_delivery"])
+
line = checkout.lines.first()
- metadata = checkout.metadata_storage
- metadata.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: external_method_data.id}
- metadata.save(update_fields=["private_metadata"])
variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)
price = Decimal("13.11")
@@ -1429,12 +1397,12 @@ def test_checkout_lines_add_doesnt_delete_external_shipping_method_if_valid(
)
# then
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery
+ assert checkout.delivery_methods_stale_at == timezone.now()
content = get_graphql_content(response)
data = content["data"]["checkoutLinesAdd"]
assert not data["errors"]
- assert metadata.private_metadata == {
- PRIVATE_META_APP_SHIPPING_ID: external_method_data.id
- }
def test_checkout_lines_add_custom_price_and_order_fixed_discount(
@@ -2080,6 +2048,23 @@ def test_with_active_problems_flow(
assert not content["data"]["checkoutLinesAdd"]["errors"]
+MUTATION_CHECKOUT_LINES_ADD_WITH_ONLY_ID = """
+mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {
+ checkoutLinesAdd(id: $id, lines: $lines) {
+ checkout {
+ id
+ }
+ errors {
+ field
+ code
+ message
+ variants
+ }
+ }
+}
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -2090,11 +2075,11 @@ def test_with_active_problems_flow(
wraps=send_webhook_request_async.apply_async,
)
@patch(
- "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_lines_add_triggers_webhooks(
- mocked_send_webhook_using_scheme_method,
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -2106,7 +2091,6 @@ def test_checkout_lines_add_triggers_webhooks(
address,
):
# given
- mocked_send_webhook_using_scheme_method.return_value = WebhookResponse(content="")
mocked_send_webhook_request_sync.return_value = []
(
tax_webhook,
@@ -2141,40 +2125,38 @@ def test_checkout_lines_add_triggers_webhooks(
}
# when
- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_ADD_WITH_ONLY_ID, variables
+ )
# then
content = get_graphql_content(response)
assert not content["data"]["checkoutLinesAdd"]["errors"]
- assert wrapped_call_checkout_info_event.called
- assert mocked_send_webhook_request_async.call_count == 1
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
+ # confirm that event delivery was generated for each async webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
- ).exists()
-
- sync_deliveries = {
- call.args[0].event_type: call.args[0]
- for call in mocked_send_webhook_request_sync.mock_calls
- }
-
- assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
- shipping_methods_delivery = sync_deliveries[
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
+ )
- assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
- filter_shipping_delivery = sync_deliveries[
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- ]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
+ mocked_generate_deferred_payloads.assert_called_once_with(
+ kwargs={
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ "telemetry_context": ANY,
+ },
+ bind=True,
+ )
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
def test_checkout_lines_add_when_line_deleted(user_api_client, checkout_with_item):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
index 8db9ae5ffd..5201a08250 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
@@ -13,10 +13,10 @@ from .....checkout.utils import invalidate_checkout
from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINES_DELETE = """
mutation checkoutLinesDelete($id: ID, $linesIds: [ID!]!) {
@@ -44,8 +44,8 @@ MUTATION_CHECKOUT_LINES_DELETE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout",
@@ -53,7 +53,7 @@ MUTATION_CHECKOUT_LINES_DELETE = """
)
def test_checkout_lines_delete(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
checkout_with_items,
):
@@ -81,7 +81,9 @@ def test_checkout_lines_delete(
assert lines_list not in lines_ids
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -95,8 +97,8 @@ def test_checkout_lines_delete(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout",
@@ -104,7 +106,7 @@ def test_checkout_lines_delete(
)
def test_checkout_lines_delete_when_line_without_channel_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -144,7 +146,9 @@ def test_checkout_lines_delete_when_line_without_channel_listing(
assert lines_list not in lines_ids
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -158,8 +162,8 @@ def test_checkout_lines_delete_when_line_without_channel_listing(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_delete."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout",
@@ -167,7 +171,7 @@ def test_checkout_lines_delete_when_line_without_channel_listing(
)
def test_checkout_lines_delete_when_checkout_has_variant_without_channel_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -209,7 +213,9 @@ def test_checkout_lines_delete_when_checkout_has_variant_without_channel_listing
assert lines_list not in lines_ids
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -343,8 +349,12 @@ def test_checkout_lines_delete_not_associated_with_checkout(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_lines_delete_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -393,39 +403,22 @@ def test_checkout_lines_delete_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_items.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
- )
-
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ bind=True,
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 4826c12b15..58eae473ea 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -1,12 +1,13 @@
import datetime
from decimal import Decimal
from unittest import mock
-from unittest.mock import patch
+from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
from django.utils import timezone
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_info_event
from .....checkout.calculations import (
@@ -28,13 +29,12 @@ from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
from .....tests import race_condition
from .....warehouse.models import Reservation, Stock
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.transport.asynchronous.transport import send_webhook_request_async
-from .....webhook.transport.utils import WebhookResponse
from ....core.mutations import MISSING_NODE_ERROR_MESSAGE_PREFIX
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
MUTATION_CHECKOUT_LINES_UPDATE = """
mutation checkoutLinesUpdate(
@@ -84,8 +84,8 @@ MUTATION_CHECKOUT_LINES_UPDATE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
@@ -93,7 +93,7 @@ MUTATION_CHECKOUT_LINES_UPDATE = """
)
def test_checkout_lines_update(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
checkout_with_item,
):
@@ -128,7 +128,9 @@ def test_checkout_lines_update(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@@ -142,8 +144,8 @@ def test_checkout_lines_update(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
@@ -151,7 +153,7 @@ def test_checkout_lines_update(
)
def test_checkout_lines_update_when_checkout_has_line_without_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -202,18 +204,20 @@ def test_checkout_lines_update_when_checkout_has_line_without_listing(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_update_using_line_id(
- mocked_update_shipping_method, user_api_client, checkout_with_item
+ mocked_mark_shipping_methods_as_stale, user_api_client, checkout_with_item
):
checkout = checkout_with_item
lines, _ = fetch_checkout_lines(checkout)
@@ -246,17 +250,19 @@ def test_checkout_lines_update_using_line_id(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_update_using_line_id_and_variant_id(
- mocked_update_shipping_method, user_api_client, checkout_with_item
+ mocked_mark_shipping_methods_as_stale, user_api_client, checkout_with_item
):
checkout = checkout_with_item
lines, _ = fetch_checkout_lines(checkout)
@@ -293,7 +299,9 @@ def test_checkout_lines_update_using_line_id_and_variant_id(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
@@ -358,11 +366,14 @@ def test_checkout_lines_update_block_when_variant_id_and_line_id_provided(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_lines_update_only_stock_in_cc_warehouse(
- mocked_update_shipping_method, user_api_client, checkout_with_item, warehouse_for_cc
+ mocked_mark_shipping_methods_as_stale,
+ user_api_client,
+ checkout_with_item,
+ warehouse_for_cc,
):
"""Test that click-and-collect quantities are available if no shipping method is set."""
# given
@@ -407,12 +418,14 @@ def test_checkout_lines_update_only_stock_in_cc_warehouse(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
def test_checkout_lines_update_only_stock_in_cc_warehouse_delivery_method_set(
- user_api_client, checkout_with_item, warehouse_for_cc, shipping_method
+ user_api_client, checkout_with_item, warehouse_for_cc, checkout_delivery
): # given
"""Test that click-and-collect quantities are unavailable if a non-C&C shipping method is set."""
checkout = checkout_with_item
@@ -426,8 +439,8 @@ def test_checkout_lines_update_only_stock_in_cc_warehouse_delivery_method_set(
warehouse=warehouse_for_cc, product_variant=variant, quantity=10
)
- checkout.shipping_method = shipping_method
- checkout.save(update_fields=["shipping_method"])
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save(update_fields=["assigned_delivery"])
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
@@ -1228,11 +1241,11 @@ def test_checkout_lines_delete_with_by_zero_quantity_when_variant_out_of_stock(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_line_delete_by_zero_quantity(
- mocked_update_shipping_method, user_api_client, checkout_with_item
+ mocked_mark_shipping_methods_as_stale, user_api_client, checkout_with_item
):
checkout = checkout_with_item
assert checkout.lines.count() == 1
@@ -1257,17 +1270,19 @@ def test_checkout_line_delete_by_zero_quantity(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_line_delete_by_zero_quantity_when_variant_unavailable_for_purchase(
- mocked_update_shipping_method, user_api_client, checkout_with_item
+ mocked_mark_shipping_methods_as_stale, user_api_client, checkout_with_item
):
checkout = checkout_with_item
assert checkout.lines.count() == 1
@@ -1293,16 +1308,18 @@ def test_checkout_line_delete_by_zero_quantity_when_variant_unavailable_for_purc
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
def test_checkout_line_update_by_zero_quantity_dont_create_new_lines(
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
checkout_with_item,
):
@@ -1329,7 +1346,9 @@ def test_checkout_line_update_by_zero_quantity_dont_create_new_lines(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
@@ -1388,11 +1407,13 @@ def test_checkout_lines_update_check_lines_quantity(
assert data["errors"][0]["field"] == "quantity"
-def test_checkout_lines_update_with_chosen_shipping(
- user_api_client, checkout, stock, address, shipping_method
+@freeze_time("2022-04-12 12:00:00")
+def test_checkout_lines_update_marks_shipping_as_stale(
+ user_api_client, checkout, stock, address, checkout_delivery
):
+ # given
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
variant = stock.product_variant
@@ -1401,7 +1422,10 @@ def test_checkout_lines_update_with_chosen_shipping(
"id": to_global_id_or_none(checkout),
"lines": [{"variantId": variant_id, "quantity": 1}],
}
+ # when
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["checkoutLinesUpdate"]
@@ -1409,16 +1433,25 @@ def test_checkout_lines_update_with_chosen_shipping(
checkout.refresh_from_db()
lines, _ = fetch_checkout_lines(checkout)
assert calculate_checkout_quantity(lines) == 1
+ assert checkout.assigned_delivery
+ assert checkout.delivery_methods_stale_at == timezone.now()
-def test_checkout_lines_update_remove_shipping_if_removed_product_with_shipping(
- user_api_client, checkout_with_item, digital_content, address, shipping_method
+@freeze_time("2022-04-12 12:00:00")
+def test_checkout_lines_update_do_not_remove_shipping_if_removed_product_with_shipping(
+ user_api_client,
+ checkout_with_item,
+ digital_content,
+ address,
+ checkout_delivery,
):
+ # given
checkout = checkout_with_item
digital_variant = digital_content.product_variant
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
+
checkout_info = fetch_checkout_info(
checkout, [], get_plugins_manager(allow_replica=False)
)
@@ -1432,14 +1465,19 @@ def test_checkout_lines_update_remove_shipping_if_removed_product_with_shipping(
"id": to_global_id_or_none(checkout),
"lines": [{"variantId": variant_id, "quantity": 0}],
}
+
+ # when
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["checkoutLinesUpdate"]
assert not data["errors"]
checkout.refresh_from_db()
assert checkout.lines.count() == 1
- assert not checkout.shipping_method
+ assert checkout.assigned_delivery
+ assert checkout.delivery_methods_stale_at == timezone.now()
def test_with_active_problems_flow(
@@ -1499,6 +1537,25 @@ def test_checkout_lines_update_quantity_gift(user_api_client, checkout_with_item
assert errors[0]["lines"] == [line_id]
+MUTATION_CHECKOUT_LINES_UPDATE_WITH_ONLY_ID = """
+ mutation checkoutLinesUpdate(
+ $id: ID, $lines: [CheckoutLineUpdateInput!]!) {
+ checkoutLinesUpdate(id: $id, lines: $lines) {
+ checkout {
+ id
+ }
+ errors {
+ field
+ code
+ message
+ variants
+ lines
+ }
+ }
+ }
+ """
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_lines_add.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -1509,11 +1566,11 @@ def test_checkout_lines_update_quantity_gift(user_api_client, checkout_with_item
wraps=send_webhook_request_async.apply_async,
)
@patch(
- "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_lines_update_triggers_webhooks(
- mocked_send_webhook_using_scheme_method,
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1525,8 +1582,6 @@ def test_checkout_lines_update_triggers_webhooks(
address,
):
# given
- mocked_send_webhook_using_scheme_method.return_value = WebhookResponse(content="")
- mocked_send_webhook_request_sync.return_value = []
(
tax_webhook,
shipping_webhook,
@@ -1554,42 +1609,38 @@ def test_checkout_lines_update_triggers_webhooks(
# when
response = api_client.post_graphql(
- MUTATION_CHECKOUT_LINES_UPDATE,
+ MUTATION_CHECKOUT_LINES_UPDATE_WITH_ONLY_ID,
variables,
)
# then
content = get_graphql_content(response)
assert not content["data"]["checkoutLinesUpdate"]["errors"]
- assert wrapped_call_checkout_info_event.called
- assert mocked_send_webhook_request_async.call_count == 1
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
+ # confirm that event delivery was generated for each async webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
- ).exists()
+ )
- sync_deliveries = {
- call.args[0].event_type: call.args[0]
- for call in mocked_send_webhook_request_sync.mock_calls
- }
+ mocked_generate_deferred_payloads.assert_called_once_with(
+ kwargs={
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_items.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ "telemetry_context": ANY,
+ },
+ bind=True,
+ )
- assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
- shipping_methods_delivery = sync_deliveries[
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
- filter_shipping_delivery = sync_deliveries[
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- ]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
def test_checkout_lines_update_when_line_deleted(user_api_client, checkout_with_item):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index 9cd52bfeb3..d68a6ec211 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -1,11 +1,12 @@
import datetime
from decimal import Decimal
-from unittest.mock import patch
+from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
from django.utils import timezone
+from freezegun import freeze_time
from prices import Money
from .....checkout import base_calculations
@@ -17,9 +18,8 @@ from .....discount import RewardValueType
from .....discount.models import Voucher, VoucherChannelListing, VoucherCode
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.transport.asynchronous.transport import send_webhook_request_async
-from .....webhook.transport.utils import WebhookResponse
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -781,6 +781,23 @@ def test_with_active_problems_flow(
)
+MUTATION_CHECKOUT_REMOVE_PROMO_CODE_WITH_ONLY_ID = """
+ mutation($id: ID, $promoCode: String, $promoCodeId: ID) {
+ checkoutRemovePromoCode(
+ id: $id, promoCode: $promoCode, promoCodeId: $promoCodeId) {
+ errors {
+ field
+ code
+ message
+ }
+ checkout {
+ id
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_remove_promo_code.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -791,11 +808,11 @@ def test_with_active_problems_flow(
wraps=send_webhook_request_async.apply_async,
)
@patch(
- "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_remove_triggers_webhooks(
- mocked_send_webhook_using_scheme_method,
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -806,7 +823,6 @@ def test_checkout_remove_triggers_webhooks(
address,
):
# given
- mocked_send_webhook_using_scheme_method.return_value = WebhookResponse(content="")
mocked_send_webhook_request_sync.return_value = []
(
tax_webhook,
@@ -827,39 +843,41 @@ def test_checkout_remove_triggers_webhooks(
}
# when
- content = _mutate_checkout_remove_promo_code(api_client, variables)
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_REMOVE_PROMO_CODE_WITH_ONLY_ID, variables
+ )
# then
+ content = get_graphql_content(response)
+ content = content["data"]["checkoutRemovePromoCode"]
+
assert not content["errors"]
assert wrapped_call_checkout_info_event.called
- assert mocked_send_webhook_request_async.call_count == 1
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
+ # confirm that event delivery was generated for each async webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
- ).exists()
-
- sync_deliveries = {
- call.args[0].event_type: call.args[0]
- for call in mocked_send_webhook_request_sync.mock_calls
- }
-
- assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
- shipping_methods_delivery = sync_deliveries[
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
+ )
- assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
- filter_shipping_delivery = sync_deliveries[
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- ]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
+ mocked_generate_deferred_payloads.assert_called_once_with(
+ kwargs={
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_voucher.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ "telemetry_context": ANY,
+ },
+ bind=True,
+ )
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
@patch("saleor.plugins.manager.PluginsManager.checkout_updated")
@@ -923,3 +941,44 @@ def test_checkout_remove_voucher_code_voucher_code_deleted(
checkout_updated_webhook_mock.assert_called_once_with(
checkout_with_voucher, webhooks=set()
)
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_remove_voucher_code_marks_shipping_as_stale(
+ api_client,
+ checkout_with_voucher,
+ checkout_delivery,
+ address,
+):
+ # given
+ previous_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+
+ checkout = checkout_with_voucher
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = previous_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
+ )
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_voucher),
+ "promoCode": checkout_with_voucher.voucher_code,
+ }
+
+ # when
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=1)
+ with freeze_time(expected_stale_time):
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert not data["errors"]
+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)
+ assert data["checkout"]["voucherCode"] is None
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == expected_stale_time
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
index 386eb8b3bf..92e197cd02 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
from django.utils import timezone
+from freezegun import freeze_time
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
@@ -16,14 +17,13 @@ from .....checkout.utils import (
invalidate_checkout,
)
from .....core.models import EventDelivery
-from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
from .....warehouse.models import Reservation, Stock
-from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...mutations.utils import update_checkout_shipping_method_if_invalid
+from ...mutations.utils import mark_checkout_deliveries_as_stale_if_needed
from ..utils import assert_address_data
MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """
@@ -97,8 +97,8 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_WITH_METADATA_UPDATE = """
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
@@ -107,7 +107,7 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_WITH_METADATA_UPDATE = """
)
def test_checkout_shipping_address_with_metadata_update(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
checkout_with_item,
graphql_address_data,
@@ -133,7 +133,9 @@ def test_checkout_shipping_address_with_metadata_update(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
assert checkout.save_shipping_address is True
@@ -148,8 +150,8 @@ def test_checkout_shipping_address_with_metadata_update(
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
@@ -158,7 +160,7 @@ def test_checkout_shipping_address_with_metadata_update(
)
def test_checkout_shipping_address_when_variant_without_listing(
mocked_invalidate_checkout,
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_listing_model,
listing_filter_field,
user_api_client,
@@ -196,7 +198,9 @@ def test_checkout_shipping_address_when_variant_without_listing(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.last_change != previous_last_change
assert mocked_invalidate_checkout.call_count == 1
assert checkout.save_shipping_address is True
@@ -204,12 +208,12 @@ def test_checkout_shipping_address_when_variant_without_listing(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@override_settings(DEFAULT_COUNTRY="DE")
def test_checkout_shipping_address_update_changes_checkout_country(
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
user_api_client,
channel_USD,
variant_with_many_stocks_different_shipping_zones,
@@ -245,7 +249,9 @@ def test_checkout_shipping_address_update_changes_checkout_country(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ mocked_mark_shipping_methods_as_stale.assert_called_once_with(
+ checkout_info.checkout, lines
+ )
assert checkout.country == shipping_address["country"]
assert checkout.last_change != previous_last_change
assert checkout.save_shipping_address is True
@@ -253,12 +259,12 @@ def test_checkout_shipping_address_update_changes_checkout_country(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@override_settings(DEFAULT_COUNTRY="DE")
def test_checkout_shipping_address_update_insufficient_stocks(
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_USD,
user_api_client,
variant_with_many_stocks_different_shipping_zones,
@@ -300,12 +306,12 @@ def test_checkout_shipping_address_update_insufficient_stocks(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@override_settings(DEFAULT_COUNTRY="DE")
def test_checkout_shipping_address_update_doesnt_raise_error(
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
channel_USD,
user_api_client,
product_list,
@@ -343,12 +349,12 @@ def test_checkout_shipping_address_update_doesnt_raise_error(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@override_settings(DEFAULT_COUNTRY="DE")
def test_checkout_shipping_address_update_with_reserved_stocks(
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
site_settings_with_reservations,
channel_USD,
user_api_client,
@@ -399,12 +405,12 @@ def test_checkout_shipping_address_update_with_reserved_stocks(
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
- "update_checkout_shipping_method_if_invalid",
- wraps=update_checkout_shipping_method_if_invalid,
+ "mark_checkout_deliveries_as_stale_if_needed",
+ wraps=mark_checkout_deliveries_as_stale_if_needed,
)
@override_settings(DEFAULT_COUNTRY="DE")
def test_checkout_shipping_address_update_against_reserved_stocks(
- mocked_update_shipping_method,
+ mocked_mark_shipping_methods_as_stale,
site_settings_with_reservations,
channel_USD,
user_api_client,
@@ -560,35 +566,6 @@ def test_checkout_shipping_address_update_without_phone_country_prefix(
assert not data["errors"]
- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
-)
-def test_checkout_shipping_address_update_exclude_shipping_method(
- mocked_webhook,
- user_api_client,
- checkout_with_items_and_shipping,
- graphql_address_data,
- settings,
-):
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- checkout = checkout_with_items_and_shipping
- shipping_method = checkout.shipping_method
- assert shipping_method is not None
- webhook_reason = "hello-there"
- mocked_webhook.return_value = [
- ExcludedShippingMethod(shipping_method.id, webhook_reason)
- ]
- shipping_address = graphql_address_data
- variables = {
- "id": to_global_id_or_none(checkout),
- "shippingAddress": shipping_address,
- }
-
- user_api_client.post_graphql(MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables)
- checkout.refresh_from_db()
- assert checkout.shipping_method is None
-
-
@pytest.mark.parametrize(
"address_data",
[
@@ -980,13 +957,13 @@ def test_checkout_shipping_address_update_with_not_applicable_voucher(
voucher_shipping_type,
graphql_address_data,
address_other_country,
- shipping_method,
+ checkout_delivery,
):
assert checkout_with_item.shipping_address is None
assert checkout_with_item.voucher_code is None
checkout_with_item.shipping_address = address_other_country
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
assert checkout_with_item.shipping_address.country == address_other_country.country
@@ -1127,6 +1104,32 @@ def test_checkout_shipping_address_skip_validation_by_app(
assert checkout.shipping_address.validation_skipped is True
+MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE_WITH_ONLY_ID = """
+ mutation checkoutShippingAddressUpdate(
+ $id: ID,
+ $shippingAddress: AddressInput!,
+ $validationRules: CheckoutAddressValidationRules
+ $saveAddress: Boolean
+ ) {
+ checkoutShippingAddressUpdate(
+ id: $id,
+ shippingAddress: $shippingAddress,
+ validationRules: $validationRules
+ saveAddress: $saveAddress
+ ) {
+ checkout {
+ id
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -1135,8 +1138,12 @@ def test_checkout_shipping_address_skip_validation_by_app(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_shipping_address_update_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1165,7 +1172,7 @@ def test_checkout_shipping_address_update_triggers_webhooks(
# when
response = user_api_client.post_graphql(
- MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE_WITH_ONLY_ID, variables
)
# then
@@ -1178,42 +1185,26 @@ def test_checkout_shipping_address_update_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_item.pk,
+ "requestor_model_name": "account.user",
+ "requestor_object_id": user_api_client.user.pk,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
- )
-
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
+ bind=True,
)
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
def test_checkout_shipping_address_update_reset_the_save_address_flag_to_default_value(
@@ -1364,3 +1355,49 @@ def test_checkout_shipping_address_update_when_switching_from_cc(
assert not data["errors"]
checkout.refresh_from_db()
assert checkout.shipping_address
+
+
+@freeze_time("2024-05-31 12:00:01")
+def test_checkout_shipping_address_marks_shipping_as_stale(
+ user_api_client,
+ checkout_with_item,
+ graphql_address_data,
+ checkout_delivery,
+ address,
+):
+ # given
+ checkout = checkout_with_item
+ assert checkout.shipping_address is None
+
+ expected_stale_time = timezone.now() + timezone.timedelta(minutes=10)
+ checkout = checkout_with_item
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_address = address
+ checkout.delivery_methods_stale_at = expected_stale_time
+ checkout.save(
+ update_fields=[
+ "assigned_delivery",
+ "shipping_address",
+ "delivery_methods_stale_at",
+ ]
+ )
+
+ query = MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE_WITH_ONLY_ID
+ shipping_address = graphql_address_data
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "shippingAddress": shipping_address,
+ }
+
+ # when
+ new_now = timezone.now()
+ with freeze_time(new_now):
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.delivery_methods_stale_at == new_now
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 d5fdcaa806..526e68d057 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
@@ -1,25 +1,29 @@
+from datetime import timedelta
from decimal import Decimal
from unittest import mock
from unittest.mock import ANY, patch
import graphene
-import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....account.models import Address
from .....checkout.actions import call_checkout_info_event
from .....checkout.calculations import fetch_checkout_data
from .....checkout.error_codes import CheckoutErrorCode
-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+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 .....core.models import EventDelivery
from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....shipping import models as shipping_models
-from .....shipping.utils import convert_to_shipping_method_data
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
-from .....webhook.transport.asynchronous.transport import send_webhook_request_async
-from .....webhook.transport.utils import WebhookResponse
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -53,11 +57,10 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
"""
-# TODO: Deprecated
[email protected]("is_valid_shipping_method", [True, False])
@patch(
"saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
)
@patch(
"saleor.graphql.checkout.mutations.utils.invalidate_checkout",
@@ -65,50 +68,92 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
)
def test_checkout_shipping_method_update(
mocked_invalidate_checkout,
- mock_clean_shipping,
+ mock_get_or_fetch_checkout_deliveries,
staff_api_client,
shipping_method,
checkout_with_item_and_shipping_method,
- is_valid_shipping_method,
):
+ # given
checkout = checkout_with_item_and_shipping_method
- old_shipping_method = checkout.shipping_method
query = MUTATION_UPDATE_SHIPPING_METHOD
- mock_clean_shipping.return_value = is_valid_shipping_method
previous_last_change = checkout.last_change
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ # when
response = staff_api_client.post_graphql(
query, {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
checkout.refresh_from_db()
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- mock_clean_shipping.assert_called_once_with(
- checkout_info=checkout_info,
- method=convert_to_shipping_method_data(
- shipping_method, shipping_method.channel_listings.first()
- ),
+ mock_get_or_fetch_checkout_deliveries.assert_called_once_with(
+ checkout_info,
)
errors = data["errors"]
- if is_valid_shipping_method:
- assert not errors
- assert data["checkout"]["token"] == str(checkout.token)
- assert checkout.shipping_method == shipping_method
- assert checkout.last_change != previous_last_change
- assert mocked_invalidate_checkout.call_count == 1
- else:
- assert len(errors) == 1
- assert errors[0]["field"] == "shippingMethod"
- assert (
- errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
- )
- assert checkout.shipping_method == old_shipping_method
- assert checkout.last_change == previous_last_change
+ assert not errors
+ assert data["checkout"]["token"] == str(checkout.token)
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
+@freeze_time("2023-01-01 12:00:00")
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+@patch(
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_not_valid_shipping_method(
+ mocked_invalidate_checkout,
+ mock_get_or_fetch_checkout_deliveries,
+ staff_api_client,
+ other_shipping_method,
+ checkout_with_item_and_shipping_method,
+):
+ # given
+ checkout = checkout_with_item_and_shipping_method
+ checkout.delivery_methods_stale_at = timezone.now() + timedelta(minutes=10)
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+
+ old_shipping_method = checkout.assigned_delivery
+ previous_last_change = checkout.last_change
+
+ query = MUTATION_UPDATE_SHIPPING_METHOD
+
+ # other_shipping_method is not present in denormalized checkout shipping methods
+ method_id = graphene.Node.to_global_id("ShippingMethod", other_shipping_method.id)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ checkout.refresh_from_db()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mock_get_or_fetch_checkout_deliveries.assert_called_once_with(
+ checkout_info,
+ )
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "shippingMethod"
+ assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
+ assert checkout.assigned_delivery == old_shipping_method
+ assert checkout.last_change == previous_last_change
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -163,7 +208,7 @@ def test_checkout_shipping_method_update_external_shipping_method(
assert not errors
assert data["checkout"]["token"] == str(checkout_with_item.token)
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == method_id
assert checkout.undiscounted_base_shipping_price_amount == method_price
assert checkout.shipping_method_name == method_name
assert (
@@ -171,50 +216,6 @@ def test_checkout_shipping_method_update_external_shipping_method(
)
-def test_checkout_shipping_method_update_overwrites_external_shipping(
- staff_api_client, shipping_method, checkout_with_item_and_shipping_method, address
-):
- # given
- checkout = checkout_with_item_and_shipping_method
- checkout.external_shipping_method_id = "ext-ship"
- checkout.undiscounted_base_shipping_price_amount = Decimal(110)
- checkout.shipping_method_name = "Ext shipping"
- checkout.shipping_address = address
- checkout.save()
-
- query = MUTATION_UPDATE_SHIPPING_METHOD
- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
-
- # when
- response = staff_api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}
- )
-
- # then
- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
- checkout.refresh_from_db()
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
-
- errors = data["errors"]
- assert not errors
- assert checkout.shipping_method == shipping_method
- assert checkout.external_shipping_method_id is None
- assert (
- checkout.undiscounted_base_shipping_price_amount
- == shipping_method.channel_listings.get().price_amount
- )
- assert checkout.shipping_method_name == shipping_method.name
-
-
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_shipping_method_update_deletes_external_shipping_when_not_valid(
mock_send_request,
@@ -271,59 +272,6 @@ def test_checkout_shipping_method_update_deletes_external_shipping_when_not_vali
)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_checkout_shipping_method_update_external_shipping_method_with_tax_plugin(
- mock_send_request,
- staff_api_client,
- address,
- checkout_with_item,
- shipping_app,
- channel_USD,
- settings,
-):
- settings.PLUGINS = [
- "saleor.plugins.tests.sample_plugins.PluginSample",
- "saleor.plugins.webhook.plugin.WebhookPlugin",
- ]
- response_method_id = "abcd"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- mock_send_request.return_value = mock_json_response
-
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save()
-
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
- )
-
- # Set external shipping method for first time
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_SHIPPING_METHOD,
- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
- )
- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
- assert not data["errors"]
-
- # Set external shipping for second time
- # Without a fix this request results in infinite recursion
- # between Avalara and Webhooks plugins
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_SHIPPING_METHOD,
- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
- )
- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
- assert not data["errors"]
-
-
@mock.patch(
"saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
)
@@ -335,7 +283,7 @@ def test_checkout_shipping_method_update_excluded_webhook(
address,
):
# given
- webhook_reason = "spanish-inquisition"
+ webhook_reason = "disabled by webhook"
checkout = checkout_with_item
checkout.shipping_address = address
checkout.save(update_fields=["shipping_address"])
@@ -359,8 +307,7 @@ def test_checkout_shipping_method_update_excluded_webhook(
assert len(errors) == 1
assert errors[0]["field"] == "shippingMethod"
assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
assert checkout.shipping_method_name is None
@@ -394,8 +341,7 @@ def test_checkout_shipping_method_update_excluded_postal_code(
assert len(errors) == 1
assert errors[0]["field"] == "shippingMethod"
assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
assert checkout.shipping_method_name is None
assert (
@@ -439,8 +385,7 @@ def test_checkout_shipping_method_update_with_not_all_required_shipping_address_
)
assert not data["errors"]
- assert checkout.shipping_method == shipping_method
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
assert (
checkout.undiscounted_base_shipping_price_amount
== shipping_method.channel_listings.get().price_amount
@@ -489,8 +434,7 @@ def test_checkout_shipping_method_update_with_not_valid_shipping_address_data(
)
assert not data["errors"]
- assert checkout.shipping_method == shipping_method
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
assert (
checkout.undiscounted_base_shipping_price_amount
== shipping_method.channel_listings.get().price_amount
@@ -564,56 +508,11 @@ def test_checkout_shipping_method_update_shipping_zone_without_channel(
assert len(errors) == 1
assert errors[0]["field"] == "shippingMethod"
assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
- assert checkout.shipping_method is None
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
assert checkout.shipping_method_name is None
-# Deprecated
-def test_checkout_shipping_method_update_shipping_zone_with_channel(
- staff_api_client,
- shipping_method,
- checkout_with_item,
- address,
-):
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
- query = MUTATION_UPDATE_SHIPPING_METHOD
-
- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
-
- response = staff_api_client.post_graphql(
- query,
- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
- )
- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
-
- checkout.refresh_from_db()
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
-
- errors = data["errors"]
- assert not errors
- assert data["checkout"]["token"] == str(checkout_with_item.token)
-
- assert checkout.shipping_method == shipping_method
- assert checkout.external_shipping_method_id is None
- assert (
- checkout.undiscounted_base_shipping_price_amount
- == shipping_method.channel_listings.get().price_amount
- )
- assert checkout.shipping_method_name == shipping_method.name
-
-
def test_checkout_update_shipping_method_with_digital(
api_client, checkout_with_digital_item, address, shipping_method
):
@@ -640,9 +539,8 @@ def test_checkout_update_shipping_method_with_digital(
]
# Ensure the shipping method was unchanged
- checkout.refresh_from_db(fields=["shipping_method"])
- assert checkout.shipping_method is None
- assert checkout.external_shipping_method_id is None
+ checkout.refresh_from_db()
+ assert checkout.assigned_delivery is None
assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
assert checkout.shipping_method_name is None
@@ -673,6 +571,22 @@ def test_with_active_problems_flow(
assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
+MUTATION_UPDATE_SHIPPING_METHOD_WITH_ONLY_ID = """
+ mutation checkoutShippingMethodUpdate($id: ID, $shippingMethodId: ID) {
+ checkoutShippingMethodUpdate(id: $id, shippingMethodId: $shippingMethodId) {
+ errors {
+ field
+ message
+ code
+ }
+ checkout {
+ id
+ }
+ }
+ }
+"""
+
+
@patch(
"saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
@@ -681,8 +595,12 @@ def test_with_active_problems_flow(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_shipping_method_update_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -708,7 +626,7 @@ def test_checkout_shipping_method_update_triggers_webhooks(
# when
response = api_client.post_graphql(
- MUTATION_UPDATE_SHIPPING_METHOD,
+ MUTATION_UPDATE_SHIPPING_METHOD_WITH_ONLY_ID,
{
"id": to_global_id_or_none(checkout_with_items),
"shippingMethodId": method_id,
@@ -720,111 +638,30 @@ def test_checkout_shipping_method_update_triggers_webhooks(
assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
assert wrapped_call_checkout_info_event.called
- assert mocked_send_webhook_request_async.call_count == 1
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 4
- assert not EventDelivery.objects.exclude(
+ # confirm that event delivery was generated for each async webhook.
+ checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
- ).exists()
-
- sync_deliveries = {
- call.args[0].event_type: call.args[0]
- for call in mocked_send_webhook_request_sync.mock_calls
- }
-
- assert WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT in sync_deliveries
- shipping_methods_delivery = sync_deliveries[
- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- ]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS in sync_deliveries
- filter_shipping_delivery = sync_deliveries[
- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- ]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
-
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
-
-
-@patch(
- "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
- wraps=call_checkout_info_event,
-)
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-@patch(
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async",
- wraps=send_webhook_request_async.apply_async,
-)
-@patch(
- "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
-)
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
-def test_checkout_shipping_method_update_external_shipping_triggers_webhooks(
- mocked_send_webhook_using_scheme_method,
- mocked_send_webhook_request_async,
- mocked_send_webhook_request_sync,
- wrapped_call_checkout_info_event,
- setup_checkout_webhooks,
- settings,
- address,
- staff_api_client,
- checkout_with_item,
-):
- # given
- mocked_send_webhook_using_scheme_method.return_value = WebhookResponse(content="")
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_updated_webhook,
- ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
-
- response_method_id = "abcd"
- mock_json_response = [
- {
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
- ]
- mocked_send_webhook_request_sync.side_effect = [
- mock_json_response,
- [],
- [],
- ]
-
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.save(update_fields=["shipping_address"])
-
- method_id = graphene.Node.to_global_id(
- "app", f"{shipping_webhook.app.identifier}:{response_method_id}"
)
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_SHIPPING_METHOD,
- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
+ mocked_generate_deferred_payloads.assert_called_once_with(
+ kwargs={
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_items.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
+ "telemetry_context": ANY,
+ },
+ bind=True,
)
- # then
- content = get_graphql_content(response)
- assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]
-
- assert wrapped_call_checkout_info_event.called
- assert wrapped_call_checkout_info_event.called
- assert mocked_send_webhook_request_async.call_count == 1
-
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
+ # Deferred payload covers the async actions
+ assert not mocked_send_webhook_request_async.called
sync_deliveries = {
call.args[0].event_type: call.args[0]
@@ -843,9 +680,7 @@ def test_checkout_shipping_method_update_external_shipping_triggers_webhooks(
]
assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
- tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- assert tax_delivery.webhook_id == tax_webhook.id
+ assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES not in sync_deliveries
@patch(
@@ -856,8 +691,12 @@ def test_checkout_shipping_method_update_external_shipping_triggers_webhooks(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"
+)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_checkout_shipping_method_update_to_none_triggers_webhooks(
+ mocked_generate_deferred_payloads,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -866,7 +705,7 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
address,
api_client,
checkout_with_items,
- shipping_method,
+ checkout_delivery,
):
# given
mocked_send_webhook_request_sync.return_value = []
@@ -878,12 +717,12 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
checkout_with_items.shipping_address = address
- checkout_with_items.shipping_method = shipping_method
- checkout_with_items.save(update_fields=["shipping_address", "shipping_method"])
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
+ checkout_with_items.save(update_fields=["shipping_address", "assigned_delivery"])
# when
response = api_client.post_graphql(
- MUTATION_UPDATE_SHIPPING_METHOD,
+ MUTATION_UPDATE_SHIPPING_METHOD_WITH_ONLY_ID,
{
"id": to_global_id_or_none(checkout_with_items),
"shippingMethodId": None,
@@ -900,42 +739,26 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
checkout_update_delivery = EventDelivery.objects.get(
webhook_id=checkout_updated_webhook.id
)
- mocked_send_webhook_request_async.assert_called_once_with(
+
+ mocked_generate_deferred_payloads.assert_called_once_with(
kwargs={
- "event_delivery_id": checkout_update_delivery.id,
+ "event_delivery_ids": [checkout_update_delivery.id],
+ "deferred_payload_data": {
+ "model_name": "checkout.checkout",
+ "object_id": checkout_with_items.pk,
+ "requestor_model_name": None,
+ "requestor_object_id": None,
+ "request_time": None,
+ },
+ "send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
},
- queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
- MessageGroupId="example.com:saleorappadditional",
+ bind=True,
)
- # confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 3
- assert not EventDelivery.objects.exclude(
- webhook_id=checkout_updated_webhook.id
- ).exists()
-
- shipping_methods_call, filter_shipping_call, tax_delivery_call = (
- mocked_send_webhook_request_sync.mock_calls
- )
- shipping_methods_delivery = shipping_methods_call.args[0]
- assert shipping_methods_delivery.webhook_id == shipping_webhook.id
- assert (
- shipping_methods_delivery.event_type
- == WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
- )
- assert shipping_methods_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- filter_shipping_delivery = filter_shipping_call.args[0]
- assert filter_shipping_delivery.webhook_id == shipping_filter_webhook.id
- assert (
- filter_shipping_delivery.event_type
- == WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- )
- assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
-
- tax_delivery = tax_delivery_call.args[0]
- assert tax_delivery.webhook_id == tax_webhook.id
+ # Deferred payload covers the sync and async actions
+ assert not mocked_send_webhook_request_async.called
+ assert not mocked_send_webhook_request_sync.called
@mock.patch(
@@ -994,8 +817,7 @@ def test_checkout_shipping_method_update_from_external_shipping_to_different_ext
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == method_id
assert checkout.shipping_method_name == response_shipping_name
mocked_invalidate_checkout.assert_called_once()
@@ -1044,7 +866,15 @@ def test_checkout_shipping_method_update_from_external_shipping_to_the_same_exte
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.external_shipping_method_id = method_id
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=method_id,
+ name=response_shipping_name,
+ price_amount=response_shipping_price,
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_method_name = response_shipping_name
checkout.undiscounted_base_shipping_price_amount = Decimal(response_shipping_price)
checkout.save()
@@ -1065,9 +895,10 @@ def test_checkout_shipping_method_update_from_external_shipping_to_the_same_exte
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
- assert checkout.shipping_method_name == response_shipping_name
+ assert checkout.assigned_delivery.shipping_method_id == method_id
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal(
+ response_shipping_price
+ )
mocked_invalidate_checkout.assert_not_called()
mocked_call_checkout_info_event.assert_not_called()
@@ -1111,9 +942,8 @@ def test_checkout_shipping_method_update_from_external_shipping_to_built_in_meth
checkout.refresh_from_db()
+ assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == shipping_method.id
assert checkout.shipping_method_name == shipping_method.name
mocked_invalidate_checkout.assert_called_once()
@@ -1152,8 +982,7 @@ def test_checkout_shipping_method_update_from_external_shipping_to_none(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.shipping_method_name is None
mocked_invalidate_checkout.assert_called_once()
@@ -1198,8 +1027,9 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_different_bui
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == other_shipping_method.id
+ assert checkout.assigned_delivery.shipping_method_id == str(
+ other_shipping_method.id
+ )
assert checkout.shipping_method_name == other_shipping_method.name
mocked_invalidate_checkout.assert_called_once()
@@ -1262,8 +1092,7 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_external(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id == method_id
+ assert checkout.assigned_delivery.shipping_method_id == method_id
assert checkout.shipping_method_name == response_shipping_name
mocked_invalidate_checkout.assert_called_once()
@@ -1287,17 +1116,21 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_the_same_buil
# given
checkout = checkout_with_shipping_method
- shipping_method = checkout.shipping_method
- price = shipping_method.channel_listings.get().price
+ assigned_delivery = checkout.assigned_delivery
+ price = assigned_delivery.price
+ checkout.shipping_method_name = assigned_delivery.name
checkout.undiscounted_base_shipping_price_amount = price.amount
checkout.save()
+ method_id = graphene.Node.to_global_id(
+ "ShippingMethod", assigned_delivery.shipping_method_id
+ )
# when
response = api_client.post_graphql(
MUTATION_UPDATE_SHIPPING_METHOD,
{
"id": to_global_id_or_none(checkout),
- "shippingMethodId": to_global_id_or_none(shipping_method),
+ "shippingMethodId": method_id,
},
)
@@ -1305,16 +1138,13 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_the_same_buil
data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
errors = data["errors"]
assert not errors
- assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
- shipping_method
- )
- assert data["checkout"]["deliveryMethod"]["name"] == shipping_method.name
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == assigned_delivery.name
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.external_shipping_method_id is None
- assert checkout.shipping_method_id == shipping_method.id
- assert checkout.shipping_method_name == shipping_method.name
+ assert checkout.assigned_delivery_id == assigned_delivery.id
+ assert checkout.shipping_method_name == assigned_delivery.name
mocked_invalidate_checkout.assert_not_called()
mocked_call_checkout_info_event.assert_not_called()
@@ -1351,8 +1181,7 @@ def test_checkout_shipping_method_update_from_built_in_shipping_to_none(
checkout.refresh_from_db()
assert checkout.collection_point_id is None
- assert checkout.shipping_method_id is None
- assert checkout.external_shipping_method_id is None
+ assert checkout.assigned_delivery_id is None
assert checkout.shipping_method_name is None
mocked_invalidate_checkout.assert_called_once()
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update_nullable_shipping_method_id.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update_nullable_shipping_method_id.py
index 59ae94a3f6..311fd7efd3 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update_nullable_shipping_method_id.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update_nullable_shipping_method_id.py
@@ -1,5 +1,3 @@
-from unittest.mock import patch
-
import graphene
import pytest
@@ -40,12 +38,7 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
@pytest.mark.django_db
-@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "clean_delivery_method"
-)
def test_checkout_shipping_method_update_nullable_shipping_method_id(
- mock_clean_delivery_method,
staff_api_client,
shipping_method,
checkout_with_item_and_voucher_and_shipping_method,
@@ -53,9 +46,6 @@ def test_checkout_shipping_method_update_nullable_shipping_method_id(
# Set up the initial state of the checkout
checkout = checkout_with_item_and_voucher_and_shipping_method
- # Mock the clean_delivery_method function
- mock_clean_delivery_method.return_value = True
-
# Execute the mutation to remove the shipping method from the checkout
response = staff_api_client.post_graphql(
MUTATION_UPDATE_SHIPPING_METHOD,
@@ -69,8 +59,8 @@ def test_checkout_shipping_method_update_nullable_shipping_method_id(
assert data["checkout"]["shippingMethod"] is None
# Ensure the shipping method was removed from the checkout
- checkout.refresh_from_db(fields=["shipping_method"])
- assert checkout.shipping_method is None
+ checkout.refresh_from_db(fields=["assigned_delivery"])
+ assert checkout.assigned_delivery is None
# Assert that the shipping price is cleared
assert checkout.shipping_price.net.amount == 0
@@ -96,5 +86,5 @@ def test_checkout_shipping_method_update_nullable_shipping_method_id(
assert not errors
# Ensure the shipping method was added back to the checkout
- checkout.refresh_from_db(fields=["shipping_method"])
- assert checkout.shipping_method is not None
+ checkout.refresh_from_db(fields=["assigned_delivery"])
+ assert checkout.assigned_delivery is not 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 2879943fe7..040c3c2c2d 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
@@ -8,13 +8,19 @@ from django.db import transaction
from django.db.models.aggregates import Sum
from django.test import override_settings
from django.utils import timezone
+from freezegun import freeze_time
from prices import Money, TaxedMoney
from .....channel import MarkAsPaidStrategy
from .....checkout import calculations
from .....checkout.error_codes import OrderCreateFromCheckoutErrorCode
-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.models import Checkout, CheckoutLine
+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
@@ -27,6 +33,7 @@ from .....order.models import Fulfillment, Order
from .....payment.model_helpers import get_subtotal
from .....plugins.manager import PluginsManager, get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
+from .....shipping.models import ShippingMethod
from .....tests import race_condition
from .....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
from .....warehouse.tests.utils import get_available_quantity_for_stock
@@ -90,7 +97,7 @@ def test_order_from_checkout_with_inactive_channel(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
):
assert not gift_card.last_used_on
@@ -99,7 +106,7 @@ def test_order_from_checkout_with_inactive_channel(
channel.is_active = False
channel.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -137,14 +144,14 @@ def test_order_from_checkout(
gift_card,
address,
address_usa,
- shipping_method,
+ checkout_delivery,
customer_user,
):
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address_usa
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -206,7 +213,6 @@ def test_order_from_checkout(
order_line = order.lines.first()
line_tax_class = order_line.variant.product.tax_class
- shipping_tax_class = shipping_method.tax_class
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
@@ -218,13 +224,16 @@ def test_order_from_checkout(
assert order_line.tax_class_metadata == line_tax_class.metadata
assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
+ assigned_delivery = checkout.assigned_delivery
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(assigned_delivery.shipping_method_id)
assert order.shipping_tax_rate is not None
- assert order.shipping_tax_class_name == shipping_tax_class.name
- assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert order.shipping_tax_class.id == assigned_delivery.tax_class_id
+ assert order.shipping_tax_class_name == assigned_delivery.tax_class_name
+ assert order.shipping_tax_class_metadata == assigned_delivery.tax_class_metadata
assert (
- order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ order.shipping_tax_class_private_metadata
+ == assigned_delivery.tax_class_private_metadata
)
assert order.search_vector
@@ -248,12 +257,12 @@ def test_order_from_checkout_with_transaction(
permission_handle_checkouts,
permission_manage_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_and_transaction_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -291,13 +300,13 @@ def test_order_from_checkout_saving_addresses_off(
permission_handle_checkouts,
permission_manage_checkouts,
address,
- shipping_method,
+ checkout_delivery,
customer_user,
):
# given
checkout = checkout_with_item_and_transaction_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save_shipping_address = False
checkout.save_billing_address = False
@@ -351,12 +360,12 @@ def test_order_from_checkout_auto_confirm_flag(
permission_handle_checkouts,
permission_manage_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_and_transaction_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -393,12 +402,12 @@ def test_order_from_checkout_with_metadata(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -468,12 +477,12 @@ def test_order_from_checkout_with_metadata_checkout_without_metadata(
checkout_with_gift_card,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -535,12 +544,13 @@ def test_order_from_checkout_by_app_with_missing_permission(
checkout_with_item,
customer_user,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.user = customer_user
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+
checkout.billing_address = address
checkout.save()
@@ -566,13 +576,13 @@ def test_order_from_checkout_gift_card_bought(
permission_handle_checkouts,
checkout_with_gift_card_items,
address,
- shipping_method,
+ checkout_delivery,
payment_txn_captured,
):
# given
checkout = checkout_with_gift_card_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -648,11 +658,11 @@ def test_order_from_checkout_no_checkout_email(
permission_handle_checkouts,
checkout_with_gift_card,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_gift_card
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -684,11 +694,11 @@ def test_order_from_checkout_with_variant_without_sku(
gift_card,
permission_handle_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -731,11 +741,11 @@ def test_order_from_checkout_with_variant_without_price(
checkout_with_item,
gift_card,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -803,7 +813,7 @@ def test_order_from_checkout_with_voucher(
checkout_with_voucher_percentage,
voucher_percentage,
address,
- shipping_method,
+ checkout_delivery,
):
code = voucher_percentage.codes.first()
voucher_used_count = code.used
@@ -812,7 +822,7 @@ def test_order_from_checkout_with_voucher(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -849,7 +859,10 @@ def test_order_from_checkout_with_voucher(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
+
order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()
assert order_discount
assert (
@@ -874,6 +887,7 @@ def test_order_from_checkout_with_voucher_and_gift_card(
gift_card,
address,
shipping_method,
+ checkout_delivery,
):
# given
checkout_with_voucher_percentage.gift_cards.add(gift_card)
@@ -891,7 +905,7 @@ def test_order_from_checkout_with_voucher_and_gift_card(
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -940,7 +954,9 @@ def test_order_from_checkout_with_voucher_and_gift_card(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()
assert order_discount
assert (
@@ -970,7 +986,7 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(
checkout_with_voucher_percentage,
voucher_percentage,
address,
- shipping_method,
+ checkout_delivery,
):
code = voucher_percentage.codes.first()
voucher_used_count = code.used
@@ -985,7 +1001,7 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(
checkout_line_variant = checkout_line.variant
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1028,7 +1044,9 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
order_line_discount = OrderLineDiscount.objects.get()
assert order_line_discount
assert (
@@ -1050,7 +1068,7 @@ def test_order_from_checkout_with_specific_product_voucher(
checkout_with_item_and_voucher_specific_products,
voucher_specific_product_type,
address,
- shipping_method,
+ checkout_delivery,
):
code = voucher_specific_product_type.codes.first()
voucher_used_count = code.used
@@ -1059,7 +1077,7 @@ def test_order_from_checkout_with_specific_product_voucher(
checkout = checkout_with_item_and_voucher_specific_products
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1095,7 +1113,9 @@ def test_order_from_checkout_with_specific_product_voucher(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
order_line_discount = OrderLineDiscount.objects.get()
assert order_line_discount
@@ -1119,6 +1139,7 @@ def test_order_from_checkout_with_free_shipping_voucher_and_gift_card(
voucher_percentage,
gift_card,
address,
+ checkout_delivery,
shipping_method,
):
# given
@@ -1140,7 +1161,7 @@ def test_order_from_checkout_with_free_shipping_voucher_and_gift_card(
voucher_percentage.save(update_fields=["usage_limit"])
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1153,7 +1174,7 @@ def test_order_from_checkout_with_free_shipping_voucher_and_gift_card(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- shipping_price = shipping_listing.price
+ shipping_price = checkout.assigned_delivery.price
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -1187,7 +1208,9 @@ def test_order_from_checkout_with_free_shipping_voucher_and_gift_card(
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()
assert order_discount
assert order_discount.amount_value == shipping_amount
@@ -1215,7 +1238,7 @@ def test_order_from_checkout_voucher_not_increase_uses_on_preprocess_creation_fa
checkout_with_voucher_percentage,
voucher_percentage,
address,
- shipping_method,
+ checkout_delivery,
):
mocked_preprocess_order_creation.side_effect = TaxError("tax error!")
code = voucher_percentage.codes.first()
@@ -1226,7 +1249,7 @@ def test_order_from_checkout_voucher_not_increase_uses_on_preprocess_creation_fa
checkout = checkout_with_voucher_percentage
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1295,12 +1318,12 @@ def test_order_from_checkout_on_catalogue_promotion(
permission_manage_checkouts,
permission_manage_orders,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_on_promotion
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1357,12 +1380,12 @@ def test_order_from_checkout_on_order_promotion(
permission_manage_checkouts,
permission_manage_orders,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_and_order_discount
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1414,12 +1437,12 @@ def test_order_from_checkout_on_gift_promotion(
permission_manage_checkouts,
permission_manage_orders,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_and_gift_promotion
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
line_count = checkout.lines.count()
@@ -1478,12 +1501,12 @@ def test_order_from_checkout_on_catalogue_and_gift_promotion(
permission_handle_checkouts,
permission_manage_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item_on_promotion
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1571,11 +1594,9 @@ def test_order_from_checkout_without_inventory_tracking(
permission_handle_checkouts,
checkout_with_variant_without_inventory_tracking,
address,
- shipping_method,
):
checkout = checkout_with_variant_without_inventory_tracking
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1620,7 +1641,9 @@ def test_order_from_checkout_without_inventory_tracking(
assert checkout_line_variant == order_line.variant
assert not order_line.allocations.all()
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
def test_order_from_checkout_checkout_without_lines(
@@ -1629,11 +1652,11 @@ def test_order_from_checkout_checkout_without_lines(
permission_handle_checkouts,
checkout,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -1669,7 +1692,7 @@ def test_order_from_checkout_insufficient_stock(
app_api_client,
checkout_with_item,
address,
- shipping_method,
+ checkout_delivery,
permission_handle_checkouts,
):
checkout = checkout_with_item
@@ -1679,7 +1702,7 @@ def test_order_from_checkout_insufficient_stock(
checkout_line.quantity = quantity_available + 1
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1702,7 +1725,7 @@ def test_order_from_checkout_insufficient_stock_reserved_by_other_user(
permission_handle_checkouts,
checkout_with_item,
address,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
checkout = checkout_with_item
@@ -1728,7 +1751,7 @@ def test_order_from_checkout_insufficient_stock_reserved_by_other_user(
checkout_line.quantity = 1
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1753,7 +1776,7 @@ def test_order_from_checkout_own_reservation(
permission_handle_checkouts,
checkout_with_item,
address,
- shipping_method,
+ checkout_delivery,
channel_USD,
):
checkout = checkout_with_item
@@ -1764,7 +1787,7 @@ def test_order_from_checkout_own_reservation(
checkout_line.quantity = quantity_available
checkout_line.save()
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -1930,7 +1953,7 @@ def test_order_from_checkout_0_total_value(
gift_card,
permission_handle_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
assert not gift_card.last_used_on
@@ -1955,8 +1978,6 @@ def test_order_from_checkout_0_total_value(
checkout_line_variant.price_amount = Decimal(0)
checkout_line_variant.save()
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -2202,11 +2223,11 @@ def test_order_from_draft_create_with_preorder_variant(
permission_handle_checkouts,
checkout_with_item_and_preorder_item,
address,
- shipping_method,
+ checkout_delivery,
):
checkout = checkout_with_item_and_preorder_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -2247,7 +2268,9 @@ def test_order_from_draft_create_with_preorder_variant(
for variant_id, quantity in variants_and_quantities.items():
assert order.lines.get(variant_id=variant_id).quantity == quantity
assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_method.id == int(
+ checkout.assigned_delivery.shipping_method_id
+ )
preorder_line = order.lines.filter(variant__is_preorder=True).first()
assert not preorder_line.allocations.exists()
@@ -2335,14 +2358,14 @@ def test_order_from_checkout_create_when_line_without_listing(
listing_filter_field,
checkout_with_items,
address,
- shipping_method,
+ checkout_delivery,
app_api_client,
permission_handle_checkouts,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2394,12 +2417,12 @@ def test_order_from_draft_create_variant_channel_listing_no_price(
permission_handle_checkouts,
checkout_with_items,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2451,12 +2474,12 @@ def test_order_from_draft_create_product_channel_listing_does_not_exist(
permission_handle_checkouts,
checkout_with_items,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2508,13 +2531,13 @@ def test_order_from_draft_create_product_channel_listing_not_available_for_purch
permission_handle_checkouts,
checkout_with_items,
address,
- shipping_method,
+ checkout_delivery,
available_for_purchase,
):
# given
checkout = checkout_with_items
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
checkout.metadata_storage.store_value_in_private_metadata(
@@ -2564,7 +2587,7 @@ def test_order_from_draft_create_0_total_value_from_voucher(
app_api_client,
permission_handle_checkouts,
checkout_without_shipping_required,
- shipping_method,
+ checkout_delivery,
address,
voucher,
):
@@ -2584,8 +2607,6 @@ def test_order_from_draft_create_0_total_value_from_voucher(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -2645,8 +2666,6 @@ def test_order_from_draft_create_0_total_value_from_giftcard(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- checkout.refresh_from_db()
-
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -2721,12 +2740,12 @@ def test_order_from_checkout_with_transaction_empty_product_translation(
permission_handle_checkouts,
permission_manage_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -2770,12 +2789,12 @@ def test_order_from_checkout_with_translation_equal_name(
permission_handle_checkouts,
permission_manage_checkouts,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
@@ -2863,6 +2882,130 @@ def test_order_from_checkout_order_status_changed_after_creation(
assert order["status"] == OrderStatus.UNFULFILLED.upper()
+@patch(
+ "saleor.graphql.checkout.mutations.order_create_from_checkout."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+def test_order_from_checkout_refreshes_shipping_methods_when_stale(
+ mocked_get_or_fetch_checkout_deliveries,
+ app_api_client,
+ permission_handle_checkouts,
+ site_settings,
+ checkout_ready_to_complete,
+ gift_card,
+ address,
+ address_usa,
+ customer_user,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+
+ assert not data["errors"]
+ assert mocked_get_or_fetch_checkout_deliveries.called
+
+
+@freeze_time("2023-01-01 12:00:00")
+@patch(
+ "saleor.checkout.fetch.fetch_shipping_methods_for_checkout",
+ wraps=fetch_shipping_methods_for_checkout,
+)
+def test_order_from_checkout_do_not_refresh_shipping_methods_when_not_stale(
+ mocked_fetch_checkout_deliveries,
+ app_api_client,
+ permission_handle_checkouts,
+ site_settings,
+ checkout_ready_to_complete,
+ gift_card,
+ address,
+ address_usa,
+ customer_user,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now() + datetime.timedelta(hours=1)
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+
+ assert not data["errors"]
+ assert not mocked_fetch_checkout_deliveries.called
+
+
+@freeze_time("2023-01-01 12:00:00")
+@patch(
+ "saleor.graphql.checkout.mutations.order_create_from_checkout."
+ "get_or_fetch_checkout_deliveries",
+ wraps=get_or_fetch_checkout_deliveries,
+)
+def test_order_from_checkout_refreshes_shipping_methods_when_stale_and_invalid(
+ mocked_get_or_fetch_checkout_deliveries,
+ app_api_client,
+ permission_handle_checkouts,
+ site_settings,
+ checkout_ready_to_complete,
+ gift_card,
+ address,
+ address_usa,
+ customer_user,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.delivery_methods_stale_at = timezone.now()
+ checkout.save(update_fields=["delivery_methods_stale_at"])
+
+ # Shipping is not available anymore
+ ShippingMethod.objects.all().delete()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ new_now_time = timezone.now() + datetime.timedelta(hours=16)
+
+ # when
+ with freeze_time(new_now_time):
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert data["errors"]
+ assert (
+ data["errors"][0]["code"]
+ == OrderCreateFromCheckoutErrorCode.INVALID_SHIPPING_METHOD.name
+ )
+
+ assert Order.objects.count() == 0
+ assert mocked_get_or_fetch_checkout_deliveries.called
+
+
@pytest.mark.integration
@override_settings(
PLUGINS=[
@@ -2902,8 +3045,15 @@ def test_order_from_checkout_with_external_shipping(
mocked_sync_webhook.return_value = mock_json_response
checkout = checkout_with_item
- checkout.external_shipping_method_id = graphql_external_method_id
- checkout.shipping_method_name = external_shipping_name
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=graphql_external_method_id,
+ name=external_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_address = address
checkout.billing_address = address
checkout.save()
@@ -3017,8 +3167,15 @@ def test_order_from_checkout_with_external_shipping_private_metadata(
mocked_sync_webhook.return_value = mock_json_response
checkout = checkout_with_item
- checkout.external_shipping_method_id = graphql_external_method_id
- checkout.shipping_method_name = external_shipping_name
+ checkout.assigned_delivery = CheckoutDelivery.objects.create(
+ checkout=checkout,
+ external_shipping_method_id=graphql_external_method_id,
+ name=external_shipping_name,
+ price_amount="10.00",
+ currency="USD",
+ maximum_delivery_days=7,
+ is_external=True,
+ )
checkout.shipping_address = address
checkout.billing_address = address
checkout.save()
@@ -3052,6 +3209,7 @@ def test_order_from_checkout_with_external_shipping_private_metadata(
)
+@freeze_time("2023-01-01 12:00:00")
@pytest.mark.integration
def test_order_from_checkout_builtin_shipping_method_metadata_denormalization(
app_api_client,
@@ -3059,21 +3217,26 @@ def test_order_from_checkout_builtin_shipping_method_metadata_denormalization(
checkout_with_item,
shipping_method,
address,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.billing_address = address
- checkout.shipping_method = shipping_method
- checkout.save()
expected_metadata_key = "AnyKey"
expected_metadata_value = "AnyValue"
expected_shipping_metadata = {
expected_metadata_key: expected_metadata_value,
}
- shipping_method.metadata = expected_shipping_metadata
- shipping_method.save()
+ assigned_delivery = checkout_delivery(checkout, shipping_method)
+ assigned_delivery.metadata = expected_shipping_metadata
+ assigned_delivery.save()
+
+ checkout.shipping_address = address
+ checkout.billing_address = address
+ checkout.assigned_delivery = assigned_delivery
+ checkout.delivery_methods_stale_at = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.save()
+
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
# when
diff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.py
index 4a44981a01..0cae4c412f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_utils.py
+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py
@@ -1,9 +1,8 @@
import graphene
-from prices import Money
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.models import CheckoutDelivery
from .....plugins.manager import get_plugins_manager
-from .....shipping.interface import ShippingMethodData
from ...mutations.utils import (
CheckoutLineData,
assign_delivery_method_to_checkout,
@@ -203,7 +202,6 @@ def test_assign_delivery_method_to_checkout_delivery_method_to_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.shipping_method is None
assert checkout_info.collection_point is None
@@ -224,28 +222,36 @@ def test_assign_delivery_method_to_checkout_delivery_method_to_external(
method_id = graphene.Node.to_global_id(
"app", f"{shipping_app.id}:{app_shipping_id}"
)
- external_shipping_data = ShippingMethodData(
- name=app_shipping_name, id=method_id, price=Money(0, checkout.currency)
+
+ 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, external_shipping_data
+ checkout_info, lines_info, manager, shipping_method
)
# then
- assert checkout.external_shipping_method_id == method_id
assert checkout.shipping_method_name == app_shipping_name
- assert checkout.shipping_method_id is None
- assert checkout_info.shipping_method is None
+ 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, shipping_method_weight_based, warehouses_for_cc, checkout_delivery
):
# given
- checkout.shipping_method = shipping_method_weight_based
+ 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)
@@ -265,6 +271,5 @@ def test_assign_delivery_method_to_checkout_delivery_method_to_cc(
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.shipping_method_id is None
+ assert checkout.assigned_delivery is None
assert checkout.shipping_method_name is None
- assert checkout_info.shipping_method is None
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index b07d7f49b4..e960c808f1 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -3,6 +3,7 @@ import json
from decimal import Decimal
from unittest import mock
+import freezegun
import graphene
import pytest
from django.core.exceptions import ValidationError
@@ -51,7 +52,6 @@ from ....product.models import (
ProductVariantChannelListing,
)
from ....shipping.models import ShippingMethod, ShippingMethodTranslation
-from ....shipping.utils import convert_to_shipping_method_data
from ....tests import race_condition
from ....tests.utils import dummy_editorjs
from ....warehouse import WarehouseClickAndCollectOption
@@ -60,122 +60,6 @@ from ...core.utils import to_global_id_or_none
from ...payment.enums import TokenizedPaymentFlowEnum
from ...tests.utils import assert_no_permission, get_graphql_content
from ..enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
-from ..mutations.utils import (
- clean_delivery_method,
- update_checkout_shipping_method_if_invalid,
-)
-
-
-def test_clean_delivery_method_after_shipping_address_changes_stay_the_same(
- checkout_with_single_item, address, shipping_method, other_shipping_method
-):
- """Ensure the current shipping method applies to new address.
-
- If it does, then it doesn't need to be changed.
- """
-
- checkout = checkout_with_single_item
- checkout.shipping_address = address
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- delivery_method = convert_to_shipping_method_data(
- shipping_method, shipping_method.channel_listings.first()
- )
- is_valid_method = clean_delivery_method(checkout_info, delivery_method)
- assert is_valid_method is True
-
-
-def test_clean_delivery_method_with_preorder_is_valid_for_enabled_warehouse(
- checkout_with_preorders_only, address, warehouses_for_cc
-):
- checkout = checkout_with_preorders_only
- checkout.shipping_address = address
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- is_valid_method = clean_delivery_method(checkout_info, warehouses_for_cc[1])
-
- assert is_valid_method is True
-
-
-def test_clean_delivery_method_does_nothing_if_no_shipping_method(
- checkout_with_single_item, address, other_shipping_method
-):
- """If no shipping method was selected, it shouldn't return an error."""
-
- checkout = checkout_with_single_item
- checkout.shipping_address = address
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- is_valid_method = clean_delivery_method(checkout_info, None)
- assert is_valid_method is True
-
-
-def test_update_checkout_shipping_method_if_invalid(
- checkout_with_single_item,
- address,
- shipping_method,
- other_shipping_method,
- shipping_zone_without_countries,
-):
- # If the shipping method is invalid, it should be removed.
-
- checkout = checkout_with_single_item
- checkout.shipping_address = address
- checkout.shipping_method = shipping_method
-
- shipping_method.shipping_zone = shipping_zone_without_countries
- shipping_method.save(update_fields=["shipping_zone"])
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- update_checkout_shipping_method_if_invalid(checkout_info, lines)
-
- assert checkout.shipping_method is None
- assert checkout_info.get_delivery_method_info().delivery_method is None
-
- # Ensure the checkout's shipping method was saved
- checkout.refresh_from_db(fields=["shipping_method"])
- assert checkout.shipping_method is None
-
-
-def test_update_checkout_shipping_method_if_invalid_no_checkout_metadata(
- checkout_with_single_item,
- address,
- shipping_method,
- other_shipping_method,
- shipping_zone_without_countries,
-):
- # If the shipping method is invalid, it should be removed.
-
- # given
- checkout = checkout_with_single_item
- checkout.metadata_storage.delete()
- checkout.shipping_address = address
- checkout.shipping_method = shipping_method
-
- shipping_method.shipping_zone = shipping_zone_without_countries
- shipping_method.save(update_fields=["shipping_zone"])
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- # when
- update_checkout_shipping_method_if_invalid(checkout_info, lines)
-
- # then
- assert checkout.shipping_method is None
- assert checkout_info.get_delivery_method_info().delivery_method is None
-
- # Ensure the checkout's shipping method was saved
- checkout.refresh_from_db(fields=["shipping_method"])
- assert checkout.shipping_method is None
@pytest.fixture
@@ -337,9 +221,11 @@ query getCheckout($id: ID) {
def test_checkout_selected_shipping_method(
- api_client, checkout_with_item, address, shipping_zone
+ api_client, checkout_with_item, address, shipping_zone, checkout_delivery
):
+ # given
checkout_with_item.shipping_address = address
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
shipping_method = shipping_zone.shipping_methods.first()
@@ -358,8 +244,6 @@ def test_checkout_selected_shipping_method(
ShippingMethodTranslation.objects.create(
language_code="pl", shipping_method=shipping_method, name=translated_name
)
- checkout_with_item.shipping_method = shipping_method
- checkout_with_item.save()
# when
query = GET_CHECKOUT_SELECTED_SHIPPING_METHOD
@@ -368,7 +252,6 @@ def test_checkout_selected_shipping_method(
content = get_graphql_content(response)
data = content["data"]["checkout"]
- shipping_method = shipping_zone.shipping_methods.first()
# then
assert data["shippingMethod"]["id"] == (
graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
@@ -385,10 +268,8 @@ def test_checkout_selected_shipping_method(
data["shippingMethod"]["maximumDeliveryDays"]
== shipping_method.maximum_delivery_days
)
- assert data["shippingMethod"]["minimumOrderWeight"]["unit"] == "KG"
- assert data["shippingMethod"]["minimumOrderWeight"]["value"] == min_weight
- assert data["shippingMethod"]["maximumOrderWeight"]["unit"] == "KG"
- assert data["shippingMethod"]["maximumOrderWeight"]["value"] == max_weight
+ assert data["shippingMethod"]["minimumOrderWeight"] is None
+ assert data["shippingMethod"]["maximumOrderWeight"] is None
assert data["shippingMethod"]["metadata"][0]["key"] == metadata_key
assert data["shippingMethod"]["metadata"][0]["value"] == metadata_value
assert data["shippingMethod"]["translation"]["name"] == translated_name
@@ -410,22 +291,32 @@ query getCheckout($id: ID) {
def test_checkout_selected_shipping_method_as_staff(
- staff_api_client, checkout_with_item, shipping_zone, permission_manage_shipping
+ staff_api_client,
+ checkout_with_item,
+ shipping_zone,
+ checkout_delivery,
+ permission_manage_shipping,
+ address,
):
# given
staff_api_client.user.user_permissions.add(permission_manage_shipping)
- shipping_method = shipping_zone.shipping_methods.first()
+
+ shipping_method = shipping_zone.shipping_methods.get()
metadata_key = "md key"
metadata_value = "md value"
shipping_method.store_value_in_private_metadata({metadata_key: metadata_value})
shipping_method.save()
- checkout_with_item.shipping_method = shipping_method
+
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.shipping_address = address
checkout_with_item.save()
# when
query = GET_CHECKOUT_SELECTED_SHIPPING_METHOD_PRIVATE_FIELDS
variables = {"id": to_global_id_or_none(checkout_with_item)}
response = staff_api_client.post_graphql(query, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["checkout"]
@@ -483,19 +374,18 @@ GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS = (
@pytest.mark.parametrize("field", ["availableShippingMethods", "shippingMethods"])
def test_checkout_available_shipping_methods(
- api_client, checkout_with_item, address, shipping_zone, field
+ api_client,
+ checkout_with_item,
+ address,
+ shipping_zone,
+ checkout_delivery,
+ field,
):
# given
- checkout_with_item.shipping_address = address
- checkout_with_item.save()
shipping_method = shipping_zone.shipping_methods.first()
- min_weight = 0
- shipping_method.minimum_order_weight = Weight(oz=min_weight)
- max_weight = 10
- shipping_method.maximum_order_weight = Weight(kg=max_weight)
metadata_key = "md key"
metadata_value = "md value"
- raw_description = "this is descr"
+ raw_description = "Description"
description = dummy_editorjs(raw_description)
shipping_method.description = description
shipping_method.store_value_in_metadata({metadata_key: metadata_value})
@@ -505,6 +395,11 @@ def test_checkout_available_shipping_methods(
language_code="pl", shipping_method=shipping_method, name=translated_name
)
+ checkout_with_item.shipping_address = address
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.delivery_methods_stale_at = timezone.now()
+ checkout_with_item.save()
+
# when
query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS_TEMPLATE % field
variables = {"id": to_global_id_or_none(checkout_with_item)}
@@ -517,20 +412,14 @@ def test_checkout_available_shipping_methods(
graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
)
assert data[field][0]["name"] == shipping_method.name
- assert data[field][0]["type"] == shipping_method.type.upper()
+ assert data[field][0]["type"] is None
assert raw_description in data[field][0]["description"]
assert data[field][0]["active"]
assert data[field][0]["message"] == ""
- assert (
- data[field][0]["minimumDeliveryDays"] == shipping_method.minimum_delivery_days
- )
- assert (
- data[field][0]["maximumDeliveryDays"] == shipping_method.maximum_delivery_days
- )
- assert data[field][0]["minimumOrderWeight"]["unit"] == "KG"
- assert data[field][0]["minimumOrderWeight"]["value"] == min_weight
- assert data[field][0]["maximumOrderWeight"]["unit"] == "KG"
- assert data[field][0]["maximumOrderWeight"]["value"] == max_weight
+ assert data[field][0]["minimumDeliveryDays"] is None
+ assert data[field][0]["maximumDeliveryDays"] is None
+ assert data[field][0]["minimumOrderWeight"] is None
+ assert data[field][0]["maximumOrderWeight"] is None
assert data[field][0]["metadata"][0]["key"] == metadata_key
assert data[field][0]["metadata"][0]["value"] == metadata_value
assert data[field][0]["translation"]["name"] == translated_name
@@ -732,7 +621,7 @@ def test_checkout_available_shipping_methods_weight_method_with_higher_minimal_w
assert shipping_method.name not in shipping_methods
-def test_checkout_shipping_methods_with_price_based_shipping_method_and_discount(
+def test_checkout_deliveries_with_price_based_shipping_method_and_discount(
api_client,
checkout_with_item,
address,
@@ -772,7 +661,7 @@ def test_checkout_shipping_methods_with_price_based_shipping_method_and_discount
assert shipping_method.name not in shipping_methods
-def test_checkout_shipping_methods_with_price_based_shipping_and_shipping_discount(
+def test_checkout_deliveries_with_price_based_shipping_and_shipping_discount(
api_client,
checkout_with_item,
address,
@@ -817,7 +706,7 @@ def test_checkout_shipping_methods_with_price_based_shipping_and_shipping_discou
assert shipping_method.name in shipping_methods
-def test_checkout_shipping_methods_with_price_based_method_and_product_voucher(
+def test_checkout_deliveries_with_price_based_method_and_product_voucher(
api_client, checkout_with_item, address, shipping_method, voucher, channel_USD
):
"""Test that product discounts properly qualify checkout for price-based shipping."""
@@ -935,6 +824,7 @@ def test_checkout_available_shipping_methods_with_price_displayed(
listing.maximum_order_price = expected_max_order_price
listing.save()
checkout_with_item.shipping_address = address
+
checkout_with_item.save()
translated_name = "Dostawa ekspresowa"
ShippingMethodTranslation.objects.create(
@@ -954,14 +844,6 @@ def test_checkout_available_shipping_methods_with_price_displayed(
data["availableShippingMethods"][0]["price"]["amount"]
== expected_shipping_price.amount
)
- assert (
- data["availableShippingMethods"][0]["minimumOrderPrice"]["amount"]
- == expected_min_order_price.amount
- )
- assert (
- data["availableShippingMethods"][0]["maximumOrderPrice"]["amount"]
- == expected_max_order_price.amount
- )
assert data["availableShippingMethods"][0]["translation"]["name"] == translated_name
@@ -4259,10 +4141,16 @@ def test_query_checkout_lines_with_meta(
assert lines == expected_lines
-def test_clean_checkout(checkout_with_item, payment_dummy, address, shipping_method):
+def test_clean_checkout(
+ checkout_with_item,
+ payment_dummy,
+ address,
+ shipping_method,
+ checkout_delivery,
+):
checkout = checkout_with_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.billing_address = address
checkout.save()
@@ -4304,9 +4192,11 @@ def test_clean_checkout_no_shipping_method(checkout_with_item, address):
assert e.value.error_dict["shipping_method"][0].message == msg
-def test_clean_checkout_no_shipping_address(checkout_with_item, shipping_method):
+def test_clean_checkout_no_shipping_address(
+ checkout_with_item, shipping_method, checkout_delivery
+):
checkout = checkout_with_item
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.save()
manager = get_plugins_manager(allow_replica=False)
@@ -4319,13 +4209,18 @@ def test_clean_checkout_no_shipping_address(checkout_with_item, shipping_method)
def test_clean_checkout_invalid_shipping_method(
- checkout_with_item, address, shipping_zone_without_countries
+ checkout_with_item,
+ address,
+ shipping_zone_without_countries,
+ checkout_delivery,
):
checkout = checkout_with_item
checkout.shipping_address = address
shipping_method = shipping_zone_without_countries.shipping_methods.first()
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
checkout.save()
+ checkout.assigned_delivery.is_valid = False
+ checkout.assigned_delivery.save(update_fields=["is_valid"])
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
@@ -5009,3 +4904,303 @@ def test_query_checkout_email_with_explicit_email_for_authenticated_user(
content = get_graphql_content(response)
# Return the email explicitly assigned to the user
assert content["data"]["checkout"]["email"] == expected_email
+
+
[email protected]_time("2023-01-01 12:00:00")
+def test_query_checkout_delivery_method_invalidates_taxes_when_delivery_price_is_changed(
+ user_api_client, checkout_with_item, checkout_delivery, shipping_method, address
+):
+ # This test confirms that any change in the price of assigned delivery method
+ # will invalidate checkout prices and taxes even when shipping method is not changed.
+ # This confirms that the `deliveryMethod` field behaves the same way as before
+ # denormalizing deliveries on DB side.
+
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+
+ checkout.price_expiration = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.save()
+
+ current_checkout_delivery_price = checkout.assigned_delivery.price_amount
+
+ # Change shipping method price
+ shipping_method.channel_listings.all().update(
+ price_amount=current_checkout_delivery_price + 10
+ )
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ query = """
+ query getCheckout($id: ID) {
+ checkout(id: $id) {
+ deliveryMethod {
+ ... on ShippingMethod{
+ id
+ }
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now()
+ assert content["data"]["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+
[email protected]_time("2023-01-01 12:00:00")
+def test_query_checkout_delivery_method_invalidates_taxes_when_delivery_tax_class_is_changed(
+ user_api_client,
+ checkout_with_item,
+ checkout_delivery,
+ shipping_method,
+ address,
+ tax_class_zero_rates,
+):
+ # This test confirms that any change in the tax class of assigned delivery method
+ # will invalidate checkout prices and taxes even when shipping method is not changed.
+ # This confirms that the `deliveryMethod` field behaves the same way as before
+ # denormalizing deliveries on DB side.
+
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.save()
+
+ # Change tax class of shipping
+ assert shipping_method.tax_class != tax_class_zero_rates
+ shipping_method.tax_class = tax_class_zero_rates
+ shipping_method.save(update_fields=["tax_class"])
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ query = """
+ query getCheckout($id: ID) {
+ checkout(id: $id) {
+ deliveryMethod {
+ ... on ShippingMethod{
+ id
+ }
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now()
+ assert content["data"]["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+
[email protected]_time("2023-01-01 12:00:00")
+def test_query_checkout_delivery_method_dont_invalidate_taxes_when_nothing_changed(
+ user_api_client,
+ checkout_with_item,
+ checkout_delivery,
+ shipping_method,
+ address,
+):
+ # This test confirms that no change in the assigned delivery method
+ # will not trigger invalidation of checkout prices and taxes.
+ # This confirms that the `deliveryMethod` field behaves the same way as before
+ # denormalizing deliveries on DB side.
+
+ # given
+ expected_price_expiration = timezone.now() + datetime.timedelta(minutes=5)
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.price_expiration = expected_price_expiration
+ checkout.save()
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ query = """
+ query getCheckout($id: ID) {
+ checkout(id: $id) {
+ deliveryMethod {
+ ... on ShippingMethod{
+ id
+ }
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == expected_price_expiration
+ assert content["data"]["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+
[email protected]_time("2023-01-01 12:00:00")
+def test_query_checkout_shipping_method_invalidates_taxes_when_shipping_price_is_changed(
+ user_api_client, checkout_with_item, checkout_delivery, shipping_method, address
+):
+ # This test confirms that any change in the price of assigned delivery method
+ # will invalidate checkout prices and taxes even when shipping method is not changed.
+ # This confirms that the `shippingMethod` field behaves the same way as before
+ # denormalizing deliveries on DB side.
+
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+
+ checkout.price_expiration = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.save()
+
+ current_checkout_delivery_price = checkout.assigned_delivery.price_amount
+
+ # Change shipping method price
+ shipping_method.channel_listings.all().update(
+ price_amount=current_checkout_delivery_price + 10
+ )
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ query = """
+ query getCheckout($id: ID) {
+ checkout(id: $id) {
+ shippingMethod {
+ id
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now()
+ assert content["data"]["checkout"]["shippingMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+
[email protected]_time("2023-01-01 12:00:00")
+def test_query_checkout_shipping_method_invalidates_taxes_when_shipping_tax_class_is_changed(
+ user_api_client,
+ checkout_with_item,
+ checkout_delivery,
+ shipping_method,
+ address,
+ tax_class_zero_rates,
+):
+ # This test confirms that any change in the tax class of assigned delivery method
+ # will invalidate checkout prices and taxes even when shipping method is not changed.
+ # This confirms that the `shippingMethod` field behaves the same way as before
+ # denormalizing deliveries on DB side.
+
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(minutes=5)
+ checkout.save()
+
+ # Change tax class of shipping
+ assert shipping_method.tax_class != tax_class_zero_rates
+ shipping_method.tax_class = tax_class_zero_rates
+ shipping_method.save(update_fields=["tax_class"])
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ query = """
+ query getCheckout($id: ID) {
+ checkout(id: $id) {
+ shippingMethod {
+ id
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now()
+ assert content["data"]["checkout"]["shippingMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+
+
[email protected]_time("2023-01-01 12:00:00")
+def test_query_checkout_shipping_method_dont_invalidate_taxes_when_nothing_changed(
+ user_api_client,
+ checkout_with_item,
+ checkout_delivery,
+ shipping_method,
+ address,
+):
+ # This test confirms that no change in the assigned delivery method
+ # will not trigger invalidation of checkout prices and taxes.
+ # This confirms that the `shippingMethod` field behaves the same way as before
+ # denormalizing deliveries on DB side.
+
+ # given
+ expected_price_expiration = timezone.now() + datetime.timedelta(minutes=5)
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.delivery_methods_stale_at = timezone.now() - datetime.timedelta(minutes=5)
+ checkout.price_expiration = expected_price_expiration
+ checkout.save()
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ query = """
+ query getCheckout($id: ID) {
+ checkout(id: $id) {
+ shippingMethod {
+ id
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == expected_price_expiration
+ assert content["data"]["checkout"]["shippingMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
diff --git a/saleor/graphql/checkout/tests/test_checkout_digital.py b/saleor/graphql/checkout/tests/test_checkout_digital.py
index 0bd901422b..9d75973c4d 100644
--- a/saleor/graphql/checkout/tests/test_checkout_digital.py
+++ b/saleor/graphql/checkout/tests/test_checkout_digital.py
@@ -4,7 +4,7 @@ from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....plugins.manager import get_plugins_manager
from ...core.utils import to_global_id_or_none
from ...tests.utils import get_graphql_content
-from ..mutations.utils import update_checkout_shipping_method_if_invalid
+from ..mutations.utils import mark_checkout_deliveries_as_stale_if_needed
def test_checkout_has_no_available_shipping_methods(
@@ -39,19 +39,19 @@ def test_checkout_has_no_available_shipping_methods(
assert len(data["availableShippingMethods"]) == 0
-def test_remove_shipping_method_if_only_digital_in_checkout(
- checkout_with_digital_item, address, shipping_method
+def test_do_not_remove_shipping_method_if_only_digital_in_checkout(
+ checkout_with_digital_item, address, checkout_delivery
):
checkout = checkout_with_digital_item
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
- assert checkout.shipping_method
+ assert checkout.assigned_delivery
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- update_checkout_shipping_method_if_invalid(checkout_info, lines)
+ mark_checkout_deliveries_as_stale_if_needed(checkout_info.checkout, lines)
checkout.refresh_from_db()
- assert not checkout.shipping_method
+ assert checkout.assigned_delivery
diff --git a/saleor/graphql/checkout/tests/test_checkouts_query.py b/saleor/graphql/checkout/tests/test_checkouts_query.py
index 8f61737ebd..1672324ca0 100644
--- a/saleor/graphql/checkout/tests/test_checkouts_query.py
+++ b/saleor/graphql/checkout/tests/test_checkouts_query.py
@@ -3,9 +3,7 @@ from unittest.mock import patch
from django.utils import timezone
-from ....shipping.models import ShippingMethod
from ....webhook.event_types import WebhookEventSyncType
-from ...core.utils import to_global_id_or_none
from ...tests.utils import get_graphql_content
CHECKOUTS_QUERY = """
@@ -87,9 +85,12 @@ def test_query_checkouts_do_not_trigger_external_shipping_webhook_with_flat_rate
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
checkout = checkout_with_delivery_method_for_external_shipping
checkout.price_expiration = timezone.now()
+ checkout.delivery_methods_stale_at = timezone.now()
checkout.undiscounted_base_shipping_price_amount = Decimal(100)
checkout.save()
+ checkout_delivery = checkout.shipping_methods.get()
+
# when
response = staff_api_client.post_graphql(
CHECKOUTS_QUERY,
@@ -101,25 +102,23 @@ def test_query_checkouts_do_not_trigger_external_shipping_webhook_with_flat_rate
assert len(data) == 1
checkout_data = data[0]["node"]
- shipping_method = ShippingMethod.objects.get()
assert len(checkout_data["shippingMethods"]) == 1
- assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["shippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
assert len(checkout_data["availableShippingMethods"]) == 1
- assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["availableShippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
delivery_method = checkout_data["deliveryMethod"]
assert delivery_method
- assert delivery_method["id"] == checkout.external_shipping_method_id
- assert delivery_method["name"] == checkout.shipping_method_name
- assert (
- delivery_method["price"]["amount"]
- == checkout.undiscounted_base_shipping_price_amount
- )
+ assert delivery_method["id"] == checkout.assigned_delivery.shipping_method_id
+ assert delivery_method["name"] == checkout.assigned_delivery.name
+ assert delivery_method["price"]["amount"] == checkout.assigned_delivery.price_amount
mocked_request.assert_not_called()
@@ -143,9 +142,13 @@ def test_query_checkouts_do_not_trigger_external_shipping_webhook_with_tax_app(
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
checkout = checkout_with_delivery_method_for_external_shipping
checkout.price_expiration = timezone.now()
+
checkout.undiscounted_base_shipping_price_amount = Decimal(100)
+ checkout.delivery_methods_stale_at = timezone.now()
checkout.save()
+ checkout_delivery = checkout.shipping_methods.get()
+
# when
response = staff_api_client.post_graphql(
CHECKOUTS_QUERY,
@@ -157,25 +160,23 @@ def test_query_checkouts_do_not_trigger_external_shipping_webhook_with_tax_app(
assert len(data) == 1
checkout_data = data[0]["node"]
- shipping_method = ShippingMethod.objects.get()
assert len(checkout_data["shippingMethods"]) == 1
- assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["shippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
assert len(checkout_data["availableShippingMethods"]) == 1
- assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["availableShippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
delivery_method = checkout_data["deliveryMethod"]
assert delivery_method
- assert delivery_method["id"] == checkout.external_shipping_method_id
- assert delivery_method["name"] == checkout.shipping_method_name
- assert (
- delivery_method["price"]["amount"]
- == checkout.undiscounted_base_shipping_price_amount
- )
+ assert delivery_method["id"] == checkout.assigned_delivery.shipping_method_id
+ assert delivery_method["name"] == checkout.assigned_delivery.name
+ assert delivery_method["price"]["amount"] == checkout.assigned_delivery.price_amount
mocked_request.assert_not_called()
@@ -199,8 +200,11 @@ def test_query_checkouts_do_not_trigger_exclude_shipping_webhooks_with_flat_rate
checkout = checkout_with_delivery_method_for_external_shipping
checkout.price_expiration = timezone.now()
checkout.undiscounted_base_shipping_price_amount = Decimal(100)
+ checkout.delivery_methods_stale_at = timezone.now()
checkout.save()
+ checkout_delivery = checkout.shipping_methods.get()
+
# when
response = staff_api_client.post_graphql(
CHECKOUTS_QUERY,
@@ -212,25 +216,23 @@ def test_query_checkouts_do_not_trigger_exclude_shipping_webhooks_with_flat_rate
assert len(data) == 1
checkout_data = data[0]["node"]
- shipping_method = ShippingMethod.objects.get()
assert len(checkout_data["shippingMethods"]) == 1
- assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["shippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
assert len(checkout_data["availableShippingMethods"]) == 1
- assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["availableShippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
delivery_method = checkout_data["deliveryMethod"]
assert delivery_method
- assert delivery_method["id"] == checkout.external_shipping_method_id
- assert delivery_method["name"] == checkout.shipping_method_name
- assert (
- delivery_method["price"]["amount"]
- == checkout.undiscounted_base_shipping_price_amount
- )
+ assert delivery_method["id"] == checkout.assigned_delivery.shipping_method_id
+ assert delivery_method["name"] == checkout.assigned_delivery.name
+ assert delivery_method["price"]["amount"] == checkout.assigned_delivery.price_amount
mocked_request.assert_not_called()
@@ -254,8 +256,11 @@ def test_query_checkouts_do_not_trigger_exclude_shipping_webhooks_with_tax_app(
checkout = checkout_with_delivery_method_for_external_shipping
checkout.price_expiration = timezone.now()
checkout.undiscounted_base_shipping_price_amount = Decimal(100)
+ checkout.delivery_methods_stale_at = timezone.now()
checkout.save()
+ checkout_delivery = checkout.shipping_methods.get()
+
# when
response = staff_api_client.post_graphql(
CHECKOUTS_QUERY,
@@ -267,23 +272,21 @@ def test_query_checkouts_do_not_trigger_exclude_shipping_webhooks_with_tax_app(
assert len(data) == 1
checkout_data = data[0]["node"]
- shipping_method = ShippingMethod.objects.get()
assert len(checkout_data["shippingMethods"]) == 1
- assert checkout_data["shippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["shippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
assert len(checkout_data["availableShippingMethods"]) == 1
- assert checkout_data["availableShippingMethods"][0]["id"] == to_global_id_or_none(
- shipping_method
+ assert (
+ checkout_data["availableShippingMethods"][0]["id"]
+ == checkout_delivery.shipping_method_id
)
delivery_method = checkout_data["deliveryMethod"]
assert delivery_method
- assert delivery_method["id"] == checkout.external_shipping_method_id
- assert delivery_method["name"] == checkout.shipping_method_name
- assert (
- delivery_method["price"]["amount"]
- == checkout.undiscounted_base_shipping_price_amount
- )
+ assert delivery_method["id"] == checkout.assigned_delivery.shipping_method_id
+ assert delivery_method["name"] == checkout.assigned_delivery.name
+ assert delivery_method["price"]["amount"] == checkout.assigned_delivery.price_amount
mocked_request.assert_not_called()
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 642fcf932e..7c2bab4682 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,12 +1,15 @@
+import uuid
from decimal import Decimal
from typing import TYPE_CHECKING, Any
import graphene
+from django.utils import timezone
from promise import Promise
from ...account.models import User
from ...checkout import calculations, models, problems
from ...checkout.calculations import fetch_checkout_data
+from ...checkout.fetch import fetch_shipping_methods_for_checkout
from ...checkout.utils import get_valid_collection_points_for_checkout
from ...core.db.connection import allow_writer_in_context
from ...core.prices import quantize_price
@@ -24,6 +27,7 @@ from ...permission.enums import (
PaymentPermissions,
)
from ...shipping.interface import ShippingMethodData
+from ...shipping.utils import convert_checkout_delivery_to_shipping_method_data
from ...tax.utils import get_display_gross_prices
from ...warehouse import models as warehouse_models
from ...warehouse.reservations import is_reservation_enabled
@@ -80,7 +84,10 @@ from ..tax.dataloaders import (
TaxConfigurationPerCountryByTaxConfigurationIDLoader,
)
from ..utils import get_user_or_app_from_context
-from ..warehouse.dataloaders import StocksReservationsByCheckoutTokenLoader
+from ..warehouse.dataloaders import (
+ StocksReservationsByCheckoutTokenLoader,
+ WarehouseByIdLoader,
+)
from ..warehouse.types import Warehouse
from ..webhook.dataloaders.pregenerated_payload_for_checkout_tax import (
PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,
@@ -95,6 +102,10 @@ from .dataloaders import (
CheckoutMetadataByCheckoutIdLoader,
TransactionItemsByCheckoutIDLoader,
)
+from .dataloaders.checkout_delivery import (
+ CheckoutDeliveriesOnlyValidByCheckoutIdLoader,
+ CheckoutDeliveryByIdLoader,
+)
from .enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
from .utils import prevent_sync_event_circular_query
@@ -615,6 +626,139 @@ class DeliveryMethod(graphene.Union):
return super().resolve_type(instance, info)
+def _should_load_denormalized_checkout_deliveries(
+ checkout_context: SyncWebhookControlContext[models.Checkout],
+):
+ return not checkout_context.allow_sync_webhooks or (
+ checkout_context.node.delivery_methods_stale_at
+ and checkout_context.node.delivery_methods_stale_at > timezone.now()
+ )
+
+
+def _load_denormalized_checkout_deliveries(checkout_pk: uuid.UUID, info: ResolveInfo):
+ return (
+ CheckoutDeliveriesOnlyValidByCheckoutIdLoader(info.context)
+ .load(checkout_pk)
+ .then(
+ lambda shipping_methods: [
+ convert_checkout_delivery_to_shipping_method_data(sm)
+ for sm in shipping_methods
+ ]
+ )
+ )
+
+
+def _resolve_checkout_deliveries(
+ root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
+):
+ checkout = root.node
+
+ def with_checkout_info(data):
+ if _should_load_denormalized_checkout_deliveries(root):
+ return _load_denormalized_checkout_deliveries(checkout.pk, info)
+
+ checkout_info, excluded_payloads = data
+ checkout_info.pregenerated_payloads_for_excluded_shipping_method = (
+ excluded_payloads
+ )
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ checkout.delivery_methods_stale_at = (
+ checkout_info.checkout.delivery_methods_stale_at
+ )
+ CheckoutDeliveriesOnlyValidByCheckoutIdLoader(info.context).prime(
+ checkout.pk, shipping_methods
+ )
+ return [
+ convert_checkout_delivery_to_shipping_method_data(sm)
+ for sm in shipping_methods
+ ]
+
+ if _should_load_denormalized_checkout_deliveries(root):
+ return _load_denormalized_checkout_deliveries(checkout.pk, info)
+
+ excluded_shipping_methods_payloads_dataloader = (
+ PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(
+ info.context
+ ).load(root.node.token)
+ )
+ checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(info.context).load(
+ root.node.token
+ )
+ dataloaders_promise = Promise.all(
+ [
+ checkout_info_dataloader,
+ excluded_shipping_methods_payloads_dataloader,
+ ]
+ )
+ return dataloaders_promise.then(with_checkout_info)
+
+
+def _resolve_checkout_delivery(
+ root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
+) -> Promise[ShippingMethodData | None] | None:
+ checkout = root.node
+
+ assigned_delivery_id = checkout.assigned_delivery_id
+ if not assigned_delivery_id:
+ return None
+
+ if (
+ checkout.delivery_methods_stale_at
+ and checkout.delivery_methods_stale_at > timezone.now()
+ ) or not root.allow_sync_webhooks:
+ return (
+ CheckoutDeliveryByIdLoader(info.context)
+ .load(assigned_delivery_id)
+ .then(
+ lambda sm: (
+ convert_checkout_delivery_to_shipping_method_data(sm)
+ if sm.is_valid and sm.active
+ else None
+ )
+ )
+ )
+
+ def with_checkout_info(data):
+ checkout_info, excluded_payloads = data
+ checkout_info.pregenerated_payloads_for_excluded_shipping_method = (
+ excluded_payloads
+ )
+ checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ shipping_methods = fetch_shipping_methods_for_checkout(checkout_info)
+ root.node.delivery_methods_stale_at = (
+ checkout_info.checkout.delivery_methods_stale_at
+ )
+ CheckoutDeliveriesOnlyValidByCheckoutIdLoader(info.context).prime(
+ checkout.pk, shipping_methods
+ )
+ CheckoutInfoByCheckoutTokenLoader(info.context).clear(root.node.token)
+
+ for sm in shipping_methods:
+ if sm.id == assigned_delivery_id:
+ CheckoutDeliveryByIdLoader(info.context).prime(assigned_delivery_id, sm)
+ return convert_checkout_delivery_to_shipping_method_data(sm)
+
+ CheckoutDeliveryByIdLoader(info.context).clear(assigned_delivery_id)
+ return None
+
+ excluded_shipping_methods_payloads_dataloader = (
+ PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(
+ info.context
+ ).load(root.node.token)
+ )
+ checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(info.context).load(
+ root.node.token
+ )
+ dataloaders_promise = Promise.all(
+ [
+ checkout_info_dataloader,
+ excluded_shipping_methods_payloads_dataloader,
+ ]
+ )
+ return dataloaders_promise.then(with_checkout_info)
+
+
class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
id = graphene.ID(required=True, description="The ID of the checkout.")
created = DateTime(
@@ -991,32 +1135,7 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
@staticmethod
def resolve_shipping_method(root: SyncWebhookControlContext[models.Checkout], info):
- def with_checkout_info(data):
- checkout_info, excluded_payloads = data
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- checkout_info.pregenerated_payloads_for_excluded_shipping_method = (
- excluded_payloads
- )
- delivery_method = checkout_info.get_delivery_method_info().delivery_method
- if not delivery_method or not isinstance(
- delivery_method, ShippingMethodData
- ):
- return None
- return delivery_method
-
- excluded_shipping_methods_payloads_dataloader = None
- if root.allow_sync_webhooks:
- excluded_shipping_methods_payloads_dataloader = (
- PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(
- info.context
- ).load(root.node.token)
- )
- checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- root.node.token
- )
- return Promise.all(
- [checkout_info_dataloader, excluded_shipping_methods_payloads_dataloader]
- ).then(with_checkout_info)
+ return _resolve_checkout_delivery(root, info)
@staticmethod
@traced_resolver
@@ -1024,57 +1143,17 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_shipping_methods(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- @allow_writer_in_context(info.context)
- def with_checkout_info(data):
- checkout_info, excluded_payloads = data
- checkout_info.pregenerated_payloads_for_excluded_shipping_method = (
- excluded_payloads
- )
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- return checkout_info.get_all_shipping_methods()
-
- excluded_shipping_methods_payloads_dataloader = None
- if root.allow_sync_webhooks:
- excluded_shipping_methods_payloads_dataloader = (
- PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(
- info.context
- ).load(root.node.token)
- )
-
- checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- root.node.token
- )
- return Promise.all(
- [checkout_info_dataloader, excluded_shipping_methods_payloads_dataloader]
- ).then(with_checkout_info)
+ return _resolve_checkout_deliveries(root, info)
@staticmethod
def resolve_delivery_method(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- @allow_writer_in_context(info.context)
- def with_checkout_info(data):
- checkout_info, excluded_payloads = data
- checkout_info.pregenerated_payloads_for_excluded_shipping_method = (
- excluded_payloads
- )
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- return checkout_info.get_delivery_method_info().delivery_method
-
- excluded_shipping_methods_payloads_dataloader = None
- if root.allow_sync_webhooks:
- excluded_shipping_methods_payloads_dataloader = (
- PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(
- info.context
- ).load(root.node.token)
- )
+ checkout = root.node
+ if checkout.collection_point_id:
+ return WarehouseByIdLoader(info.context).load(checkout.collection_point_id)
- checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- root.node.token
- )
- return Promise.all(
- [checkout_info_dataloader, excluded_shipping_methods_payloads_dataloader]
- ).then(with_checkout_info)
+ return _resolve_checkout_delivery(root, info)
@staticmethod
def resolve_quantity(
@@ -1205,30 +1284,9 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_available_shipping_methods(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- @allow_writer_in_context(info.context)
- def with_checkout_info(data):
- checkout_info, excluded_payloads = data
- checkout_info.pregenerated_payloads_for_excluded_shipping_method = (
- excluded_payloads
- )
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
-
- return checkout_info.valid_shipping_methods
-
- excluded_shipping_methods_payloads_dataloader = None
- if root.allow_sync_webhooks:
- excluded_shipping_methods_payloads_dataloader = (
- PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(
- info.context
- ).load(root.node.token)
- )
-
- checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- root.node.token
+ return _resolve_checkout_deliveries(root, info).then(
+ lambda methods: [method for method in methods if method.active]
)
- return Promise.all(
- [checkout_info_dataloader, excluded_shipping_methods_payloads_dataloader]
- ).then(with_checkout_info)
@staticmethod
@traced_resolver
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index c906e2e766..93876668a3 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -10,7 +10,6 @@ from promise import Promise
from ...account.models import Address
from ...account.models import User as UserModel
-from ...checkout.utils import get_external_shipping_id
from ...core.anonymize import obfuscate_address, obfuscate_email
from ...core.db.connection import allow_writer_in_context
from ...core.prices import quantize_price
@@ -31,6 +30,7 @@ from ...order import OrderOrigin, OrderStatus, calculations, models
from ...order.calculations import fetch_order_prices_if_expired
from ...order.models import FulfillmentStatus
from ...order.utils import (
+ get_external_shipping_id,
get_order_country,
get_valid_collection_points_for_order,
get_valid_shipping_methods_for_order,
diff --git a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
index 896a2d875b..da3b74795c 100644
--- a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
@@ -120,13 +120,17 @@ def test_checkout_add_payment_without_shipping_method_with_shipping_required(
def test_checkout_add_payment_with_shipping_method_and_shipping_required(
- user_api_client, checkout_with_shipping_required, other_shipping_method, address
+ user_api_client,
+ checkout_with_shipping_required,
+ other_shipping_method,
+ address,
+ checkout_delivery,
):
# given
checkout = checkout_with_shipping_required
checkout.billing_address = address
checkout.shipping_address = address
- checkout.shipping_method = other_shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, other_shipping_method)
checkout.save()
manager = get_plugins_manager(allow_replica=False)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 662c972493..71142c608e 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5297,10 +5297,10 @@ type ShippingMethod implements Node & ObjectWithMetadata @doc(category: "Shippin
price: Money!
"""Maximum order price for this shipping method."""
- maximumOrderPrice: Money
+ maximumOrderPrice: Money @deprecated
"""Minimal order price for this shipping method."""
- minimumOrderPrice: Money
+ minimumOrderPrice: Money @deprecated
"""Describes if this shipping method is active and can be selected."""
active: Boolean!
diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.py
index 6de34c6d42..ca471e40aa 100644
--- a/saleor/graphql/shipping/types.py
+++ b/saleor/graphql/shipping/types.py
@@ -380,10 +380,14 @@ class ShippingMethod(BaseObjectType):
Money, required=True, description="The price of selected shipping method."
)
maximum_order_price = graphene.Field(
- Money, description="Maximum order price for this shipping method."
+ Money,
+ description="Maximum order price for this shipping method.",
+ deprecation_reason=DEFAULT_DEPRECATION_REASON,
)
minimum_order_price = graphene.Field(
- Money, description="Minimal order price for this shipping method."
+ Money,
+ description="Minimal order price for this shipping method.",
+ deprecation_reason=DEFAULT_DEPRECATION_REASON,
)
active = graphene.Boolean(
required=True,
diff --git a/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.py b/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.py
index 5ede646687..33bffa1f69 100644
--- a/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.py
+++ b/saleor/graphql/webhook/dataloaders/pregenerated_payloads_for_checkout_filter_shipping_methods.py
@@ -3,10 +3,14 @@ from typing import Any
from promise import Promise
+from ....checkout.fetch import get_available_built_in_shipping_methods_for_checkout_info
from ....core.utils.events import get_is_deferred_payload
from ....webhook.event_types import WebhookEventSyncType
from ...app.dataloaders.apps import AppsByEventTypeLoader
-from ...checkout.dataloaders.models import CheckoutByTokenLoader
+from ...checkout.dataloaders.checkout_infos import (
+ CheckoutInfoByCheckoutTokenLoader,
+ CheckoutLinesInfoByCheckoutTokenLoader,
+)
from ...core.dataloaders import DataLoader
from ..subscription_payload import (
generate_payload_promise_from_subscription,
@@ -56,49 +60,76 @@ class PregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader(Data
event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
- def generate_payloads(data):
- checkouts, apps, request_context, webhooks = data
- apps_map = {app.id: app for app in apps}
- promises = []
- for checkout in checkouts:
- for webhook in webhooks:
- if not webhook.subscription_query:
- continue
- query_hash = get_subscription_query_hash(webhook.subscription_query)
- app_id = webhook.app_id
- app = apps_map[app_id]
- checkout_token = str(checkout.token)
- promise_payload = generate_payload_promise_from_subscription(
- event_type=event_type,
- subscribable_object=checkout,
- subscription_query=webhook.subscription_query,
- request=request_context,
- app=app,
- )
- promises.append(promise_payload)
-
- def store_payload(
- payload,
- checkout_token=checkout_token,
- app_id=app_id,
- query_hash=query_hash,
- ):
- if payload:
- results[checkout_token][app_id][query_hash] = payload
-
- promise_payload.then(store_payload)
-
- def return_payloads(_payloads):
- return [results[str(checkout.token)] for checkout in checkouts]
+ def with_webhooks(webhooks):
+ if not webhooks:
+ return [None for _ in keys]
- return Promise.all(promises).then(return_payloads)
+ def generate_payloads(data):
+ checkout_infos, lines_infos, apps, request_context = data
+ apps_map = {app.id: app for app in apps}
+ promises = []
+ for checkout_info, lines_info in zip(
+ checkout_infos, lines_infos, strict=False
+ ):
+ checkout = checkout_info.checkout
+ checkout_info.lines_info = lines_info
+ built_in_shipping_methods = (
+ get_available_built_in_shipping_methods_for_checkout_info(
+ checkout_info
+ )
+ )
- checkouts = CheckoutByTokenLoader(self.context).load_many(keys)
- apps = AppsByEventTypeLoader(self.context).load(event_type)
- request_context = PayloadsRequestContextByEventTypeLoader(self.context).load(
- event_type
- )
- webhooks = WebhooksByEventTypeLoader(self.context).load(event_type)
- return Promise.all([checkouts, apps, request_context, webhooks]).then(
- generate_payloads
+ for webhook in webhooks:
+ if not webhook.subscription_query:
+ continue
+ query_hash = get_subscription_query_hash(
+ webhook.subscription_query
+ )
+ app_id = webhook.app_id
+ app = apps_map[app_id]
+ checkout_token = str(checkout.token)
+ promise_payload = generate_payload_promise_from_subscription(
+ event_type=event_type,
+ subscribable_object=(checkout, built_in_shipping_methods),
+ subscription_query=webhook.subscription_query,
+ request=request_context,
+ app=app,
+ )
+ promises.append(promise_payload)
+
+ def store_payload(
+ payload,
+ checkout_token=checkout_token,
+ app_id=app_id,
+ query_hash=query_hash,
+ ):
+ if payload:
+ results[checkout_token][app_id][query_hash] = payload
+
+ promise_payload.then(store_payload)
+
+ def return_payloads(_payloads):
+ return [
+ results[str(checkout_info.checkout.token)]
+ for checkout_info in checkout_infos
+ ]
+
+ return Promise.all(promises).then(return_payloads)
+
+ apps = AppsByEventTypeLoader(self.context).load(event_type)
+ request_context = PayloadsRequestContextByEventTypeLoader(
+ self.context
+ ).load(event_type)
+ lines_infos = CheckoutLinesInfoByCheckoutTokenLoader(
+ self.context
+ ).load_many(keys)
+ checkout_infos = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(
+ keys
+ )
+ return Promise.all(
+ [checkout_infos, lines_infos, apps, request_context]
+ ).then(generate_payloads)
+
+ return (
+ WebhooksByEventTypeLoader(self.context).load(event_type).then(with_webhooks)
)
diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.py
index 452d722dc0..f79cf8fe9e 100644
--- a/saleor/graphql/webhook/resolvers.py
+++ b/saleor/graphql/webhook/resolvers.py
@@ -1,13 +1,6 @@
-from django.conf import settings
from django.db.models import Exists, OuterRef, Q
from ...app.models import App
-from ...checkout.fetch import (
- fetch_checkout_info,
- fetch_checkout_lines,
- get_all_shipping_methods_list,
- get_available_built_in_shipping_methods_for_checkout_info,
-)
from ...core.exceptions import PermissionDenied
from ...permission.enums import AppPermission
from ...webhook import models, payloads
@@ -60,48 +53,3 @@ def resolve_sample_payload(info: ResolveInfo, event_name, app):
if user and user.has_perm(required_permission):
return payloads.generate_sample_payload(event_name)
raise PermissionDenied(permissions=[required_permission])
-
-
-def resolve_shipping_methods_for_checkout(
- info: ResolveInfo,
- checkout,
- manager,
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- lines, _ = fetch_checkout_lines(
- checkout, database_connection_name=database_connection_name
- )
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- checkout_info = fetch_checkout_info(
- checkout,
- lines,
- manager,
- shipping_channel_listings,
- database_connection_name=database_connection_name,
- )
- all_shipping_methods = get_all_shipping_methods_list(
- checkout_info,
- )
- return all_shipping_methods
-
-
-def resolve_only_internal_shipping_methods_for_checkout(
- info: ResolveInfo,
- checkout,
- manager,
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- lines, _ = fetch_checkout_lines(
- checkout, database_connection_name=database_connection_name
- )
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- checkout_info = fetch_checkout_info(
- checkout,
- lines,
- manager,
- shipping_channel_listings,
- database_connection_name=database_connection_name,
- )
- return get_available_built_in_shipping_methods_for_checkout_info(
- checkout_info,
- )
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index cf74d110eb..d3f063bea4 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -15,7 +15,6 @@ from ...discount.models import (
)
from ...graphql.shop.types import Shop
from ...menu.models import MenuItemTranslation
-from ...order.utils import get_all_shipping_methods_for_order
from ...page.models import PageTranslation
from ...payment.interface import (
ListStoredPaymentMethodsRequestData,
@@ -38,7 +37,6 @@ from ...webhook.const import MAX_FILTERABLE_CHANNEL_SLUGS_LIMIT
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..account.types import User as UserType
from ..app.types import App as AppType
-from ..channel.dataloaders.by_self import ChannelByIdLoader
from ..channel.enums import TransactionFlowStrategyEnum
from ..core import ResolveInfo
from ..core.context import (
@@ -74,16 +72,10 @@ from ..order.dataloaders import OrderByIdLoader
from ..order.types import Order, OrderGrantedRefund
from ..payment.enums import TokenizedPaymentFlowEnum, TransactionActionEnum
from ..payment.types import TransactionItem
-from ..plugins.dataloaders import plugin_manager_promise_callback
from ..product.dataloaders import ProductVariantByIdLoader
-from ..shipping.dataloaders import ShippingMethodChannelListingByChannelSlugLoader
from ..shipping.types import ShippingMethod
from ..translations import types as translation_types
from ..warehouse.dataloaders import WarehouseByIdLoader
-from .resolvers import (
- resolve_only_internal_shipping_methods_for_checkout,
- resolve_shipping_methods_for_checkout,
-)
TRANSLATIONS_TYPES_MAP = {
ProductTranslation: translation_types.ProductTranslation,
@@ -2482,15 +2474,18 @@ class ShippingListMethodsForCheckout(SubscriptionObjectType, CheckoutBase):
)
@staticmethod
- @plugin_manager_promise_callback
- def resolve_shipping_methods(root, info: ResolveInfo, manager):
+ def resolve_checkout(root, _info: ResolveInfo):
+ _, data = root
+ checkout, _ = data
+ return SyncWebhookControlContext(node=checkout)
+
+ @staticmethod
+ def resolve_shipping_methods(root, info: ResolveInfo):
# We should only use internal shipping methods to prevent the generation of circular payloads.
# We aren't able to list shipping methods that are not internal for listing shipping methods webhook type.
- _, checkout = root
- database_connection_name = get_database_connection_name(info.context)
- return resolve_only_internal_shipping_methods_for_checkout(
- info, checkout, manager, database_connection_name
- )
+ _, data = root
+ _, built_in_shipping_methods = data
+ return built_in_shipping_methods
class Meta:
root_type = None
@@ -2525,13 +2520,16 @@ class CheckoutFilterShippingMethods(SubscriptionObjectType, CheckoutBase):
)
@staticmethod
- @plugin_manager_promise_callback
- def resolve_shipping_methods(root, info: ResolveInfo, manager):
- _, checkout = root
- database_connection_name = get_database_connection_name(info.context)
- return resolve_shipping_methods_for_checkout(
- info, checkout, manager, database_connection_name
- )
+ def resolve_checkout(root, _info: ResolveInfo):
+ _, data = root
+ checkout, _ = data
+ return SyncWebhookControlContext(node=checkout)
+
+ @staticmethod
+ def resolve_shipping_methods(root, _info: ResolveInfo):
+ _, data = root
+ _, shipping_methods = data
+ return shipping_methods
class Meta:
root_type = None
@@ -2548,20 +2546,16 @@ class OrderFilterShippingMethods(SubscriptionObjectType, OrderBase):
)
@staticmethod
- def resolve_shipping_methods(root, info: ResolveInfo):
- _, order = root
-
- def with_channel(channel):
- def with_listings(channel_listings):
- return get_all_shipping_methods_for_order(order, channel_listings)
-
- return (
- ShippingMethodChannelListingByChannelSlugLoader(info.context)
- .load(channel.slug)
- .then(with_listings)
- )
+ def resolve_order(root, info: ResolveInfo):
+ _, data = root
+ order, _ = data
+ return SyncWebhookControlContext(order)
- return ChannelByIdLoader(info.context).load(order.channel_id).then(with_channel)
+ @staticmethod
+ def resolve_shipping_methods(root, info: ResolveInfo):
+ _, data = root
+ _, shipping_methods = data
+ return shipping_methods
class Meta:
root_type = None
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index fad7533072..20f4bc8d59 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -82,9 +82,13 @@ if TYPE_CHECKING:
from ..payment.models import Payment, TransactionItem
from ..plugins.manager import PluginsManager
+
logger = logging.getLogger(__name__)
+PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"
+
+
def get_order_country(order: Order) -> str:
"""Return country to which order will be shipped."""
return get_active_country(
@@ -1414,3 +1418,9 @@ def calculate_draft_order_line_price_expiration_date(
now = timezone.now()
return now + timedelta(hours=freeze_period)
return None
+
+
+def get_external_shipping_id(order: "Order"):
+ if not order:
+ return None
+ return order.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
index 9e1cd43dbe..94b32b6277 100644
--- a/saleor/payment/gateways/adyen/tests/conftest.py
+++ b/saleor/payment/gateways/adyen/tests/conftest.py
@@ -71,10 +71,10 @@ def adyen_plugin(settings, channel_USD):
@pytest.fixture
-def payment_adyen_for_checkout(checkout_with_items, address, shipping_method):
+def payment_adyen_for_checkout(checkout_with_items, address, checkout_delivery):
checkout_with_items.billing_address = address
checkout_with_items.shipping_address = address
- checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
checkout_with_items.save()
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout_with_items)
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
index 97d65f1252..e45c413ad7 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py
@@ -75,7 +75,7 @@ def test_append_checkout_details(
"amountExcludingTax": "1000",
"amountIncludingTax": "1000",
"description": "Shipping - DHL",
- "id": f"Shipping:{checkout_ready_to_complete.shipping_method.id}",
+ "id": f"Shipping:{checkout_ready_to_complete.assigned_delivery.shipping_method_id}",
"quantity": 1,
"taxAmount": "0",
"taxPercentage": 0,
@@ -125,7 +125,7 @@ def test_append_checkout_details_without_sku(
"amountExcludingTax": "1000",
"amountIncludingTax": "1000",
"description": "Shipping - DHL",
- "id": f"Shipping:{checkout_ready_to_complete.shipping_method.id}",
+ "id": f"Shipping:{checkout_ready_to_complete.assigned_delivery.shipping_method_id}",
"quantity": 1,
"taxAmount": "0",
"taxPercentage": 0,
@@ -188,7 +188,7 @@ def test_append_checkout_details_tax_included(
"amountExcludingTax": "1000",
"amountIncludingTax": "1000",
"description": "Shipping - DHL",
- "id": f"Shipping:{checkout_ready_to_complete.shipping_method.id}",
+ "id": f"Shipping:{checkout_ready_to_complete.assigned_delivery.shipping_method_id}",
"quantity": 1,
"taxAmount": "0",
"taxPercentage": 0,
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
index a345eda750..1497ab709b 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -155,12 +155,11 @@ def test_handle_authorization_sets_psp_reference(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -201,11 +200,10 @@ def test_handle_authorization_for_checkout(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
checkout_token = str(checkout.token)
@@ -253,11 +251,10 @@ def test_handle_authorization_for_checkout_partial_payment(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -296,7 +293,6 @@ def test_handle_authorization_for_checkout_out_of_stock_after_payment(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
refund_response = {"pspReference": "refund-psp"}
mock_refund_response = MagicMock()
@@ -305,7 +301,7 @@ def test_handle_authorization_for_checkout_out_of_stock_after_payment(
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -362,12 +358,11 @@ def test_handle_authorization_for_checkout_that_cannot_be_finalized(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -431,12 +426,11 @@ def test_handle_authorization_calls_refund_for_inactive_payment(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -518,11 +512,10 @@ def test_handle_authorization_for_checkout_one_of_variants_deleted(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -569,7 +562,7 @@ def test_handle_authorization_with_adyen_auto_capture(
):
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -846,11 +839,10 @@ def test_handle_capture_for_checkout(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
checkout_token = str(checkout.token)
@@ -900,7 +892,6 @@ def test_handle_capture_inactive_payment(
adyen_plugin,
inactive_payment_adyen_for_checkout,
address,
- shipping_method,
):
"""Test that refund is called on inactive payments without an existing capture transaction."""
# given
@@ -933,7 +924,6 @@ def test_handle_capture_inactive_payment_capture_txn_exists(
adyen_plugin,
inactive_payment_adyen_for_checkout,
address,
- shipping_method,
):
"""Test that refund is called on inactive payments with existing capture transactions."""
# given
@@ -976,14 +966,13 @@ def test_handle_capture_for_checkout_order_not_created_checkout_line_variant_del
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
"""Ensure that payment is not captured when a checkout line variant is deleted."""
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -1590,7 +1579,7 @@ def test_handle_cancel_or_refund_action_cancel_invalid_payment_id(
def test_handle_not_created_order_order_created(
- checkout_ready_to_complete, payment_adyen_for_checkout, adyen_plugin, notification
+ payment_adyen_for_checkout, adyen_plugin, notification
):
payment_adyen_for_checkout.charge_status = ChargeStatus.FULLY_CHARGED
payment_adyen_for_checkout.save(update_fields=["charge_status"])
@@ -1612,7 +1601,6 @@ def test_handle_not_created_order_order_created(
@patch("saleor.payment.gateway.refund")
def test_handle_not_created_order_order_not_created_checkout_line_variant_deleted(
refund_mock,
- checkout_ready_to_complete,
payment_adyen_for_checkout,
adyen_plugin,
notification,
@@ -1894,7 +1882,7 @@ def test_handle_order_closed_success_true(
):
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
checkout_token = str(checkout.token)
@@ -1945,7 +1933,7 @@ def test_handle_order_closed_with_adyen_partial_payments_success_true(
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
checkout_token = str(checkout.token)
@@ -2030,7 +2018,7 @@ def test_handle_order_closed_with_adyen_partial_payments_success_true_without_am
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
checkout_token = str(checkout.token)
@@ -2119,14 +2107,13 @@ def test_order_closed_with_adyen_partial_payments_unable_to_create_order(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
# given
mock_order_data.side_effect = ValidationError("Test error")
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
@@ -2194,13 +2181,12 @@ def test_order_closed_with_not_active_payment(
adyen_plugin,
payment_adyen_for_checkout,
address,
- shipping_method,
):
# given
checkout = payment_adyen_for_checkout.checkout
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+
checkout.billing_address = address
checkout.save()
diff --git a/saleor/payment/gateways/stripe/tests/conftest.py b/saleor/payment/gateways/stripe/tests/conftest.py
index 8937ff0cc2..a0b6589ed3 100644
--- a/saleor/payment/gateways/stripe/tests/conftest.py
+++ b/saleor/payment/gateways/stripe/tests/conftest.py
@@ -13,10 +13,10 @@ from ..plugin import StripeGatewayPlugin
@pytest.fixture
-def payment_stripe_for_checkout(checkout_with_items, address, shipping_method):
+def payment_stripe_for_checkout(checkout_with_items, address, checkout_delivery):
checkout_with_items.billing_address = address
checkout_with_items.shipping_address = address
- checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.assigned_delivery = checkout_delivery(checkout_with_items)
checkout_with_items.email = "[email protected]"
checkout_with_items.save()
manager = get_plugins_manager(allow_replica=False)
diff --git a/saleor/payment/tests/test_utils/test_utils.py b/saleor/payment/tests/test_utils/test_utils.py
index 7d0d837d40..3934dad2b5 100644
--- a/saleor/payment/tests/test_utils/test_utils.py
+++ b/saleor/payment/tests/test_utils/test_utils.py
@@ -126,14 +126,12 @@ def test_create_payment_lines_information_checkout_with_flat_rates(
tax_configuration_flat_rates,
default_tax_class,
address,
- shipping_method,
):
# given
tax_configuration_flat_rates.prices_entered_with_tax = False
tax_configuration_flat_rates.save()
checkout_with_items.shipping_address = address
- checkout_with_items.shipping_method = shipping_method
checkout_with_items.save()
manager = get_plugins_manager(allow_replica=False)
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 1b379c16ec..6eea53aae6 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -95,15 +95,14 @@ def test_calculate_checkout_line_total(
prices_entered_with_tax,
checkout_with_item,
ship_to_pl_address,
- monkeypatch,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
plugin_configuration()
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
tax_configuration = checkout_with_item.channel.tax_configuration
@@ -150,7 +149,7 @@ def test_calculate_checkout_line_total_with_promotion(
checkout_with_item_on_promotion,
ship_to_pl_address,
monkeypatch,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -159,7 +158,7 @@ def test_calculate_checkout_line_total_with_promotion(
checkout = checkout_with_item_on_promotion
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -197,7 +196,7 @@ def test_calculate_checkout_line_total_with_promotion(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_total_with_variant_on_promotion(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -214,10 +213,9 @@ def test_calculate_checkout_line_total_with_variant_on_promotion(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -258,7 +256,7 @@ def test_calculate_checkout_line_total_with_order_promotion(
checkout_with_item_and_order_discount,
ship_to_pl_address,
monkeypatch,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -267,7 +265,8 @@ def test_calculate_checkout_line_total_with_order_promotion(
manager = get_plugins_manager(allow_replica=False)
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -306,7 +305,7 @@ def test_calculate_checkout_line_total_with_order_promotion(
def test_calculate_checkout_line_total_gift_promotion_line(
checkout_with_item_and_gift_promotion,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -315,7 +314,8 @@ def test_calculate_checkout_line_total_gift_promotion_line(
manager = get_plugins_manager(allow_replica=False)
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -351,7 +351,7 @@ def test_calculate_checkout_line_total_gift_promotion_line(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_total_with_voucher(
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -382,10 +382,9 @@ def test_calculate_checkout_line_total_with_voucher(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -414,7 +413,7 @@ def test_calculate_checkout_line_total_with_voucher(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_total_with_voucher_once_per_order(
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -442,10 +441,9 @@ def test_calculate_checkout_line_total_with_voucher_once_per_order(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -474,7 +472,7 @@ def test_calculate_checkout_line_total_with_voucher_once_per_order(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_total_with_variant_on_promotion_and_voucher(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -501,10 +499,9 @@ def test_calculate_checkout_line_total_with_variant_on_promotion_and_voucher(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -533,7 +530,7 @@ def test_calculate_checkout_line_total_with_variant_on_promotion_and_voucher(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_total_with_variant_on_promotion_and_voucher_only_once(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -561,10 +558,9 @@ def test_calculate_checkout_line_total_with_variant_on_promotion_and_voucher_onl
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -605,7 +601,7 @@ def test_calculate_checkout_line_without_sku_total(
checkout_with_item,
ship_to_pl_address,
monkeypatch,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
monkeypatch.setattr(
@@ -616,7 +612,7 @@ def test_calculate_checkout_line_without_sku_total(
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
tax_configuration = checkout_with_item.channel.tax_configuration
@@ -665,7 +661,7 @@ def test_calculate_checkout_line_without_sku_total_with_promotion(
checkout_with_item_on_promotion,
ship_to_pl_address,
monkeypatch,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -678,7 +674,8 @@ def test_calculate_checkout_line_without_sku_total_with_promotion(
checkout = checkout_with_item_on_promotion
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -1193,7 +1190,7 @@ def test_calculate_checkout_total_uses_default_calculation(
checkout_with_item,
product_with_single_variant,
voucher_percentage,
- shipping_zone,
+ checkout_delivery,
address,
ship_to_pl_address,
monkeypatch,
@@ -1217,7 +1214,7 @@ def test_calculate_checkout_total_uses_default_calculation(
tax_configuration.country_exceptions.all().delete()
voucher_amount = Money(voucher_amount, "USD")
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.discount = voucher_amount
if voucher_amount != "0.0":
checkout_with_item.voucher_code = voucher_percentage.code
@@ -1259,7 +1256,7 @@ def test_calculate_checkout_total_uses_default_calculation_with_promotion(
checkout_with_item_on_promotion,
product_with_single_variant,
voucher_percentage,
- shipping_zone,
+ checkout_delivery,
address,
ship_to_pl_address,
monkeypatch,
@@ -1285,7 +1282,7 @@ def test_calculate_checkout_total_uses_default_calculation_with_promotion(
tax_configuration.country_exceptions.all().delete()
voucher_amount = Money(voucher_amount, "USD")
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.discount = voucher_amount
if voucher_amount != "0.0":
checkout.voucher_code = voucher_percentage.code
@@ -1330,7 +1327,7 @@ def test_calculate_checkout_total(
checkout_with_item,
product_with_single_variant,
voucher_percentage,
- shipping_zone,
+ checkout_delivery,
address,
ship_to_pl_address,
monkeypatch,
@@ -1358,7 +1355,7 @@ def test_calculate_checkout_total(
tax_configuration.country_exceptions.all().delete()
voucher_amount = Money(voucher_amount, "USD")
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.discount = voucher_amount
if voucher_amount != "0.0":
checkout_with_item.voucher_code = voucher_percentage.code
@@ -1392,7 +1389,7 @@ def test_calculate_checkout_total(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_total_with_order_promotion(
checkout_with_item_and_order_discount,
- shipping_zone,
+ checkout_delivery,
ship_to_pl_address,
monkeypatch,
plugin_configuration,
@@ -1420,9 +1417,9 @@ def test_calculate_checkout_total_with_order_promotion(
tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
tax_configuration.country_exceptions.all().delete()
- shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method = shipping_method
- checkout.save(update_fields=["shipping_method"])
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
+ checkout.save(update_fields=["assigned_delivery", "shipping_method_name"])
line = checkout.lines.first()
product = line.variant.product
@@ -1442,9 +1439,7 @@ def test_calculate_checkout_total_with_order_promotion(
line_info = lines[0]
unit_price = line_info.variant.get_price(line_info.channel_listing)
subtotal_price_amount = (unit_price * line.quantity).amount - discount_amount
- shipping_price = shipping_method.channel_listings.get(
- channel=checkout.channel
- ).price
+ shipping_price = checkout.assigned_delivery.price
total_price_amount = subtotal_price_amount + shipping_price.amount
assert total == TaxedMoney(
net=Money(round(total_price_amount / Decimal("1.23"), 2), checkout.currency),
@@ -1456,7 +1451,7 @@ def test_calculate_checkout_total_with_order_promotion(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_total_with_gift_promotion(
checkout_with_item_and_gift_promotion,
- shipping_zone,
+ checkout_delivery,
ship_to_pl_address,
monkeypatch,
plugin_configuration,
@@ -1483,9 +1478,9 @@ def test_calculate_checkout_total_with_gift_promotion(
tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
tax_configuration.country_exceptions.all().delete()
- shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method = shipping_method
- checkout.save(update_fields=["shipping_method"])
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
+ checkout.save(update_fields=["assigned_delivery", "shipping_method_name"])
line = checkout.lines.get(is_gift=False)
product = line.variant.product
@@ -1505,9 +1500,7 @@ def test_calculate_checkout_total_with_gift_promotion(
line_info = [line_info for line_info in lines if not line_info.line.is_gift][0]
unit_price = line_info.variant.get_price(line_info.channel_listing)
subtotal_price_amount = (unit_price * line.quantity).amount
- shipping_price = shipping_method.channel_listings.get(
- channel=checkout.channel
- ).price
+ shipping_price = checkout.assigned_delivery.price
total_price_amount = subtotal_price_amount + shipping_price.amount
assert total == TaxedMoney(
net=Money(round(total_price_amount / Decimal("1.23"), 2), checkout.currency),
@@ -1532,7 +1525,7 @@ def test_calculate_checkout_total_with_promotion(
checkout_with_item_on_promotion,
product_with_single_variant,
voucher_percentage,
- shipping_zone,
+ checkout_delivery,
address,
ship_to_pl_address,
monkeypatch,
@@ -1562,7 +1555,9 @@ def test_calculate_checkout_total_with_promotion(
tax_configuration.country_exceptions.all().delete()
voucher_amount = Money(voucher_amount, "USD")
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
+
checkout.discount = voucher_amount
if voucher_amount != "0.0":
checkout.voucher_code = voucher_percentage.code
@@ -1617,6 +1612,7 @@ def test_calculate_checkout_total_for_JPY(
ship_to_pl_address,
monkeypatch,
plugin_configuration,
+ checkout_delivery,
):
# given
checkout = checkout_JPY_with_item
@@ -1640,7 +1636,9 @@ def test_calculate_checkout_total_for_JPY(
tax_configuration.country_exceptions.all().delete()
voucher_amount = Money(voucher_amount, "JPY")
- checkout.shipping_method = shipping_zone_JPY.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(
+ checkout, shipping_zone_JPY.shipping_methods.get()
+ )
checkout.discount = voucher_amount
voucher_percentage.channel_listings.create(
channel=channel_JPY,
@@ -1691,6 +1689,7 @@ def test_calculate_checkout_total_for_JPY_with_promotion(
ship_to_pl_address,
monkeypatch,
plugin_configuration,
+ checkout_delivery,
):
# given
checkout = checkout_JPY_with_item
@@ -1714,7 +1713,9 @@ def test_calculate_checkout_total_for_JPY_with_promotion(
tax_configuration.country_exceptions.all().delete()
voucher_amount = Money(voucher_amount, "JPY")
- checkout.shipping_method = shipping_zone_JPY.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(
+ checkout, shipping_zone_JPY.shipping_methods.get()
+ )
checkout.discount = voucher_amount
voucher_percentage.channel_listings.create(
channel=channel_JPY,
@@ -1800,7 +1801,7 @@ def test_calculate_checkout_total_voucher_on_entire_order(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -1824,7 +1825,7 @@ def test_calculate_checkout_total_voucher_on_entire_order(
net = variant.get_price(channel_listing) * checkout_with_item.lines.first().quantity
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.discount_amount = net.amount
checkout_with_item.save()
@@ -1851,7 +1852,7 @@ def test_calculate_checkout_total_voucher_on_entire_order_applied_once_per_order
monkeypatch,
site_settings,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -1882,15 +1883,14 @@ def test_calculate_checkout_total_voucher_on_entire_order_applied_once_per_order
)
discount_value = voucher_listing.discount_value
- shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.shipping_method_name = checkout_with_item.assigned_delivery.name
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_method
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.discount_amount = net.amount
checkout_with_item.save()
- shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)
- shipping_price = shipping_channel_listings.price
+ shipping_price = checkout_with_item.assigned_delivery.price
checkout_info = fetch_checkout_info(checkout_with_item, [], manager)
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -1921,7 +1921,7 @@ def test_calculate_checkout_total_voucher_on_entire_order_product_without_taxes(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -1947,14 +1947,14 @@ def test_calculate_checkout_total_voucher_on_entire_order_product_without_taxes(
discount_amount = Decimal("2.0")
checkout_with_item.shipping_address = ship_to_pl_address
- shipping_method = shipping_zone.shipping_methods.get()
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.shipping_method_name = checkout_with_item.assigned_delivery.name
+
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.discount_amount = discount_amount
checkout_with_item.save()
- shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)
- shipping_price = shipping_channel_listings.price
+ shipping_price = checkout_with_item.assigned_delivery.price
checkout_info = fetch_checkout_info(checkout_with_item, [], manager)
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -1991,7 +1991,7 @@ def test_calculate_checkout_total_voucher_on_shipping(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
"""Test that free shipping results in correct checkout totals."""
@@ -2009,13 +2009,12 @@ def test_calculate_checkout_total_voucher_on_shipping(
tax_configuration.save(update_fields=["prices_entered_with_tax"])
tax_configuration.country_exceptions.all().delete()
- shipping_method = shipping_zone.shipping_methods.get()
- shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)
-
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.voucher_code = voucher_free_shipping.code
- checkout_with_item.discount_amount = shipping_channel_listings.price.amount
+ checkout_with_item.discount_amount = (
+ checkout_with_item.assigned_delivery.price.amount
+ )
checkout_with_item.save()
checkout_info = fetch_checkout_info(checkout_with_item, [], manager)
@@ -2035,6 +2034,7 @@ def test_calculate_checkout_total_voucher_on_shipping(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_total_not_charged_product_and_shipping_with_0_price(
checkout_with_item,
+ checkout_delivery,
shipping_zone,
ship_to_pl_address,
monkeypatch,
@@ -2050,8 +2050,7 @@ def test_calculate_checkout_total_not_charged_product_and_shipping_with_0_price(
lambda *_: False,
)
manager = get_plugins_manager(allow_replica=False)
- checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.save()
+
channel = checkout_with_item.channel
tax_configuration = channel.tax_configuration
@@ -2060,13 +2059,14 @@ def test_calculate_checkout_total_not_charged_product_and_shipping_with_0_price(
tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
tax_configuration.country_exceptions.all().delete()
- shipping_method = shipping_zone.shipping_methods.get()
- shipping_channel_listing = shipping_method.channel_listings.get(channel=channel)
- shipping_channel_listing.price = Money(0, "USD")
- shipping_channel_listing.save()
-
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.shipping_address = ship_to_pl_address
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_zone.shipping_methods.get()
+ )
+ checkout_with_item.shipping_method_name = checkout_with_item.assigned_delivery.name
checkout_with_item.save()
+ checkout_with_item.assigned_delivery.price_amount = 0
+ checkout_with_item.assigned_delivery.save()
line = checkout_with_item.lines.first()
variant = line.variant
@@ -2092,7 +2092,7 @@ def test_calculate_checkout_total_not_charged_product_and_shipping_with_0_price(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_shipping(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
ship_to_pl_address,
site_settings,
@@ -2111,7 +2111,8 @@ def test_calculate_checkout_shipping(
checkout = checkout_with_item_on_promotion
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -2143,7 +2144,7 @@ def test_calculate_checkout_subtotal(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -2162,7 +2163,7 @@ def test_calculate_checkout_subtotal(
tax_configuration.country_exceptions.all().delete()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
checkout_info = fetch_checkout_info(checkout_with_item, [], manager)
@@ -2192,7 +2193,7 @@ def test_calculate_checkout_subtotal_with_promotion(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -2213,7 +2214,8 @@ def test_calculate_checkout_subtotal_with_promotion(
tax_configuration.country_exceptions.all().delete()
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
checkout_info = fetch_checkout_info(checkout, [], manager)
@@ -2247,7 +2249,7 @@ def test_calculate_checkout_subtotal_for_product_without_tax(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
tax_class_zero_rates,
@@ -2271,7 +2273,8 @@ def test_calculate_checkout_subtotal_for_product_without_tax(
tax_configuration.country_exceptions.all().delete()
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
quantity = 2
@@ -2299,7 +2302,7 @@ def test_calculate_checkout_subtotal_voucher_on_entire_order(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -2323,7 +2326,7 @@ def test_calculate_checkout_subtotal_voucher_on_entire_order(
net = variant.get_price(channel_listing) * checkout_with_item.lines.first().quantity
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.discount_amount = net.amount
checkout_with_item.save()
@@ -2357,7 +2360,7 @@ def test_calculate_checkout_subtotal_voucher_on_shipping(
stock,
monkeypatch,
ship_to_pl_address,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -2376,13 +2379,12 @@ def test_calculate_checkout_subtotal_voucher_on_shipping(
tax_configuration.save(update_fields=["prices_entered_with_tax"])
tax_configuration.country_exceptions.all().delete()
- shipping_method = shipping_zone.shipping_methods.get()
- shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)
-
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.voucher_code = voucher_free_shipping.code
- checkout_with_item.discount_amount = shipping_channel_listings.price.amount
+ checkout_with_item.discount_amount = (
+ checkout_with_item.assigned_delivery.price.amount
+ )
checkout_with_item.save()
checkout_info = fetch_checkout_info(checkout_with_item, [], manager)
@@ -2907,7 +2909,7 @@ def test_calculate_order_line_unit_with_discount(
def test_calculate_checkout_line_unit_price(
charge_taxes,
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -2919,10 +2921,10 @@ def test_calculate_checkout_line_unit_price(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -2958,6 +2960,7 @@ def test_calculate_checkout_line_unit_price_in_JPY(
ship_to_pl_address,
channel_JPY,
plugin_configuration,
+ checkout_delivery,
):
checkout = checkout_JPY_with_item
plugin_configuration(channel=channel_JPY)
@@ -2970,7 +2973,7 @@ def test_calculate_checkout_line_unit_price_in_JPY(
method = shipping_zone_JPY.shipping_methods.get()
checkout.shipping_address = ship_to_pl_address
checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout, method)
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -2992,7 +2995,7 @@ def test_calculate_checkout_line_unit_price_in_JPY(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_with_variant_on_promotion(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -3005,10 +3008,10 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3037,7 +3040,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_order_promotion_charge_taxes(
checkout_with_item_and_order_discount,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -3051,10 +3054,9 @@ def test_calculate_checkout_line_unit_price_order_promotion_charge_taxes(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3091,7 +3093,7 @@ def test_calculate_checkout_line_unit_price_order_promotion_charge_taxes(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_order_promotion_do_not_charge_taxes(
checkout_with_item_and_order_discount,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -3105,10 +3107,9 @@ def test_calculate_checkout_line_unit_price_order_promotion_do_not_charge_taxes(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3143,7 +3144,7 @@ def test_calculate_checkout_line_unit_price_order_promotion_do_not_charge_taxes(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_gift_promotion_line(
checkout_with_item_and_gift_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
):
@@ -3156,10 +3157,9 @@ def test_calculate_checkout_line_unit_price_gift_promotion_line(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3186,7 +3186,7 @@ def test_calculate_checkout_line_unit_price_gift_promotion_line(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_with_voucher(
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -3213,10 +3213,9 @@ def test_calculate_checkout_line_unit_price_with_voucher(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3245,7 +3244,7 @@ def test_calculate_checkout_line_unit_price_with_voucher(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_with_voucher_once_per_order(
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -3273,10 +3272,9 @@ def test_calculate_checkout_line_unit_price_with_voucher_once_per_order(
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3306,7 +3304,7 @@ def test_calculate_checkout_line_unit_price_with_voucher_once_per_order(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_with_variant_on_promotion_and_voucher(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -3333,10 +3331,9 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion_and_vouche
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3365,7 +3362,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion_and_vouche
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_calculate_checkout_line_unit_price_variant_on_promotion_and_voucher_only_once(
checkout_with_item_on_promotion,
- shipping_zone,
+ checkout_delivery,
address,
plugin_configuration,
voucher,
@@ -3393,10 +3390,9 @@ def test_calculate_checkout_line_unit_price_variant_on_promotion_and_voucher_onl
manager = get_plugins_manager(allow_replica=False)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
tax_configuration = checkout.channel.tax_configuration
@@ -3429,7 +3425,7 @@ def test_preprocess_order_creation(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -3444,7 +3440,8 @@ def test_preprocess_order_creation(
checkout = checkout_with_item_on_promotion
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -3461,7 +3458,7 @@ def test_preprocess_order_creation_no_lines_data(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -3475,7 +3472,7 @@ def test_preprocess_order_creation_no_lines_data(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -3490,7 +3487,7 @@ def test_preprocess_order_creation_wrong_data(
checkout_with_item,
monkeypatch,
address,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -3502,7 +3499,7 @@ def test_preprocess_order_creation_wrong_data(
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -3521,6 +3518,7 @@ def test_preprocess_order_creation_shipping_voucher_no_tax_class_on_delivery_met
ship_to_pl_address,
site_settings,
shipping_zone,
+ checkout_delivery,
plugin_configuration,
voucher_free_shipping,
):
@@ -3537,7 +3535,8 @@ def test_preprocess_order_creation_shipping_voucher_no_tax_class_on_delivery_met
shipping_method = shipping_zone.shipping_methods.get()
checkout = checkout_with_item_on_promotion
checkout.shipping_address = ship_to_pl_address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.voucher_code = voucher_free_shipping.code
checkout.discount = shipping_method.channel_listings.first().price
checkout.save()
@@ -3559,7 +3558,7 @@ def test_preprocess_order_creation_address_error_logging(
checkout_with_item,
monkeypatch,
address,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
caplog,
):
@@ -3577,7 +3576,9 @@ def test_preprocess_order_creation_address_error_logging(
address.save(update_fields=["postal_code", "validation_skipped"])
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
+
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -3802,8 +3803,9 @@ def test_get_checkout_line_tax_rate(
checkout_with_item,
address,
plugin_configuration,
- shipping_zone,
+ checkout_delivery,
site_settings,
+ shipping_zone,
):
# given
site_settings.company_address = address
@@ -3817,23 +3819,30 @@ def test_get_checkout_line_tax_rate(
manager = get_plugins_manager(allow_replica=False)
+ shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
- checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_method
+ )
+ checkout_with_item.save(
+ update_fields=[
+ "shipping_address",
+ "assigned_delivery",
+ ]
+ )
lines, _ = fetch_checkout_lines(checkout_with_item)
- shipping_method = checkout_with_item.shipping_method
+
checkout_info = CheckoutInfo(
checkout=checkout_with_item,
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
+ assigned_delivery=checkout_with_item.assigned_delivery,
user=None,
tax_configuration=checkout_with_item.channel.tax_configuration,
discounts=[],
manager=manager,
lines=lines,
- shipping_method=shipping_method,
- shipping_channel_listings=shipping_method.channel_listings.all(),
)
checkout_line_info = lines[0]
@@ -3857,9 +3866,10 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(
checkout_with_item,
address,
plugin_configuration,
- shipping_zone,
+ checkout_delivery,
site_settings,
tax_class_zero_rates,
+ shipping_zone,
):
# given
site_settings.company_address = address
@@ -3878,12 +3888,15 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(
tax_configuration.save(update_fields=["prices_entered_with_tax"])
tax_configuration.country_exceptions.all().delete()
+ shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
- checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_method
+ )
+ checkout_with_item.save(update_fields=["shipping_address", "assigned_delivery"])
lines, _ = fetch_checkout_lines(checkout_with_item)
- shipping_method = checkout_with_item.shipping_method
+
checkout_info = CheckoutInfo(
checkout=checkout_with_item,
shipping_address=address,
@@ -3894,8 +3907,6 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(
discounts=[],
manager=manager,
lines=lines,
- shipping_method=shipping_method,
- shipping_channel_listings=shipping_method.channel_listings.all(),
)
checkout_line_info = lines[0]
product = checkout_line_info.product
@@ -3922,10 +3933,11 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
checkout_with_item,
address,
plugin_configuration,
- shipping_zone,
+ checkout_delivery,
site_settings,
product_with_two_variants,
tax_class_zero_rates,
+ shipping_method,
):
# given
site_settings.company_address = address
@@ -3948,11 +3960,12 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
product_type.save()
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
- checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+ checkout_with_item.assigned_delivery = checkout_delivery(
+ checkout_with_item, shipping_method
+ )
+ checkout_with_item.save(update_fields=["shipping_address", "assigned_delivery"])
lines, _ = fetch_checkout_lines(checkout_with_item)
- shipping_method = checkout_with_item.shipping_method
variant2 = product2.variants.first()
checkout_info = CheckoutInfo(
@@ -3960,12 +3973,11 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
+ assigned_delivery=checkout_with_item.assigned_delivery,
user=None,
tax_configuration=checkout_with_item.channel.tax_configuration,
discounts=[],
manager=manager,
- shipping_method=shipping_method,
- shipping_channel_listings=shipping_method.channel_listings.all(),
lines=lines,
)
add_variant_to_checkout(checkout_info, variant2, 1)
@@ -4026,7 +4038,11 @@ def test_get_checkout_line_tax_rate_checkout_no_shipping_method_default_value_re
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_get_checkout_line_tax_rate_error_in_response(
- monkeypatch, checkout_with_item, address, plugin_configuration, shipping_zone
+ monkeypatch,
+ checkout_with_item,
+ address,
+ plugin_configuration,
+ checkout_delivery,
):
# given
plugin_configuration()
@@ -4039,7 +4055,7 @@ def test_get_checkout_line_tax_rate_error_in_response(
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -4165,7 +4181,11 @@ def test_get_order_line_tax_rate_error_in_response(
@pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_get_checkout_shipping_tax_rate(
- checkout_with_item, address, plugin_configuration, shipping_zone, site_settings
+ checkout_with_item,
+ address,
+ plugin_configuration,
+ checkout_delivery,
+ site_settings,
):
# given
site_settings.company_address = address
@@ -4176,7 +4196,7 @@ def test_get_checkout_shipping_tax_rate(
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -4365,7 +4385,11 @@ def test_get_checkout_shipping_tax_rate_checkout_not_valid_default_value_returne
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_get_checkout_shipping_tax_rate_error_in_response(
- monkeypatch, checkout_with_item, address, plugin_configuration, shipping_zone
+ monkeypatch,
+ checkout_with_item,
+ address,
+ plugin_configuration,
+ checkout_delivery,
):
# given
plugin_configuration()
@@ -4378,7 +4402,7 @@ def test_get_checkout_shipping_tax_rate_error_in_response(
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -4398,7 +4422,11 @@ def test_get_checkout_shipping_tax_rate_error_in_response(
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])
def test_get_checkout_shipping_tax_rate_skip_plugin(
- monkeypatch, checkout_with_item, address, plugin_configuration, shipping_zone
+ monkeypatch,
+ checkout_with_item,
+ address,
+ plugin_configuration,
+ checkout_delivery,
):
# given
plugin_configuration()
@@ -4411,7 +4439,7 @@ def test_get_checkout_shipping_tax_rate_skip_plugin(
manager = get_plugins_manager(allow_replica=False)
checkout_with_item.shipping_address = address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -4742,7 +4770,7 @@ def test_preprocess_order_creation_with_enabled_flat_rates(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -4765,7 +4793,7 @@ def test_preprocess_order_creation_with_enabled_flat_rates(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -4785,7 +4813,7 @@ def test_preprocess_order_creation_with_country_exception_for_flat_rates(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -4813,7 +4841,7 @@ def test_preprocess_order_creation_with_country_exception_for_flat_rates(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -4912,7 +4940,7 @@ def test_plugin_uses_configuration_from_db(
site_settings,
address,
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
settings,
):
settings.PLUGINS = ["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"]
@@ -4927,7 +4955,7 @@ def test_plugin_uses_configuration_from_db(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -5680,7 +5708,7 @@ def test_validate_address_details(
billing_address = checkout_ready_to_complete.billing_address
billing_address = None if billing_address_none else billing_address
address = shipping_address or billing_address
- shipping_method = checkout_ready_to_complete.shipping_method
+ shipping_method = checkout_ready_to_complete.assigned_delivery
shipping_method = None if shipping_method_none else shipping_method
is_valid = _validate_address_details(
shipping_address, is_shipping_required, address, shipping_method
@@ -5945,7 +5973,7 @@ def test_generate_request_data_from_checkout_lines_with_shipping_method(
plugin_configuration,
checkout_with_item,
avatax_config,
- shipping_method,
+ checkout_delivery,
):
# given
settings.PLUGINS = ["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"]
@@ -5962,7 +5990,7 @@ def test_generate_request_data_from_checkout_lines_with_shipping_method(
)
variant.product.tax_class.save()
- checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.collection_point = None
checkout_with_item.save()
@@ -6289,8 +6317,8 @@ def test_calculate_checkout_line_unit_price_validates_checkout(
checkout = checkout_with_item
lines, _ = fetch_checkout_lines(checkout)
- checkout.shipping_method = None
- checkout.save(update_fields=["shipping_method"])
+ checkout.assigned_delivery = None
+ checkout.save(update_fields=["assigned_delivery"])
for line in lines:
line.product_type.is_shipping_required = True
@@ -6318,7 +6346,7 @@ def test_preprocess_order_creation_with_tax_app_id_as_plugin(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -6342,7 +6370,7 @@ def test_preprocess_order_creation_with_tax_app_id_as_plugin(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -6362,7 +6390,7 @@ def test_preprocess_order_creation_with_country_exception_tax_app_id_plugin(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -6391,7 +6419,7 @@ def test_preprocess_order_creation_with_country_exception_tax_app_id_plugin(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -6507,7 +6535,7 @@ def test_get_checkout_tax_data_set_tax_error(
address,
ship_to_pl_address,
site_settings,
- shipping_zone,
+ checkout_delivery,
plugin_configuration,
):
# given
@@ -6532,7 +6560,7 @@ def test_get_checkout_tax_data_set_tax_error(
site_settings.save()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
@@ -6628,6 +6656,7 @@ def test_calculate_checkout_subtotal_with_additional_force_line(
address,
plugin_configuration,
test_response_multiple_lines_with_same_item_code,
+ checkout_delivery,
):
# given
plugin_configuration()
@@ -6651,7 +6680,7 @@ def test_calculate_checkout_subtotal_with_additional_force_line(
tax_configuration.country_exceptions.all().delete()
checkout_with_item.shipping_address = ship_to_pl_address
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
checkout_with_item.save()
checkout_info = fetch_checkout_info(checkout_with_item, [], manager)
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 1fb3fbffc6..49067c2334 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -758,7 +758,7 @@ class BasePlugin:
# Note: This method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from the plugin to core modules.
get_shipping_methods_for_checkout: Callable[
- ["Checkout", Any], list["ShippingMethodData"]
+ ["Checkout", list["ShippingMethodData"], Any], list["ShippingMethodData"]
]
get_supported_currencies: Callable[[Any], Any]
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index bcc9520565..8d4b55d91d 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -2589,6 +2589,7 @@ class PluginsManager(PaymentInterface):
def list_shipping_methods_for_checkout(
self,
checkout: "Checkout",
+ built_in_shipping_methods: list["ShippingMethodData"],
channel_slug: str | None = None,
active_only: bool = True,
) -> list["ShippingMethodData"]:
@@ -2604,7 +2605,9 @@ class PluginsManager(PaymentInterface):
for plugin in shipping_plugins:
shipping_methods.extend(
# https://github.com/python/mypy/issues/9975
- getattr(plugin, "get_shipping_methods_for_checkout")(checkout, None)
+ getattr(plugin, "get_shipping_methods_for_checkout")(
+ checkout, built_in_shipping_methods, None
+ )
)
return list(
filter(
@@ -2613,22 +2616,6 @@ class PluginsManager(PaymentInterface):
)
)
- def get_shipping_method(
- self,
- shipping_method_id: str,
- checkout: Optional["Checkout"] = None,
- channel_slug: str | None = None,
- ):
- if checkout:
- methods = {
- method.id: method
- for method in self.list_shipping_methods_for_checkout(
- checkout=checkout, channel_slug=channel_slug
- )
- }
- return methods.get(shipping_method_id)
- return None
-
def list_external_authentications(self, active_only: bool = True) -> list[dict]:
auth_basic_method = "external_obtain_access_tokens"
plugins = self.get_plugins(active_only=active_only)
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index b21802274c..fa5c28314c 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -372,7 +372,10 @@ class PluginSample(BasePlugin):
return previous_value
def get_shipping_methods_for_checkout(
- self, checkout: "Checkout", previous_value: Any
+ self,
+ checkout: "Checkout",
+ built_in_shipping_methods: list["ShippingMethodData"],
+ previous_value: Any,
) -> list["ShippingMethodData"]:
different_currency = "EUR"
assert checkout.currency != different_currency
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 04c11140b0..75fb50698d 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -1615,11 +1615,13 @@ def test_manager_skips_external_shipping_with_different_currency_than_checkout_c
plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
# when
+
shipping_methods = PluginsManager(
plugins=plugins
).list_shipping_methods_for_checkout(
checkout=checkout_with_item,
channel_slug=checkout_with_item.channel.slug,
+ built_in_shipping_methods=[],
)
# then
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index eee4d73342..f76e6ef746 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -3616,7 +3616,10 @@ class WebhookPlugin(BasePlugin):
)
def get_shipping_methods_for_checkout(
- self, checkout: "Checkout", previous_value: Any
+ self,
+ checkout: "Checkout",
+ built_in_shipping_methods: list["ShippingMethodData"],
+ previous_value: Any,
) -> list["ShippingMethodData"]:
methods = []
event_type = WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
@@ -3631,7 +3634,7 @@ class WebhookPlugin(BasePlugin):
webhook=webhook,
cache_data=cache_data,
allow_replica=self.allow_replica,
- subscribable_object=checkout,
+ subscribable_object=(checkout, built_in_shipping_methods),
request_timeout=WEBHOOK_SYNC_TIMEOUT,
cache_timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,
requestor=self.requestor,
@@ -3689,7 +3692,7 @@ class WebhookPlugin(BasePlugin):
event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
previous_value=previous_value,
payload_fun=payload_fun,
- subscribable_object=order,
+ subscribable_object=(order, available_shipping_methods),
allow_replica=self.allow_replica,
requestor=self.requestor,
)
@@ -3712,7 +3715,7 @@ class WebhookPlugin(BasePlugin):
event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
previous_value=previous_value,
payload_fun=payload_function,
- subscribable_object=checkout,
+ subscribable_object=(checkout, available_shipping_methods),
allow_replica=self.allow_replica,
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
diff --git a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
index a062e39fad..61b9c2598c 100644
--- a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
+++ b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
@@ -27,7 +27,11 @@ def test_get_shipping_methods_for_checkout_webhook_response_none(
mocked_webhook.return_value = None
# when
- response = plugin.get_shipping_methods_for_checkout(checkout, None)
+ response = plugin.get_shipping_methods_for_checkout(
+ checkout,
+ [],
+ None,
+ )
# then
assert not response
@@ -54,7 +58,7 @@ def test_get_shipping_methods_for_checkout_set_cache(
plugin = webhook_plugin()
# when
- plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, [], None)
# then
assert mocked_webhook.called
@@ -86,7 +90,7 @@ def test_get_shipping_methods_no_webhook_response_sets_short_term_cache(
plugin = webhook_plugin()
# when
- plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, [], None)
# then
assert mocked_webhook.called
@@ -118,7 +122,7 @@ def test_get_shipping_methods_for_checkout_use_cache(
plugin = webhook_plugin()
# when
- plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, [], None)
# then
assert not mocked_webhook.called
@@ -139,7 +143,7 @@ def test_get_shipping_methods_for_checkout_use_cache_for_empty_list(
plugin = webhook_plugin()
# when
- plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, [], None)
# then
assert not mocked_webhook.called
@@ -191,7 +195,7 @@ def test_checkout_change_invalidates_cache_key(
WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
shipping_app.id,
)
- plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, [], None)
# then
assert cache_key != new_cache_key
@@ -248,7 +252,7 @@ def test_ignore_selected_fields_on_generating_cache_key(
WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
shipping_app.id,
)
- plugin.get_shipping_methods_for_checkout(checkout_with_item, None)
+ plugin.get_shipping_methods_for_checkout(checkout_with_item, [], None)
# then
assert cache_key == new_cache_key
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index ec53c3b204..fe87718e1e 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -10,6 +10,7 @@ from ....graphql.core.utils import to_global_id_or_none
from ....graphql.tests.utils import get_graphql_content
from ....graphql.webhook.utils import get_subscription_query_hash
from ....order import OrderStatus
+from ....shipping.models import ShippingMethod
from ....webhook.const import CACHE_EXCLUDED_SHIPPING_TIME
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
@@ -123,7 +124,7 @@ def test_excluded_shipping_methods_for_order(
payload,
shipping_webhook,
False,
- subscribable_object=order_with_lines,
+ subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -215,7 +216,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
payload,
shipping_webhook,
False,
- subscribable_object=order_with_lines,
+ subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -226,7 +227,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
payload,
second_shipping_webhook,
False,
- subscribable_object=order_with_lines,
+ subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -347,7 +348,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
payload,
first_webhook,
False,
- subscribable_object=order_with_lines,
+ subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -358,7 +359,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
payload,
second_webhook,
False,
- subscribable_object=order_with_lines,
+ subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -635,17 +636,20 @@ def test_order_available_shipping_methods(
@mock.patch(
"saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_checkout"
)
-def test_checkout_shipping_methods(
+def test_checkout_deliveries(
mocked_webhook,
staff_api_client,
checkout_ready_to_complete,
permission_manage_checkouts,
settings,
+ shipping_method_weight_based,
):
# given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
webhook_reason = "spanish-inquisition"
- excluded_shipping_method_id = checkout_ready_to_complete.shipping_method.id
+ excluded_shipping_method_id = (
+ checkout_ready_to_complete.assigned_delivery.shipping_method_id
+ )
mocked_webhook.return_value = [
ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
]
@@ -682,12 +686,15 @@ def test_checkout_available_shipping_methods(
checkout_ready_to_complete,
permission_manage_checkouts,
settings,
+ shipping_method_weight_based,
):
# given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
webhook_reason = "spanish-inquisition"
- excluded_shipping_method_id = checkout_ready_to_complete.shipping_method.id
+ excluded_shipping_method_id = (
+ checkout_ready_to_complete.assigned_delivery.shipping_method_id
+ )
mocked_webhook.return_value = [
ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
]
@@ -708,7 +715,7 @@ def test_checkout_available_shipping_methods(
@mock.patch(
"saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
)
-def test_checkout_shipping_methods_webhook_called_once(
+def test_checkout_deliveries_webhook_called_once(
mocked_webhook,
staff_api_client,
checkout_ready_to_complete,
@@ -725,8 +732,10 @@ def test_checkout_shipping_methods_webhook_called_once(
content = get_graphql_content(response)
checkout_data = content["data"]["checkout"]
# then
- assert len(checkout_data["availableShippingMethods"]) == 2
- assert len(checkout_data["shippingMethods"]) == 2
+ expected_count = ShippingMethod.objects.count()
+ assert len(checkout_data["availableShippingMethods"]) == expected_count
+ assert len(checkout_data["shippingMethods"]) == expected_count
+ assert mocked_webhook.called
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -801,7 +810,7 @@ def test_excluded_shipping_methods_for_checkout_webhook_without_pregenerated_pay
payload,
shipping_webhook,
False,
- subscribable_object=checkout_with_items,
+ subscribable_object=(checkout_with_items, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -889,7 +898,7 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription_base_p
payload,
shipping_webhook,
False,
- subscribable_object=checkout_with_items,
+ subscribable_object=(checkout_with_items, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -1031,7 +1040,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
payload,
shipping_webhook,
False,
- subscribable_object=checkout_with_items,
+ subscribable_object=(checkout_with_items, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -1042,7 +1051,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
payload,
second_shipping_webhook,
False,
- subscribable_object=checkout_with_items,
+ subscribable_object=(checkout_with_items, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -1163,7 +1172,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
payload,
first_webhook,
False,
- subscribable_object=checkout_with_items,
+ subscribable_object=(checkout_with_items, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
@@ -1174,7 +1183,7 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_ch
payload,
second_webhook,
False,
- subscribable_object=checkout_with_items,
+ subscribable_object=(checkout_with_items, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
requestor=None,
diff --git a/saleor/settings.py b/saleor/settings.py
index 79d83ffa75..f4aff80cef 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -949,6 +949,9 @@ JWT_TTL_REQUEST_EMAIL_CHANGE = datetime.timedelta(
CHECKOUT_PRICES_TTL = datetime.timedelta(
seconds=parse(os.environ.get("CHECKOUT_PRICES_TTL", "1 hour"))
)
+CHECKOUT_DELIVERY_OPTIONS_TTL = datetime.timedelta(
+ seconds=parse(os.environ.get("CHECKOUT_DELIVERY_OPTIONS_TTL", "24 hours"))
+)
CHECKOUT_TTL_BEFORE_RELEASING_FUNDS = datetime.timedelta(
seconds=parse(os.environ.get("CHECKOUT_TTL_BEFORE_RELEASING_FUNDS", "6 hours"))
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 9e938d3b23..c8e4e9459b 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -159,7 +159,6 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):
# instances.
if product_ids:
qs = self.exclude_shipping_methods_for_excluded_products(qs, product_ids)
-
price_based_methods = _applicable_price_based_methods(
price, qs, channel_id, database_connection_name=self.db
)
@@ -211,7 +210,6 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):
country_code=country_code,
product_ids=instance_product_ids,
).prefetch_related("postal_code_rules")
-
return filter_shipping_methods_by_postal_code_rules(
applicable_methods, shipping_address
)
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index 380854ac25..2b20b70b20 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -2,13 +2,15 @@ import logging
from typing import TYPE_CHECKING, Optional
from django_countries import countries
+from prices import Money
+from ..checkout.models import Checkout, CheckoutDelivery
from ..core.db.connection import allow_writer
from ..plugins.base_plugin import ExcludedShippingMethod
+from ..tax.models import TaxClass
from .interface import ShippingMethodData
if TYPE_CHECKING:
- from ..tax.models import TaxClass
from .models import ShippingMethod, ShippingMethodChannelListing
@@ -45,7 +47,6 @@ def convert_to_shipping_method_data(
# TODO: load tax_class with data loader and pass as an argument
with allow_writer():
tax_class = shipping_method.tax_class
-
return ShippingMethodData(
id=str(shipping_method.id),
name=shipping_method.name,
@@ -64,6 +65,68 @@ def convert_to_shipping_method_data(
)
+def convert_checkout_delivery_to_shipping_method_data(
+ checkout_delivery: CheckoutDelivery,
+) -> "ShippingMethodData":
+ return ShippingMethodData(
+ id=checkout_delivery.shipping_method_id,
+ name=checkout_delivery.name,
+ description=checkout_delivery.description,
+ maximum_delivery_days=checkout_delivery.maximum_delivery_days,
+ minimum_delivery_days=checkout_delivery.minimum_delivery_days,
+ metadata=checkout_delivery.metadata,
+ private_metadata=checkout_delivery.private_metadata,
+ price=Money(checkout_delivery.price_amount, checkout_delivery.currency),
+ active=all([checkout_delivery.active, checkout_delivery.is_valid]),
+ message=checkout_delivery.message or "",
+ tax_class=TaxClass(
+ id=checkout_delivery.tax_class_id,
+ name=checkout_delivery.tax_class_name or "",
+ metadata=checkout_delivery.tax_class_metadata,
+ private_metadata=checkout_delivery.tax_class_private_metadata,
+ ),
+ )
+
+
+def convert_shipping_method_data_to_checkout_delivery(
+ shipping_method_data: ShippingMethodData, checkout: Checkout
+) -> CheckoutDelivery:
+ tax_class_details = {}
+ if shipping_method_data.tax_class:
+ tax_class_details = {
+ "tax_class_id": shipping_method_data.tax_class.id,
+ "tax_class_name": shipping_method_data.tax_class.name,
+ "tax_class_metadata": shipping_method_data.tax_class.metadata,
+ "tax_class_private_metadata": shipping_method_data.tax_class.private_metadata,
+ }
+ shipping_method_is_external = shipping_method_data.is_external
+ built_in_shipping_method_id = (
+ int(shipping_method_data.id) if not shipping_method_is_external else None
+ )
+ external_shipping_method_id = (
+ shipping_method_data.id if shipping_method_is_external else None
+ )
+
+ return CheckoutDelivery(
+ checkout=checkout,
+ external_shipping_method_id=external_shipping_method_id,
+ built_in_shipping_method_id=built_in_shipping_method_id,
+ name=shipping_method_data.name or "",
+ description=shipping_method_data.description,
+ price_amount=shipping_method_data.price.amount,
+ currency=shipping_method_data.price.currency,
+ maximum_delivery_days=shipping_method_data.maximum_delivery_days,
+ minimum_delivery_days=shipping_method_data.minimum_delivery_days,
+ metadata=shipping_method_data.metadata,
+ private_metadata=shipping_method_data.private_metadata,
+ active=shipping_method_data.active,
+ message=shipping_method_data.message,
+ is_valid=True,
+ is_external=shipping_method_is_external,
+ **tax_class_details,
+ )
+
+
def initialize_shipping_method_active_status(
shipping_methods: list["ShippingMethodData"],
excluded_methods: list["ExcludedShippingMethod"],
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index 2f4f4c8244..08e9442956 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -111,7 +111,7 @@ def test_calculate_checkout_total_with_gift_cards(
def test_calculate_checkout_total(
checkout_with_item,
address,
- shipping_zone,
+ checkout_delivery,
voucher,
expected_net,
expected_gross,
@@ -126,7 +126,9 @@ def test_calculate_checkout_total(
checkout.shipping_address = address
voucher_amount = Money(voucher_amount, "USD")
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
+
checkout.voucher_code = voucher.code
checkout.discount = voucher_amount
checkout.save()
@@ -170,7 +172,7 @@ def test_calculate_checkout_total(
def test_calculate_checkout_total_with_multiple_tax_rates(
checkout_with_items,
address,
- shipping_zone,
+ checkout_delivery,
tax_classes,
expected_net,
expected_gross,
@@ -182,7 +184,8 @@ def test_calculate_checkout_total_with_multiple_tax_rates(
_enable_flat_rates(checkout, prices_entered_with_tax, use_weighted_tax_for_shipping)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
first_line = checkout.lines.first()
@@ -226,7 +229,7 @@ def test_calculate_checkout_total_with_multiple_tax_rates(
def test_calculate_checkout_shipping_with_not_weighted_taxes(
checkout_with_items,
address,
- shipping_zone,
+ checkout_delivery,
tax_classes,
expected_net,
expected_gross,
@@ -239,7 +242,8 @@ def test_calculate_checkout_shipping_with_not_weighted_taxes(
)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
first_line = checkout.lines.first()
@@ -284,7 +288,7 @@ def test_calculate_checkout_shipping_with_not_weighted_taxes(
def test_calculate_checkout_shipping_with_weighted_taxes(
checkout_with_items,
address,
- shipping_zone,
+ checkout_delivery,
tax_classes,
expected_net,
expected_gross,
@@ -297,7 +301,8 @@ def test_calculate_checkout_shipping_with_weighted_taxes(
)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
first_line = checkout.lines.first()
@@ -347,7 +352,7 @@ def test_calculate_checkout_shipping_with_weighted_taxes(
def test_calculate_checkout_total_with_sale(
checkout_with_item_on_promotion,
address,
- shipping_zone,
+ checkout_delivery,
voucher,
expected_net,
expected_gross,
@@ -361,7 +366,8 @@ def test_calculate_checkout_total_with_sale(
checkout.shipping_address = address
voucher_amount = Money(voucher_amount, "USD")
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.voucher_code = voucher.code
checkout.discount = voucher_amount
checkout.save()
@@ -391,7 +397,7 @@ def test_calculate_checkout_total_with_sale(
def test_calculate_checkout_total_no_tax_rates(
checkout_with_item,
address,
- shipping_zone,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
@@ -399,8 +405,8 @@ def test_calculate_checkout_total_no_tax_rates(
_enable_flat_rates(checkout, prices_entered_with_tax)
checkout.shipping_address = address
- shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
TaxClassCountryRate.objects.all().delete()
@@ -423,7 +429,7 @@ def test_calculate_checkout_total_no_tax_rates(
def test_calculate_checkout_total_default_tax_rate_for_country(
checkout_with_item,
address,
- shipping_zone,
+ checkout_delivery,
):
# given
checkout = checkout_with_item
@@ -431,8 +437,8 @@ def test_calculate_checkout_total_default_tax_rate_for_country(
_enable_flat_rates(checkout, prices_entered_with_tax)
checkout.shipping_address = address
- shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
TaxClassCountryRate.objects.all().delete()
@@ -463,7 +469,7 @@ def test_calculate_checkout_total_default_tax_rate_for_country(
def test_calculate_checkout_total_with_shipping_voucher(
checkout_with_item,
address,
- shipping_zone,
+ checkout_delivery,
voucher_shipping_type,
expected_net,
expected_gross,
@@ -479,7 +485,8 @@ def test_calculate_checkout_total_with_shipping_voucher(
checkout.save()
voucher_amount = Money(voucher_amount, "USD")
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.voucher_code = voucher_shipping_type.code
checkout.discount = voucher_amount
checkout.save()
@@ -512,7 +519,7 @@ def test_calculate_checkout_total_with_shipping_voucher(
def test_calculate_checkout_total_with_shipping_voucher_and_sale(
checkout_with_item_on_promotion,
address,
- shipping_zone,
+ checkout_delivery,
voucher_shipping_type,
expected_net,
expected_gross,
@@ -528,7 +535,8 @@ def test_calculate_checkout_total_with_shipping_voucher_and_sale(
checkout.save()
voucher_amount = Money(voucher_amount, "USD")
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.voucher_code = voucher_shipping_type.code
checkout.discount = voucher_amount
checkout.save()
@@ -564,7 +572,7 @@ def test_calculate_checkout_total_with_shipping_voucher_and_sale(
def test_calculate_checkout_subtotal(
checkout_with_item,
address,
- shipping_zone,
+ checkout_delivery,
expected_net,
expected_gross,
prices_entered_with_tax,
@@ -579,7 +587,8 @@ def test_calculate_checkout_subtotal(
product.tax_class.country_rates.update_or_create(country=address.country, rate=23)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
manager = get_plugins_manager(allow_replica=False)
@@ -604,7 +613,7 @@ def test_calculate_checkout_subtotal(
def test_calculate_checkout_subtotal_with_promotion_prices_entered_with_tax(
checkout_with_item_on_promotion,
address,
- shipping_zone,
+ checkout_delivery,
stock,
):
# given
@@ -617,7 +626,8 @@ def test_calculate_checkout_subtotal_with_promotion_prices_entered_with_tax(
product.tax_class.country_rates.update_or_create(country=address.country, rate=23)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
manager = get_plugins_manager(allow_replica=False)
@@ -648,7 +658,7 @@ def test_calculate_checkout_subtotal_with_promotion_prices_entered_with_tax(
def test_calculate_checkout_subtotal_with_promotion_prices_not_entered_with_tax(
checkout_with_item_on_promotion,
address,
- shipping_zone,
+ checkout_delivery,
stock,
):
# given
@@ -661,7 +671,8 @@ def test_calculate_checkout_subtotal_with_promotion_prices_not_entered_with_tax(
product.tax_class.country_rates.update_or_create(country=address.country, rate=23)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
manager = get_plugins_manager(allow_replica=False)
@@ -692,7 +703,7 @@ def test_calculate_checkout_subtotal_with_promotion_prices_not_entered_with_tax(
def test_calculate_checkout_subtotal_with_order_promotion(
checkout_with_item_and_order_discount,
address,
- shipping_zone,
+ checkout_delivery,
stock,
):
# given
@@ -702,7 +713,8 @@ def test_calculate_checkout_subtotal_with_order_promotion(
discount_amount = checkout.discounts.first().amount_value
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
manager = get_plugins_manager(allow_replica=False)
@@ -733,7 +745,7 @@ def test_calculate_checkout_subtotal_with_order_promotion(
def test_calculate_checkout_subtotal_with_gift_promotion(
checkout_with_item_and_gift_promotion,
address,
- shipping_zone,
+ checkout_delivery,
stock,
):
# given
@@ -742,7 +754,8 @@ def test_calculate_checkout_subtotal_with_gift_promotion(
_enable_flat_rates(checkout, prices_entered_with_tax)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
manager = get_plugins_manager(allow_replica=False)
@@ -771,7 +784,7 @@ def test_calculate_checkout_subtotal_with_gift_promotion(
)
-def test_calculate_checkout_line_total(checkout_with_item, shipping_zone, address):
+def test_calculate_checkout_line_total(checkout_with_item, checkout_delivery, address):
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_item
@@ -782,10 +795,9 @@ def test_calculate_checkout_line_total(checkout_with_item, shipping_zone, addres
line = checkout.lines.first()
assert line.quantity > 1
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
variant = line.variant
@@ -807,7 +819,7 @@ def test_calculate_checkout_line_total(checkout_with_item, shipping_zone, addres
def test_calculate_checkout_line_total_voucher_on_entire_order(
- checkout_with_item, shipping_zone, address, voucher
+ checkout_with_item, checkout_delivery, address, voucher
):
# given
checkout = checkout_with_item
@@ -820,10 +832,9 @@ def test_calculate_checkout_line_total_voucher_on_entire_order(
line = checkout.lines.first()
assert line.quantity > 1
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
discount_amount = Decimal(5)
checkout.discount_amount = discount_amount
checkout.voucher_code = voucher.code
@@ -857,7 +868,7 @@ def test_calculate_checkout_line_total_voucher_on_entire_order(
def test_calculate_checkout_line_total_with_voucher_one_line(
- checkout_with_item, shipping_zone, address, voucher
+ checkout_with_item, checkout_delivery, address, voucher
):
# given
checkout = checkout_with_item
@@ -868,10 +879,9 @@ def test_calculate_checkout_line_total_with_voucher_one_line(
prices_entered_with_tax = True
_enable_flat_rates(checkout, prices_entered_with_tax)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
discount_amount = Decimal(5)
checkout.discount_amount = discount_amount
checkout.voucher_code = voucher.code
@@ -910,7 +920,7 @@ def test_calculate_checkout_line_total_with_voucher_one_line(
def test_calculate_checkout_line_total_with_voucher_multiple_lines(
- checkout_with_item, shipping_zone, address, voucher, product_list
+ checkout_with_item, checkout_delivery, address, voucher, product_list
):
# given
manager = get_plugins_manager(allow_replica=False)
@@ -928,10 +938,9 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines(
add_variant_to_checkout(checkout_info, variant_1, qty_1)
add_variant_to_checkout(checkout_info, variant_2, qty_2)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
discount_amount = Decimal(5)
checkout.discount_amount = discount_amount
checkout.voucher_code = voucher.code
@@ -980,7 +989,7 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines(
def test_calculate_checkout_line_total_with_voucher_multiple_lines_last_line(
- checkout_with_item, shipping_zone, address, voucher, product_list
+ checkout_with_item, checkout_delivery, address, voucher, product_list
):
# given
manager = get_plugins_manager(allow_replica=False)
@@ -1000,10 +1009,9 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines_last_line(
add_variant_to_checkout(checkout_info, variant_1, qty_1)
add_variant_to_checkout(checkout_info, variant_2, qty_2)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
discount_amount = Decimal(5)
checkout.discount_amount = discount_amount
checkout.voucher_code = voucher.code
@@ -1057,7 +1065,7 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines_last_line(
def test_calculate_checkout_line_total_with_voucher_for_multiple_lines(
- checkout, shipping_zone, address, voucher, product_list
+ checkout, checkout_delivery, address, voucher, product_list
):
# given
manager = get_plugins_manager(allow_replica=False)
@@ -1097,10 +1105,9 @@ def test_calculate_checkout_line_total_with_voucher_for_multiple_lines(
add_variant_to_checkout(checkout_info, variant_2, qty)
add_variant_to_checkout(checkout_info, variant_3, qty)
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
discount_amount = Decimal(3)
checkout.discount_amount = discount_amount
checkout.voucher_code = voucher.code
@@ -1158,7 +1165,7 @@ def test_calculate_checkout_line_total_with_voucher_for_multiple_lines(
def test_calculate_checkout_line_total_with_shipping_voucher(
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
address,
voucher_shipping_type,
):
@@ -1172,10 +1179,9 @@ def test_calculate_checkout_line_total_with_shipping_voucher(
line = checkout.lines.first()
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.discount_amount = Decimal(5)
checkout.voucher_code = voucher_shipping_type.code
checkout.save()
@@ -1211,7 +1217,7 @@ def test_calculate_checkout_line_total_with_shipping_voucher(
def test_calculate_checkout_line_total_discount_from_order_promotion(
- checkout_with_item_and_order_discount, shipping_zone, address
+ checkout_with_item_and_order_discount, checkout_delivery, address
):
# given
manager = get_plugins_manager(allow_replica=False)
@@ -1224,10 +1230,8 @@ def test_calculate_checkout_line_total_discount_from_order_promotion(
line = checkout.lines.first()
assert line.quantity > 1
- method = shipping_zone.shipping_methods.get()
- checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
variant = line.variant
@@ -1259,7 +1263,7 @@ def test_calculate_checkout_line_total_discount_from_order_promotion(
def test_calculate_checkout_line_total_discount_for_gift_line(
- checkout_with_item_and_gift_promotion, shipping_zone, address
+ checkout_with_item_and_gift_promotion, checkout_delivery, address
):
# given
manager = get_plugins_manager(allow_replica=False)
@@ -1272,10 +1276,9 @@ def test_calculate_checkout_line_total_discount_for_gift_line(
line = checkout.lines.get(is_gift=True)
assert line.quantity == 1
- method = shipping_zone.shipping_methods.get()
checkout.shipping_address = address
- checkout.shipping_method_name = method.name
- checkout.shipping_method = method
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
checkout.save()
variant = line.variant
@@ -1297,9 +1300,7 @@ def test_calculate_checkout_line_total_discount_for_gift_line(
def test_calculate_checkout_shipping(
- checkout_with_item,
- shipping_zone,
- address,
+ checkout_with_item, checkout_delivery, address, shipping_method
):
# given
checkout = checkout_with_item
@@ -1309,8 +1310,10 @@ def test_calculate_checkout_shipping(
_enable_flat_rates(checkout, prices_entered_with_tax)
checkout.shipping_address = address
- checkout.shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method.tax_class.country_rates.update_or_create(
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ checkout.shipping_method_name = checkout.assigned_delivery.name
+
+ shipping_method.tax_class.country_rates.update_or_create(
country=address.country, rate=rate
)
checkout.save()
@@ -1362,7 +1365,8 @@ def test_calculate_checkout_shipping_no_shipping_price(
def test_calculate_checkout_shipping_voucher_on_shipping(
checkout_with_item,
- shipping_zone,
+ checkout_delivery,
+ shipping_method,
address,
voucher_shipping_type,
):
@@ -1374,9 +1378,9 @@ def test_calculate_checkout_shipping_voucher_on_shipping(
_enable_flat_rates(checkout, prices_entered_with_tax)
checkout.shipping_address = address
- shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method = shipping_method
- checkout.shipping_method.tax_class.country_rates.update_or_create(
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+
+ shipping_method.tax_class.country_rates.update_or_create(
country=address.country, rate=rate
)
checkout.voucher_code = voucher_shipping_type.code
@@ -1443,10 +1447,7 @@ def test_calculate_checkout_shipping_free_shipping_voucher(
def test_calculate_checkout_shipping_free_entire_order_voucher(
- checkout_with_item,
- shipping_zone,
- address,
- voucher,
+ checkout_with_item, checkout_delivery, address, voucher, shipping_method
):
# given
checkout = checkout_with_item
@@ -1456,9 +1457,8 @@ def test_calculate_checkout_shipping_free_entire_order_voucher(
_enable_flat_rates(checkout, prices_entered_with_tax)
checkout.shipping_address = address
- shipping_method = shipping_zone.shipping_methods.get()
- checkout.shipping_method = shipping_method
- checkout.shipping_method.tax_class.country_rates.update_or_create(
+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)
+ shipping_method.tax_class.country_rates.update_or_create(
country=address.country, rate=rate
)
checkout.voucher_code = voucher.code
@@ -1477,14 +1477,10 @@ def test_calculate_checkout_shipping_free_entire_order_voucher(
# then
shipping_price = quantize_price(shipping_price, shipping_price.currency)
- assert (
- shipping_price
- == shipping_price
- == TaxedMoney(
- net=quantize_price(
- shipping_channel_listings.price / Decimal(1.23),
- checkout.currency,
- ),
- gross=shipping_channel_listings.price,
- )
+ assert shipping_price == TaxedMoney(
+ net=quantize_price(
+ shipping_channel_listings.price / Decimal(1.23),
+ checkout.currency,
+ ),
+ gross=shipping_channel_listings.price,
)
diff --git a/saleor/tax/utils.py b/saleor/tax/utils.py
index fd855e69ad..6e03444ac9 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -284,9 +284,9 @@ def get_shipping_tax_rate_for_checkout(
[line_info.line for line_info in lines], default_tax_rate
)
shipping_tax_rates: Iterable[TaxClassCountryRate] = []
- if shipping_method := checkout_info.shipping_method:
+ if assigned_delivery := checkout_info.assigned_delivery:
# external shipping methods do not have a way to provide tax-class
- tax_class_id = shipping_method.tax_class_id
+ tax_class_id = assigned_delivery.tax_class_id
if tax_class_id:
shipping_tax_rates = TaxClassCountryRate.objects.using(
database_connection_name
diff --git a/saleor/tests/e2e/checkout/test_checkout_with_shipping_method_with_min_order_value.py b/saleor/tests/e2e/checkout/test_checkout_with_shipping_method_with_min_order_value.py
index d3c07432db..bffbec7973 100644
--- a/saleor/tests/e2e/checkout/test_checkout_with_shipping_method_with_min_order_value.py
+++ b/saleor/tests/e2e/checkout/test_checkout_with_shipping_method_with_min_order_value.py
@@ -96,16 +96,16 @@ def test_checkout_with_shipping_method_with_min_order_value_CORE_0501(
checkout_id = checkout_data["id"]
assert checkout_data["isShippingRequired"] is True
- checkout_shipping_method = checkout_data["shippingMethods"][0]["id"]
- assert checkout_shipping_method == shipping_method_id
+ checkout_delivery = checkout_data["shippingMethods"][0]["id"]
+ assert checkout_delivery == shipping_method_id
# Step 2 - Set DeliveryMethod for the checkout with the first product variant
checkout_data = checkout_delivery_method_update(
e2e_not_logged_api_client,
checkout_id,
- checkout_shipping_method,
+ checkout_delivery,
)
- assert checkout_data["deliveryMethod"]["id"] == checkout_shipping_method
+ assert checkout_data["deliveryMethod"]["id"] == checkout_delivery
# Step 3 - Create checkout with the second product variant
lines = [
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 1a8f6ddd18..453a0205f1 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -37,6 +37,7 @@ from ..payment.models import Payment, TransactionItem
from ..product import ProductMediaTypes
from ..product.models import Collection, Product, ProductMedia, ProductVariant
from ..shipping.interface import ShippingMethodData
+from ..shipping.models import ShippingMethod
from ..tax.models import TaxClassCountryRate
from ..tax.utils import get_charge_taxes_for_order
from ..thumbnail.models import Thumbnail
@@ -329,7 +330,7 @@ def generate_order_payload(
"number": order.number,
"user_email": order.get_customer_email(),
"created": order.created_at,
- "original": graphene.Node.to_global_id("Order", order.original_id),
+ "original": graphene.Node.to_global_id("Order", order.shipping_method_id),
"lines": json.loads(generate_order_lines_payload(lines)),
"fulfillments": json.loads(fulfillments_data),
"collection_point": (
@@ -555,6 +556,11 @@ def generate_checkout_payload(
checkout.shipping_address.country.code, checkout.channel_id
).first()
+ shipping_method = None
+ if checkout.assigned_delivery and not checkout.assigned_delivery.is_external:
+ shipping_method = ShippingMethod.objects.filter(
+ id=checkout.assigned_delivery.shipping_method_id
+ ).first()
checkout_data = serializer.serialize(
[checkout],
fields=checkout_fields,
@@ -572,7 +578,7 @@ def generate_checkout_payload(
extra_dict_data={
# Casting to list to make it json-serializable
"shipping_method": _generate_shipping_method_payload(
- checkout.shipping_method, checkout.channel
+ shipping_method, checkout.channel
),
"lines": list(lines_dict_data),
"collection_point": (
@@ -1332,10 +1338,10 @@ def generate_checkout_payload_for_tax_calculation(
)
# Prepare shipping data
- shipping_method = checkout.shipping_method
+ assigned_delivery = checkout.assigned_delivery
shipping_method_name = None
- if shipping_method:
- shipping_method_name = shipping_method.name
+ if assigned_delivery:
+ shipping_method_name = assigned_delivery.name
shipping_method_amount = quantize_price(
base_calculations.base_checkout_delivery_price(checkout_info, lines).amount,
checkout.currency,
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index f926264ec1..7e1bab1631 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -11,8 +11,15 @@ from ....channel.models import Channel
from ....giftcard.models import GiftCard
from ....graphql.webhook.subscription_query import SubscriptionQuery
from ....menu.models import Menu, MenuItem
+from ....order.utils import get_all_shipping_methods_for_order
from ....product.models import Category
-from ....shipping.models import ShippingMethod, ShippingZone
+from ....shipping.interface import ShippingMethodData
+from ....shipping.models import (
+ ShippingMethod,
+ ShippingMethodChannelListing,
+ ShippingZone,
+)
+from ....shipping.utils import convert_to_shipping_method_data
from ....site.models import SiteSettings
from ...event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...transport.asynchronous.transport import (
@@ -2648,16 +2655,25 @@ def test_shipping_list_methods_for_checkout(
webhooks = [subscription_shipping_list_methods_for_checkout_webhook]
event_type = WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- all_shipping_methods = ShippingMethod.objects.all()
+
+ internal_methods: list[ShippingMethodData] = []
+ for method in ShippingMethod.objects.all():
+ shipping_method_data = convert_to_shipping_method_data(
+ method, method.channel_listings.get(channel=checkout.channel)
+ )
+ internal_methods.append(shipping_method_data)
+
# when
- deliveries = create_deliveries_for_subscriptions(event_type, checkout, webhooks)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, (checkout, internal_methods), webhooks
+ )
# then
shipping_methods = [
{
- "id": graphene.Node.to_global_id("ShippingMethod", sm.pk),
+ "id": graphene.Node.to_global_id("ShippingMethod", sm.id),
"name": sm.name,
}
- for sm in all_shipping_methods
+ for sm in internal_methods
]
payload = json.loads(deliveries[0].payload.get_payload())
@@ -2681,16 +2697,26 @@ def test_checkout_filter_shipping_methods(
webhooks = [subscription_checkout_filter_shipping_methods_webhook]
event_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- all_shipping_methods = ShippingMethod.objects.all()
+
+ internal_methods: list[ShippingMethodData] = []
+ for method in ShippingMethod.objects.all():
+ shipping_method_data = convert_to_shipping_method_data(
+ method, method.channel_listings.get(channel=checkout.channel)
+ )
+ internal_methods.append(shipping_method_data)
+
# when
- deliveries = create_deliveries_for_subscriptions(event_type, checkout, webhooks)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, (checkout, internal_methods), webhooks
+ )
+
# then
shipping_methods = [
{
- "id": graphene.Node.to_global_id("ShippingMethod", sm.pk),
+ "id": graphene.Node.to_global_id("ShippingMethod", sm.id),
"name": sm.name,
}
- for sm in all_shipping_methods
+ for sm in internal_methods
]
payload = json.loads(deliveries[0].payload.get_payload())
@@ -2714,7 +2740,9 @@ def test_checkout_filter_shipping_methods_no_methods_in_channel(
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
# when
- deliveries = create_deliveries_for_subscriptions(event_type, checkout, webhooks)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, (checkout, []), webhooks
+ )
# then
expected_payload = {"checkout": {"id": checkout_id}, "shippingMethods": []}
@@ -2735,7 +2763,7 @@ def test_checkout_filter_shipping_methods_with_circular_call_for_shipping_method
# when
deliveries = create_deliveries_for_subscriptions(
- event_type, checkout_ready_to_complete, webhooks
+ event_type, (checkout_ready_to_complete, []), webhooks
)
# then
@@ -2761,7 +2789,7 @@ def test_checkout_filter_shipping_methods_with_available_shipping_methods_field(
# when
deliveries = create_deliveries_for_subscriptions(
- event_type, checkout_ready_to_complete, webhooks
+ event_type, (checkout_ready_to_complete, []), webhooks
)
# then
@@ -2787,7 +2815,7 @@ def test_checkout_filter_shipping_methods_with_circular_call_for_available_gatew
# when
deliveries = create_deliveries_for_subscriptions(
- event_type, checkout_ready_to_complete, webhooks
+ event_type, (checkout_ready_to_complete, []), webhooks
)
# then
@@ -2835,14 +2863,19 @@ def test_order_filter_shipping_methods(
webhooks = [subscription_order_filter_shipping_methods_webhook]
event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
order_id = graphene.Node.to_global_id("Order", order.pk)
- all_shipping_methods = ShippingMethod.objects.all()
+ all_shipping_methods = get_all_shipping_methods_for_order(
+ order, ShippingMethodChannelListing.objects.all()
+ )
# when
- deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, (order, all_shipping_methods), webhooks
+ )
+
# then
shipping_methods = [
{
- "id": graphene.Node.to_global_id("ShippingMethod", sm.pk),
+ "id": graphene.Node.to_global_id("ShippingMethod", sm.id),
"name": sm.name,
}
for sm in all_shipping_methods
@@ -2869,7 +2902,7 @@ def test_order_filter_shipping_methods_no_methods_in_channel(
order_id = graphene.Node.to_global_id("Order", order.pk)
# when
- deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ deliveries = create_deliveries_for_subscriptions(event_type, (order, []), webhooks)
# then
expected_payload = {"order": {"id": order_id}, "shippingMethods": []}
@@ -2891,7 +2924,7 @@ def test_order_filter_shipping_methods_with_circular_call_for_available_methods(
order = order_line_with_one_allocation.order
# when
- deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ deliveries = create_deliveries_for_subscriptions(event_type, (order, []), webhooks)
# then
payload = json.loads(deliveries[0].payload.get_payload())
@@ -2915,7 +2948,7 @@ def test_order_filter_shipping_methods_with_circular_call_for_shipping_methods(
order = order_line_with_one_allocation.order
# when
- deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ deliveries = create_deliveries_for_subscriptions(event_type, (order, []), webhooks)
# then
payload = json.loads(deliveries[0].payload.get_payload())
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
index f18c546c81..106ee1ebc5 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -291,12 +291,12 @@ def test_checkout_calculate_taxes_with_entire_order_voucher(
checkout_with_voucher,
tax_app,
address,
- shipping_method,
+ checkout_delivery,
):
# given
checkout = checkout_with_voucher
checkout.shipping_address = address
- checkout.shipping_method = shipping_method
+ checkout.assigned_delivery = checkout_delivery(checkout)
checkout.billing_address = address
checkout.save()
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 4418e94e00..07c8191ed8 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -267,7 +267,7 @@ def test_generate_order_payload(
"reason": discount_2.reason,
},
],
- "original": graphene.Node.to_global_id("Order", order.original_id),
+ "original": graphene.Node.to_global_id("Order", order.shipping_method_id),
"lines": json.loads(order_lines),
"fulfillments": [
{
@@ -1836,9 +1836,7 @@ def test_generate_checkout_payload_for_tax_calculation_entire_order_voucher(
# then
shipping_price = str(
quantize_price(
- checkout.shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- ).price.amount,
+ checkout.assigned_delivery.price.amount,
currency,
)
)
@@ -1871,7 +1869,7 @@ def test_generate_checkout_payload_for_tax_calculation_entire_order_voucher(
"included_taxes_in_prices": prices_entered_with_tax,
"lines": mocked_serialized_checkout_lines,
"metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.shipping_method.name,
+ "shipping_name": checkout.assigned_delivery.name,
"user_id": graphene.Node.to_global_id("User", checkout.user.pk),
"user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
"total_amount": str(
@@ -1933,9 +1931,7 @@ def test_generate_checkout_payload_for_tax_calculation_specific_product_voucher(
# then
shipping_price = str(
quantize_price(
- checkout.shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- ).price.amount,
+ checkout.assigned_delivery.price.amount,
currency,
)
)
@@ -1968,7 +1964,7 @@ def test_generate_checkout_payload_for_tax_calculation_specific_product_voucher(
"included_taxes_in_prices": prices_entered_with_tax,
"lines": mocked_serialized_checkout_lines,
"metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.shipping_method.name,
+ "shipping_name": checkout.assigned_delivery.name,
"user_id": graphene.Node.to_global_id("User", checkout.user.pk),
"user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
"total_amount": str(
@@ -2003,9 +1999,7 @@ def test_generate_checkout_payload_for_tax_calculation_shipping_voucher(
voucher.countries = []
voucher.save(update_fields=["countries"])
- shipping_price = checkout.shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- ).price.amount
+ shipping_price = checkout.assigned_delivery.price.amount
assert shipping_price == Decimal(10)
voucher_discount_amount = Decimal(3)
@@ -2068,7 +2062,7 @@ def test_generate_checkout_payload_for_tax_calculation_shipping_voucher(
"included_taxes_in_prices": prices_entered_with_tax,
"lines": mocked_serialized_checkout_lines,
"metadata": {},
- "shipping_name": checkout.shipping_method.name,
+ "shipping_name": checkout.assigned_delivery.name,
"user_id": graphene.Node.to_global_id("User", checkout.user.pk),
"user_public_metadata": {"key": "value"},
"total_amount": str(
@@ -2141,9 +2135,7 @@ def test_generate_checkout_payload_for_tax_calculation_order_discount(
unit_price = variant.get_price(variant_listing)
subtotal_price += unit_price * line_info.line.quantity
shipping_price = quantize_price(
- checkout.shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- ).price.amount,
+ checkout.assigned_delivery.price.amount,
currency,
)
total_price_amount = subtotal_price.amount + shipping_price
@@ -2176,7 +2168,7 @@ def test_generate_checkout_payload_for_tax_calculation_order_discount(
"included_taxes_in_prices": prices_entered_with_tax,
"lines": mocked_serialized_checkout_lines,
"metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.shipping_method.name,
+ "shipping_name": checkout.assigned_delivery.name,
"user_id": graphene.Node.to_global_id("User", checkout.user.pk),
"user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
"total_amount": str(
@@ -2262,9 +2254,7 @@ def test_generate_checkout_payload_for_tax_calculation_gift_promotion(
unit_price = variant.get_price(variant_listing)
subtotal_price += unit_price * line_info.line.quantity
shipping_price = quantize_price(
- checkout.shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- ).price.amount,
+ checkout.assigned_delivery.price.amount,
currency,
)
total_price_amount = subtotal_price.amount + shipping_price
@@ -2405,9 +2395,7 @@ def test_generate_checkout_payload_for_tax_calculation_no_discount(
unit_price = variant.get_price(variant_listing)
subtotal_price += unit_price * line_info.line.quantity
shipping_price = quantize_price(
- checkout.shipping_method.channel_listings.get(
- channel_id=checkout.channel_id
- ).price.amount,
+ checkout.assigned_delivery.price.amount,
currency,
)
total_price_amount = subtotal_price.amount + shipping_price
@@ -2440,7 +2428,7 @@ def test_generate_checkout_payload_for_tax_calculation_no_discount(
"included_taxes_in_prices": prices_entered_with_tax,
"lines": mocked_serialized_checkout_lines,
"metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.shipping_method.name,
+ "shipping_name": checkout.assigned_delivery.name,
"user_id": graphene.Node.to_global_id("User", checkout.user.pk),
"user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
"total_amount": str(
@@ -2475,10 +2463,6 @@ def test_generate_checkout_payload(
# when
payload = json.loads(generate_checkout_payload(checkout, customer_user))[0]
- shipping_method_channel_listing = checkout.shipping_method.channel_listings.filter(
- channel=checkout.channel,
- ).first()
-
# then
assert payload == {
"type": "Checkout",
@@ -2540,15 +2524,15 @@ def test_generate_checkout_payload(
},
"shipping_method": {
"id": graphene.Node.to_global_id(
- "ShippingMethod", checkout.shipping_method.pk
+ "ShippingMethod", checkout.assigned_delivery.shipping_method_id
),
- "name": checkout.shipping_method.name,
- "type": checkout.shipping_method.type,
- "currency": shipping_method_channel_listing.currency,
+ "name": checkout.assigned_delivery.name,
+ "type": "price",
+ "currency": checkout.currency,
"price_amount": str(
quantize_price(
- shipping_method_channel_listing.price_amount,
- shipping_method_channel_listing.currency,
+ checkout.assigned_delivery.price_amount,
+ checkout.currency,
)
),
},
diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.py
index 5ab04dc7fb..75f98cd6d0 100644
--- a/saleor/webhook/transport/shipping.py
+++ b/saleor/webhook/transport/shipping.py
@@ -72,7 +72,9 @@ def get_excluded_shipping_methods_or_fetch(
webhooks: QuerySet,
event_type: str,
payload: str,
- subscribable_object: Union["Order", "Checkout"] | None,
+ subscribable_object: (
+ tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None
+ ),
allow_replica: bool,
requestor: RequestorOrLazyObject | None,
pregenerated_subscription_payloads: dict | None = None,
@@ -114,7 +116,9 @@ def get_excluded_shipping_data(
event_type: str,
previous_value: list[ExcludedShippingMethod],
payload_fun: Callable[[], str],
- subscribable_object: Union["Order", "Checkout"] | None,
+ subscribable_object: (
+ tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None
+ ),
allow_replica: bool,
requestor: RequestorOrLazyObject | None = None,
pregenerated_subscription_payloads: dict | None = None,