Skip to content

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

Shipping dataclass refactor + shipping types split in 3.1 (#8737)

Krzysztof Kulig5e577ff6d55f
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 924d6a8e06..7b34a2a4c7 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -135,20 +135,21 @@ def calculate_base_line_total_price(
return prices_data
-def base_checkout_shipping_price(
+def base_checkout_delivery_price(
checkout_info: "CheckoutInfo", lines=None
) -> TaxedMoney:
+ """Calculate base (untaxed) price for any kind of delivery method."""
delivery_method_info = checkout_info.delivery_method_info
if isinstance(delivery_method_info, ShippingMethodInfo):
- return calculate_price_for_shipping_method(
+ return calculate_base_price_for_shipping_method(
checkout_info, delivery_method_info, lines
)
return zero_taxed_money(checkout_info.checkout.currency)
-def calculate_price_for_shipping_method(
+def calculate_base_price_for_shipping_method(
checkout_info: "CheckoutInfo",
shipping_method_info: ShippingMethodInfo,
lines=None,
@@ -167,16 +168,14 @@ def calculate_price_for_shipping_method(
if not shipping_method or not shipping_required:
return zero_taxed_money(checkout_info.checkout.currency)
- # external shipping methods have the price field,
- # while internal methods use channel listings
- shipping_price = shipping_method.price
- if shipping_price is None:
- shipping_price = shipping_method.channel_listings.get( # type: ignore
- channel_id=checkout_info.checkout.channel_id,
- ).get_total()
-
+ # Base price does not yet contain tax information,
+ # which can be later applied by tax plugins
return quantize_price(
- TaxedMoney(net=shipping_price, gross=shipping_price), shipping_price.currency
+ TaxedMoney(
+ net=shipping_method.price,
+ gross=shipping_method.price,
+ ),
+ checkout_info.checkout.currency,
)
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index c4bee26ae3..8f97d01e40 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -1,14 +1,15 @@
import itertools
from dataclasses import dataclass
from functools import singledispatch
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Union
from django.utils.encoding import smart_text
+from django.utils.functional import SimpleLazyObject
from ..discount import DiscountInfo, VoucherType
from ..discount.utils import fetch_active_discounts
from ..shipping.interface import ShippingMethodData
-from ..shipping.models import ShippingMethodChannelListing
+from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
from ..shipping.utils import convert_to_shipping_method_data
from ..warehouse import WarehouseClickAndCollectOption
from ..warehouse.models import Warehouse
@@ -47,9 +48,12 @@ class CheckoutInfo:
billing_address: Optional["Address"]
shipping_address: Optional["Address"]
delivery_method_info: "DeliveryMethodBase"
- valid_shipping_methods: List["ShippingMethodData"]
+ all_shipping_methods: List["ShippingMethodData"]
valid_pick_up_points: List["Warehouse"]
- shipping_method_channel_listings: Optional[ShippingMethodChannelListing]
+
+ @property
+ def valid_shipping_methods(self) -> List["ShippingMethodData"]:
+ return [method for method in self.all_shipping_methods if method.active]
@property
def valid_delivery_methods(
@@ -102,9 +106,6 @@ class DeliveryMethodBase:
def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:
return False
- def update_channel_listings(self, checkout_info: "CheckoutInfo") -> None:
- checkout_info.shipping_method_channel_listings = None
-
@dataclass(frozen=True)
class ShippingMethodInfo(DeliveryMethodBase):
@@ -130,15 +131,6 @@ class ShippingMethodInfo(DeliveryMethodBase):
valid_delivery_methods and self.delivery_method in valid_delivery_methods
)
- def update_channel_listings(self, checkout_info: "CheckoutInfo") -> None:
- if not self.delivery_method.is_external:
- checkout_info.shipping_method_channel_listings = (
- ShippingMethodChannelListing.objects.filter(
- shipping_method_id=int(self.delivery_method.id),
- channel=checkout_info.channel,
- ).first()
- )
-
@dataclass(frozen=True)
class CollectionPointInfo(DeliveryMethodBase):
@@ -186,11 +178,13 @@ class CollectionPointInfo(DeliveryMethodBase):
@singledispatch
def get_delivery_method_info(
- delivery_method: Optional[Union["ShippingMethodData", "Warehouse"]],
+ delivery_method: Optional[Union["ShippingMethodData", "Warehouse", Callable]],
address=Optional["Address"],
) -> DeliveryMethodBase:
if delivery_method is None:
return DeliveryMethodBase()
+ if callable(delivery_method):
+ delivery_method = delivery_method()
if isinstance(delivery_method, ShippingMethodData):
return ShippingMethodInfo(delivery_method, address)
if isinstance(delivery_method, Warehouse):
@@ -290,95 +284,87 @@ def fetch_checkout_info(
lines: Iterable[CheckoutLineInfo],
discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
- *,
- # Ugly hack to disable fetching shipping methods if they aren't needed
- # Preventing multiple redundant and potentially costful API calls in
- # checkout lines add/update/delete mutations
- fetch_delivery_methods: bool = True,
+ shipping_channel_listings: Optional[
+ Iterable["ShippingMethodChannelListing"]
+ ] = None,
) -> CheckoutInfo:
"""Fetch checkout as CheckoutInfo object."""
+ channel = checkout.channel
+ shipping_address = checkout.shipping_address
+ if shipping_channel_listings is None:
+ shipping_channel_listings = channel.shipping_method_listings.all()
+
+ delivery_method_info = get_delivery_method_info(None, shipping_address)
checkout_info = CheckoutInfo(
checkout=checkout,
user=checkout.user,
- channel=checkout.channel,
+ channel=channel,
billing_address=checkout.billing_address,
- shipping_address=checkout.shipping_address,
- delivery_method_info=DeliveryMethodBase(),
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
+ shipping_address=shipping_address,
+ delivery_method_info=delivery_method_info,
+ all_shipping_methods=[],
valid_pick_up_points=[],
)
-
- if fetch_delivery_methods:
- populate_checkout_info_shippings(checkout_info, lines, discounts, manager)
- valid_pick_up_points = get_valid_collection_points_for_checkout_info(
- checkout.shipping_address, lines, checkout_info
- )
- checkout_info.valid_pick_up_points = valid_pick_up_points
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info,
+ checkout.shipping_method,
+ checkout.collection_point,
+ shipping_address,
+ lines,
+ discounts,
+ manager,
+ shipping_channel_listings,
+ )
return checkout_info
-def populate_checkout_info_shippings(
+def update_checkout_info_delivery_method_info(
checkout_info: CheckoutInfo,
- lines: Iterable[CheckoutLineInfo],
- discounts: Iterable["DiscountInfo"],
- manager: "PluginsManager",
+ shipping_method: Optional[ShippingMethod],
+ collection_point: Optional[Warehouse],
+ shipping_channel_listings: Iterable[ShippingMethodChannelListing],
):
+ """Update delivery_method_attribute for CheckoutInfo.
+
+ The attribute is lazy-evaluated avoid external API calls unless accessed.
+ """
from .utils import get_external_shipping_id
+ delivery_method: Optional[Union[ShippingMethodData, Warehouse, Callable]] = None
checkout = checkout_info.checkout
- channel = checkout_info.channel
- shipping_address = checkout_info.shipping_address
- shipping_method = checkout.shipping_method
-
- external_shipping_methods = (
- get_valid_external_shipping_method_list_for_checkout_info(
- checkout_info, shipping_address, lines, discounts, manager
- )
- )
-
- shipping_channel_listings = None
if shipping_method:
- shipping_channel_listings = ShippingMethodChannelListing.objects.filter(
- shipping_method=shipping_method, channel=channel
- ).first()
+ # Find listing for the currently selected shipping method
+ shipping_channel_listing = None
+ for listing in shipping_channel_listings:
+ if listing.shipping_method_id == shipping_method.id:
+ shipping_channel_listing = listing
+ break
+
+ delivery_method = convert_to_shipping_method_data(
+ shipping_method, shipping_channel_listing
+ )
- delivery_method: Optional[
- Union["ShippingMethodData", "Warehouse"]
- ] = convert_to_shipping_method_data(shipping_method)
- else:
- delivery_method = checkout.collection_point
+ elif external_shipping_method_id := get_external_shipping_id(checkout):
+ # A local function is used to delay evaluation
+ # of the lazy `all_shipping_methods` attribute
+ def _resolve_external_method():
+ methods = {
+ method.id: method for method in checkout_info.all_shipping_methods
+ }
+ return methods.get(external_shipping_method_id)
- checkout_info.shipping_method_channel_listings = shipping_channel_listings
+ delivery_method = _resolve_external_method
- if not delivery_method:
- external_shipping_method_id = get_external_shipping_id(checkout)
- if external_shipping_method_id:
- external_shipping_methods_map = {
- external_shipping_method.id: external_shipping_method
- for external_shipping_method in external_shipping_methods
- }
- delivery_method = external_shipping_methods_map.get(
- external_shipping_method_id
- )
+ else:
+ delivery_method = collection_point
- if delivery_method:
- delivery_method_info = get_delivery_method_info(
- delivery_method, shipping_address
- )
- checkout_info.delivery_method_info = delivery_method_info
-
- valid_shipping_methods: List["ShippingMethodData"] = list(
- itertools.chain(
- get_valid_local_shipping_method_list_for_checkout_info(
- checkout_info, shipping_address, lines, discounts, manager
- ),
- external_shipping_methods,
+ checkout_info.delivery_method_info = SimpleLazyObject(
+ lambda: get_delivery_method_info(
+ delivery_method,
+ checkout_info.shipping_address,
)
- )
-
- checkout_info.valid_shipping_methods = valid_shipping_methods
+ ) # type: ignore
def update_checkout_info_shipping_address(
@@ -387,48 +373,46 @@ def update_checkout_info_shipping_address(
lines: Iterable[CheckoutLineInfo],
discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
+ shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
):
checkout_info.shipping_address = address
- valid_shipping_methods: List[
- "ShippingMethodData"
- ] = get_valid_shipping_method_list_for_checkout_info(
- checkout_info, address, lines, discounts, manager
- )
-
- checkout_info.valid_shipping_methods = valid_shipping_methods
-
- delivery_method = checkout_info.delivery_method_info.delivery_method
- checkout_info.delivery_method_info = get_delivery_method_info(
- delivery_method, address
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info,
+ checkout_info.checkout.shipping_method,
+ checkout_info.checkout.collection_point,
+ address,
+ lines,
+ discounts,
+ manager,
+ shipping_channel_listings,
)
-def get_valid_local_shipping_method_list_for_checkout_info(
+def get_valid_internal_shipping_method_list_for_checkout_info(
checkout_info: "CheckoutInfo",
shipping_address: Optional["Address"],
lines: Iterable[CheckoutLineInfo],
discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
+ shipping_channel_listings: Iterable[ShippingMethodChannelListing],
) -> List["ShippingMethodData"]:
- from .utils import get_valid_shipping_methods_for_checkout
+ from .utils import get_valid_internal_shipping_methods_for_checkout
country_code = shipping_address.country.code if shipping_address else None
subtotal = manager.calculate_checkout_subtotal(
checkout_info, lines, checkout_info.shipping_address, discounts
)
subtotal -= checkout_info.checkout.discount
- valid_shipping_method = get_valid_shipping_methods_for_checkout(
- checkout_info, lines, subtotal, country_code=country_code
+ valid_shipping_methods = get_valid_internal_shipping_methods_for_checkout(
+ checkout_info,
+ lines,
+ subtotal,
+ shipping_channel_listings,
+ country_code=country_code,
)
- if valid_shipping_method is None:
- return []
-
- return [
- convert_to_shipping_method_data(shipping) # type: ignore
- for shipping in valid_shipping_method
- ]
+ return valid_shipping_methods
def get_valid_external_shipping_method_list_for_checkout_info(
@@ -444,22 +428,53 @@ def get_valid_external_shipping_method_list_for_checkout_info(
)
-def get_valid_shipping_method_list_for_checkout_info(
+def update_delivery_method_lists_for_checkout_info(
checkout_info: "CheckoutInfo",
+ shipping_method: Optional["ShippingMethod"],
+ collection_point: Optional["Warehouse"],
shipping_address: Optional["Address"],
lines: Iterable[CheckoutLineInfo],
discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
-) -> List["ShippingMethodData"]:
- return list(
- itertools.chain(
- get_valid_local_shipping_method_list_for_checkout_info(
- checkout_info, shipping_address, lines, discounts, manager
- ),
- get_valid_external_shipping_method_list_for_checkout_info(
- checkout_info, shipping_address, lines, discounts, manager
- ),
+ shipping_channel_listings: Iterable[ShippingMethodChannelListing],
+):
+ """Update the list of shipping methods for checkout info.
+
+ Shipping methods excluded by Saleor's own business logic are not present
+ in the result list.
+
+ Availability of shipping methods according to plugins is indicated
+ by the `active` field.
+ """
+ checkout_info.all_shipping_methods = SimpleLazyObject(
+ lambda: list(
+ itertools.chain(
+ get_valid_internal_shipping_method_list_for_checkout_info(
+ checkout_info,
+ shipping_address,
+ lines,
+ discounts,
+ manager,
+ shipping_channel_listings,
+ ),
+ get_valid_external_shipping_method_list_for_checkout_info(
+ checkout_info, shipping_address, lines, discounts, manager
+ ),
+ )
+ )
+ ) # type: ignore
+ checkout_info.valid_pick_up_points = SimpleLazyObject(
+ lambda: (
+ get_valid_collection_points_for_checkout_info(
+ shipping_address, lines, checkout_info
+ )
)
+ ) # type: ignore
+ update_checkout_info_delivery_method_info(
+ checkout_info,
+ shipping_method,
+ collection_point,
+ shipping_channel_listings,
)
@@ -478,7 +493,7 @@ def get_valid_collection_points_for_checkout_info(
valid_collection_points = get_valid_collection_points_for_checkout(
lines, country_code=country_code, quantity_check=False
)
- return list(valid_collection_points)
+ return SimpleLazyObject(lambda: list(valid_collection_points))
def update_checkout_info_delivery_method(
@@ -488,4 +503,3 @@ def update_checkout_info_delivery_method(
checkout_info.delivery_method_info = get_delivery_method_info(
delivery_method, checkout_info.shipping_address
)
- checkout_info.delivery_method_info.update_channel_listings(checkout_info)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index d67ddf2a16..92b4be3019 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -16,8 +16,8 @@ from ...discount import DiscountValueType, VoucherType
from ...discount.models import NotApplicable, Voucher, VoucherChannelListing
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
-from ...shipping.models import ShippingMethod, ShippingZone
-from ...shipping.utils import convert_to_shipping_method_data
+from ...shipping.interface import ShippingMethodData
+from ...shipping.models import ShippingZone
from .. import AddressType, calculations
from ..fetch import (
CheckoutInfo,
@@ -116,7 +116,6 @@ def test_clear_delivery_method(checkout, shipping_method):
checkout.refresh_from_db()
assert not checkout.shipping_method
assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
- assert not checkout_info.shipping_method_channel_listings
def test_last_change_update(checkout):
@@ -188,10 +187,9 @@ def test_get_discount_for_checkout_value_voucher(
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
delivery_method_info=get_delivery_method_info(None, None),
+ all_shipping_methods=[],
)
lines = [
CheckoutLineInfo(
@@ -284,9 +282,8 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
manager = get_plugins_manager()
with pytest.raises(NotApplicable):
@@ -398,9 +395,8 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
with pytest.raises(NotApplicable):
get_voucher_discount_for_checkout(
@@ -428,6 +424,7 @@ def test_get_discount_for_checkout_shipping_voucher(
monkeypatch,
channel_USD,
shipping_method,
+ shipping_method_data,
):
manager = get_plugins_manager()
subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
@@ -468,14 +465,13 @@ def test_get_discount_for_checkout_shipping_voucher(
checkout=checkout,
shipping_address=shipping_address,
delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(shipping_method), shipping_address
+ shipping_method_data, shipping_address
),
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
discount = get_voucher_discount_for_checkout(
@@ -485,7 +481,7 @@ def test_get_discount_for_checkout_shipping_voucher(
def test_get_discount_for_checkout_shipping_voucher_all_countries(
- monkeypatch, channel_USD, shipping_method
+ monkeypatch, channel_USD, shipping_method, shipping_method_data
):
subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
monkeypatch.setattr(
@@ -528,16 +524,13 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(
manager = get_plugins_manager()
checkout_info = CheckoutInfo(
checkout=checkout,
- delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(shipping_method), None
- ),
+ delivery_method_info=get_delivery_method_info(shipping_method_data),
shipping_address=Mock(spec=Address, country=Mock(code="PL")),
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
discount = get_voucher_discount_for_checkout(
manager, voucher, checkout_info, [], None, None
@@ -581,9 +574,8 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
manager = get_plugins_manager()
with pytest.raises(NotApplicable):
@@ -591,17 +583,13 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
@pytest.mark.parametrize(
- "is_shipping_required, shipping_method, discount_value, discount_type,"
+ "is_shipping_required, shipping_method_data, discount_value, discount_type,"
"countries, min_spent_amount, min_checkout_items_quantity, subtotal,"
"total_quantity, error_msg",
[
(
True,
- Mock(
- spec=ShippingMethod,
- get_total=Mock(return_value=Money(10, "USD")),
- shipping_zone=Mock(countries=["PL"]),
- ),
+ ShippingMethodData("1", "test", Money(10, "USD")),
10,
DiscountValueType.FIXED,
["US"],
@@ -637,7 +625,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
),
(
True,
- Mock(spec=ShippingMethod, price=Money(10, "USD")),
+ ShippingMethodData("1", "test", Money(10, "USD")),
10,
DiscountValueType.FIXED,
[],
@@ -649,7 +637,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
),
(
True,
- Mock(spec=ShippingMethod, price=Money(10, "USD")),
+ ShippingMethodData("1", "test", Money(10, "USD")),
10,
DiscountValueType.FIXED,
[],
@@ -661,7 +649,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
),
(
True,
- Mock(spec=ShippingMethod, price=Money(10, "USD")),
+ ShippingMethodData("1", "test", Money(10, "USD")),
10,
DiscountValueType.FIXED,
[],
@@ -676,6 +664,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
def test_get_discount_for_checkout_shipping_voucher_not_applicable(
is_shipping_required,
shipping_method,
+ shipping_method_data,
discount_value,
discount_type,
countries,
@@ -723,16 +712,13 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
)
checkout_info = CheckoutInfo(
checkout=checkout,
- delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(shipping_method)
- ),
+ delivery_method_info=get_delivery_method_info(shipping_method_data),
shipping_address=Mock(spec=Address, country=Mock(code="PL")),
billing_address=None,
channel=channel_USD,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(
@@ -948,7 +934,14 @@ def test_change_address_in_checkout(checkout, address):
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(checkout_info, address, lines, [], manager)
+ change_shipping_address_in_checkout(
+ checkout_info,
+ address,
+ lines,
+ [],
+ manager,
+ checkout.channel.shipping_method_listings.all(),
+ )
change_billing_address_in_checkout(checkout, address)
checkout.refresh_from_db()
@@ -965,7 +958,14 @@ def test_change_address_in_checkout_to_none(checkout, address):
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(checkout_info, None, lines, [], manager)
+ change_shipping_address_in_checkout(
+ checkout_info,
+ None,
+ lines,
+ [],
+ manager,
+ checkout.channel.shipping_method_listings.all(),
+ )
change_billing_address_in_checkout(checkout, None)
checkout.refresh_from_db()
@@ -984,7 +984,14 @@ def test_change_address_in_checkout_to_same(checkout, address):
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(checkout_info, address, lines, [], manager)
+ change_shipping_address_in_checkout(
+ checkout_info,
+ address,
+ lines,
+ [],
+ manager,
+ checkout.channel.shipping_method_listings.all(),
+ )
change_billing_address_in_checkout(checkout, address)
checkout.refresh_from_db()
@@ -1004,7 +1011,12 @@ def test_change_address_in_checkout_to_other(checkout, address):
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
change_shipping_address_in_checkout(
- checkout_info, other_address, lines, [], manager
+ checkout_info,
+ other_address,
+ lines,
+ [],
+ manager,
+ checkout.channel.shipping_method_listings.all(),
)
change_billing_address_in_checkout(checkout, other_address)
@@ -1029,7 +1041,12 @@ def test_change_address_in_checkout_from_user_address_to_other(
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
change_shipping_address_in_checkout(
- checkout_info, other_address, lines, [], manager
+ checkout_info,
+ other_address,
+ lines,
+ [],
+ manager,
+ checkout.channel.shipping_method_listings.all(),
)
change_billing_address_in_checkout(checkout, other_address)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index deb17657fb..d5bed2c649 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -26,7 +26,9 @@ from ..giftcard.utils import (
)
from ..plugins.manager import PluginsManager
from ..product import models as product_models
-from ..shipping.models import ShippingMethod
+from ..shipping.interface import ShippingMethodData
+from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
+from ..shipping.utils import convert_to_shipping_method_data
from ..warehouse.availability import (
check_stock_and_preorder_quantity,
check_stock_and_preorder_quantity_bulk,
@@ -256,6 +258,7 @@ def change_shipping_address_in_checkout(
lines: Iterable["CheckoutLineInfo"],
discounts: Iterable[DiscountInfo],
manager: "PluginsManager",
+ shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
):
"""Save shipping address in checkout if changed.
@@ -270,7 +273,7 @@ def change_shipping_address_in_checkout(
checkout.shipping_address.delete() # type: ignore
checkout.shipping_address = address
update_checkout_info_shipping_address(
- checkout_info, address, lines, discounts, manager
+ checkout_info, address, lines, discounts, manager, shipping_channel_listings
)
checkout.save(update_fields=["shipping_address", "last_change"])
@@ -644,24 +647,39 @@ def remove_voucher_from_checkout(checkout: Checkout):
)
-def get_valid_shipping_methods_for_checkout(
+def get_valid_internal_shipping_methods_for_checkout(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
subtotal: "TaxedMoney",
+ shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
country_code: Optional[str] = None,
-):
+) -> List[ShippingMethodData]:
if not is_shipping_required(lines):
- return None
+ return []
if not checkout_info.shipping_address:
- return None
- return ShippingMethod.objects.applicable_shipping_methods_for_instance(
+ return []
+
+ shipping_methods = ShippingMethod.objects.applicable_shipping_methods_for_instance(
checkout_info.checkout,
channel_id=checkout_info.checkout.channel_id,
price=subtotal.gross,
- country_code=country_code, # type: ignore
+ country_code=country_code,
lines=lines,
)
+ channel_listings_map = {
+ listing.shipping_method_id: listing for listing in shipping_channel_listings
+ }
+
+ internal_methods = []
+ for method in shipping_methods:
+ listing = channel_listings_map.get(method.pk)
+ shipping_method_data = convert_to_shipping_method_data(method, listing)
+ if shipping_method_data:
+ internal_methods.append(shipping_method_data)
+
+ return internal_methods
+
def get_valid_collection_points_for_checkout(
lines: Iterable["CheckoutLineInfo"],
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 0b9c79166b..1772ca21e1 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -782,7 +782,6 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
"user_email": get_email(address.first_name, address.last_name),
}
- manager = get_plugins_manager()
shipping_method_channel_listing = (
ShippingMethodChannelListing.objects.filter(channel=channel)
.order_by("?")
@@ -790,9 +789,7 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
)
shipping_method = shipping_method_channel_listing.shipping_method
shipping_price = shipping_method_channel_listing.price
- shipping_price = manager.apply_taxes_to_shipping(
- shipping_price, address, channel_slug=channel.slug
- )
+ shipping_price = TaxedMoney(net=shipping_price, gross=shipping_price)
order_data.update(
{
"channel": channel,
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
index c1d0394b61..4c82daad69 100644
--- a/saleor/graphql/checkout/dataloaders.py
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -3,10 +3,13 @@ from collections import defaultdict
from django.db.models import F
from promise import Promise
-from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo, get_delivery_method_info
+from ...checkout.fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+ get_delivery_method_info,
+ update_delivery_method_lists_for_checkout_info,
+)
from ...checkout.models import Checkout, CheckoutLine
-from ...checkout.utils import get_external_shipping_id
-from ...shipping.utils import convert_to_shipping_method_data
from ..account.dataloaders import AddressByIdLoader, UserByUserIdLoader
from ..core.dataloaders import DataLoader
from ..product.dataloaders import (
@@ -18,7 +21,7 @@ from ..product.dataloaders import (
)
from ..shipping.dataloaders import (
ShippingMethodByIdLoader,
- ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,
+ ShippingMethodChannelListingByChannelSlugLoader,
)
from ..warehouse.dataloaders import WarehouseByIdLoader
@@ -150,7 +153,8 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):
context_key = "checkoutinfo_by_checkout"
def batch_load(self, keys):
- def with_checkout(checkouts):
+ def with_checkout(data):
+ checkouts, checkout_line_infos = data
from ..channel.dataloaders import ChannelByIdLoader
channel_pks = [checkout.channel_id for checkout in checkouts]
@@ -180,15 +184,11 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):
shipping_methods = ShippingMethodByIdLoader(self.context).load_many(
shipping_method_ids
)
- shipping_method_ids_channel_slugs = [
- (checkout.shipping_method_id, channel.slug)
- for checkout, channel in zip(checkouts, channels)
- if checkout.shipping_method_id
- ]
+ channel_slugs = [channel.slug for channel in channels]
shipping_method_channel_listings = (
- ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
+ ShippingMethodChannelListingByChannelSlugLoader(
self.context
- ).load_many(shipping_method_ids_channel_slugs)
+ ).load_many(channel_slugs)
)
collection_point_ids = [
checkout.collection_point_id
@@ -204,7 +204,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):
addresses,
users,
shipping_methods,
- channel_listings,
+ listings_for_channels,
collection_points,
) = results
address_map = {address.id: address for address in addresses}
@@ -213,46 +213,26 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):
shipping_method.id: shipping_method
for shipping_method in shipping_methods
}
- shipping_method_channel_listing_map = {
- (listing.shipping_method_id, listing.channel_id): listing
- for listing in channel_listings
- if listing
- }
-
collection_points_map = {
collection_point.id: collection_point
for collection_point in collection_points
}
checkout_info_map = {}
- for key, checkout, channel in zip(keys, checkouts, channels):
+ for key, checkout, channel, checkout_lines in zip(
+ keys, checkouts, channels, checkout_line_infos
+ ):
shipping_method = shipping_method_map.get(
checkout.shipping_method_id
)
- external_app_shipping_id = get_external_shipping_id(checkout)
-
- if shipping_method:
- delivery_method = convert_to_shipping_method_data(
- shipping_method
- )
- elif external_app_shipping_id:
- delivery_method = self.context.plugins.get_shipping_method(
- checkout=checkout,
- channel_slug=checkout.channel.slug,
- shipping_method_id=external_app_shipping_id,
- )
- else:
- delivery_method = collection_points_map.get(
- checkout.collection_point_id
- )
- shipping_address = (
- address_map.get(checkout.shipping_address_id),
+ collection_point = collection_points_map.get(
+ checkout.collection_point_id
)
+ shipping_address = address_map.get(checkout.shipping_address_id)
delivery_method_info = get_delivery_method_info(
- delivery_method, shipping_address
+ None, shipping_address
)
-
- checkout_info_map[key] = CheckoutInfo(
+ checkout_info = CheckoutInfo(
checkout=checkout,
user=user_map.get(checkout.user_id),
channel=channel,
@@ -263,15 +243,30 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):
checkout.shipping_address_id
),
delivery_method_info=delivery_method_info,
- valid_shipping_methods=[],
valid_pick_up_points=[],
- shipping_method_channel_listings=(
- shipping_method_channel_listing_map.get(
- (checkout.shipping_method_id, channel.id)
- )
- ),
+ all_shipping_methods=[],
)
+ manager = self.context.plugins
+ discounts = self.context.discounts
+ shipping_method_listings = [
+ listing
+ for channel_listings in listings_for_channels
+ for listing in channel_listings
+ if listing.channel_id == channel.id
+ ]
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info,
+ shipping_method,
+ collection_point,
+ shipping_address,
+ checkout_lines,
+ discounts,
+ manager,
+ shipping_method_listings,
+ )
+ checkout_info_map[key] = checkout_info
+
return [checkout_info_map[key] for key in keys]
return Promise.all(
@@ -290,7 +285,11 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):
.then(with_channel)
)
- return CheckoutByTokenLoader(self.context).load_many(keys).then(with_checkout)
+ checkouts = CheckoutByTokenLoader(self.context).load_many(keys)
+ checkout_line_infos = CheckoutLinesInfoByCheckoutTokenLoader(
+ self.context
+ ).load_many(keys)
+ return Promise.all([checkouts, checkout_line_infos]).then(with_checkout)
class CheckoutLineByIdLoader(DataLoader):
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index cf866e3380..4be0b63b9a 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -17,9 +17,7 @@ from ...checkout.fetch import (
CheckoutLineInfo,
fetch_checkout_info,
fetch_checkout_lines,
- get_valid_collection_points_for_checkout_info,
- get_valid_shipping_method_list_for_checkout_info,
- populate_checkout_info_shippings,
+ update_delivery_method_lists_for_checkout_info,
)
from ...checkout.utils import (
add_promo_code_to_checkout,
@@ -249,11 +247,17 @@ def validate_variants_are_published(variants_id: set, channel_id: int):
)
-def get_checkout_by_token(token: uuid.UUID, prefetch_lookups: Iterable[str] = []):
- try:
- checkout = models.Checkout.objects.prefetch_related(*prefetch_lookups).get(
- token=token
+def get_checkout_by_token(token: uuid.UUID, qs=None):
+ if qs is None:
+ qs = models.Checkout.objects.select_related(
+ "channel",
+ "shipping_method",
+ "collection_point",
+ "billing_address",
+ "shipping_address",
)
+ try:
+ checkout = qs.get(token=token)
except ObjectDoesNotExist:
raise ValidationError(
{
@@ -592,11 +596,16 @@ class CheckoutLinesAdd(BaseMutation):
)
lines = fetch_checkout_lines(checkout)
- populate_checkout_info_shippings(checkout_info, lines, discounts, manager)
- checkout_info.valid_pick_up_points = (
- get_valid_collection_points_for_checkout_info(
- checkout_info.shipping_address, lines, checkout_info
- )
+ shipping_channel_listings = checkout.channel.shipping_method_listings.all()
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info,
+ checkout_info.checkout.shipping_method,
+ checkout_info.checkout.collection_point,
+ checkout_info.shipping_address,
+ lines,
+ discounts,
+ manager,
+ shipping_channel_listings,
)
return lines
@@ -624,14 +633,12 @@ class CheckoutLinesAdd(BaseMutation):
variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)
input_quantities = group_quantity_by_variants(lines)
- lines = fetch_checkout_lines(checkout)
+ shipping_channel_listings = checkout.channel.shipping_method_listings.all()
checkout_info = fetch_checkout_info(
- checkout,
- lines,
- discounts,
- manager,
- fetch_delivery_methods=False,
+ checkout, [], discounts, manager, shipping_channel_listings
)
+
+ lines = fetch_checkout_lines(checkout)
lines = cls.clean_input(
info,
checkout,
@@ -643,7 +650,6 @@ class CheckoutLinesAdd(BaseMutation):
discounts,
replace,
)
-
update_checkout_shipping_method_if_invalid(checkout_info, lines)
recalculate_checkout_discount(
manager, checkout_info, lines, info.context.discounts
@@ -978,7 +984,10 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
if token:
checkout = get_checkout_by_token(
- token, prefetch_lookups=["lines__variant__product__product_type"]
+ token,
+ qs=models.Checkout.objects.prefetch_related(
+ "lines__variant__product__product_type"
+ ),
)
# DEPRECATED
if checkout_id:
@@ -1019,7 +1028,10 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
discounts = info.context.discounts
manager = info.context.plugins
- checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+ shipping_channel_listings = checkout.channel.shipping_method_listings.all()
+ checkout_info = fetch_checkout_info(
+ checkout, lines, discounts, manager, shipping_channel_listings
+ )
country = shipping_address.country.code
checkout.set_country(country, commit=True)
@@ -1033,7 +1045,12 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
with traced_atomic_transaction():
shipping_address.save()
change_shipping_address_in_checkout(
- checkout_info, shipping_address, lines, discounts, manager
+ checkout_info,
+ shipping_address,
+ lines,
+ discounts,
+ manager,
+ shipping_channel_listings,
)
recalculate_checkout_discount(manager, checkout_info, lines, discounts)
@@ -1303,7 +1320,13 @@ class CheckoutShippingMethodUpdate(BaseMutation):
"postal_code_rules"
),
)
- delivery_method = convert_to_shipping_method_data(shipping_method)
+ delivery_method = convert_to_shipping_method_data(
+ shipping_method,
+ shipping_models.ShippingMethodChannelListing.objects.filter(
+ shipping_method=shipping_method,
+ channel=checkout_info.channel,
+ ).first(),
+ )
cls._check_delivery_method(
checkout_info, lines, delivery_method=delivery_method
@@ -1379,7 +1402,13 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
),
)
- delivery_method = convert_to_shipping_method_data(shipping_method)
+ delivery_method = convert_to_shipping_method_data(
+ shipping_method,
+ shipping_models.ShippingMethodChannelListing.objects.filter(
+ shipping_method=shipping_method,
+ channel=checkout_info.channel,
+ ).first(),
+ )
cls._check_delivery_method(
checkout_info, lines, shipping_method=delivery_method, collection_point=None
)
@@ -1751,7 +1780,10 @@ class CheckoutAddPromoCode(BaseMutation):
manager = info.context.plugins
discounts = info.context.discounts
lines = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+ shipping_channel_listings = checkout.channel.shipping_method_listings.all()
+ checkout_info = fetch_checkout_info(
+ checkout, lines, discounts, manager, shipping_channel_listings
+ )
add_promo_code_to_checkout(
manager,
@@ -1761,10 +1793,15 @@ class CheckoutAddPromoCode(BaseMutation):
discounts,
)
- checkout_info.valid_shipping_methods = (
- get_valid_shipping_method_list_for_checkout_info(
- checkout_info, checkout_info.shipping_address, lines, discounts, manager
- )
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info,
+ checkout_info.checkout.shipping_method,
+ checkout_info.checkout.collection_point,
+ checkout_info.shipping_address,
+ lines,
+ discounts,
+ manager,
+ shipping_channel_listings,
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 0cbc5ccc74..6a25f48c85 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -447,7 +447,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(53):
+ with django_assert_num_queries(54):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -465,7 +465,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(53):
+ with django_assert_num_queries(54):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -706,7 +706,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(57):
+ with django_assert_num_queries(53):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"token": checkout.token,
@@ -720,7 +720,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(57):
+ with django_assert_num_queries(53):
variables = {
"token": checkout.token,
"lines": [],
@@ -829,7 +829,7 @@ def test_add_checkout_lines(
api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
)
assert not response["data"]["checkoutLinesAdd"]["errors"]
- assert mock_send_request.call_count == 1
+ assert mock_send_request.call_count == 0
@pytest.mark.django_db
@@ -912,10 +912,9 @@ def test_add_checkout_lines_with_external_shipping(
api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
)
assert not response["data"]["checkoutLinesAdd"]["errors"]
- # Two API calls:
- # - mutate() logic
- # - dataloader for lines totalPrice
- assert mock_send_request.call_count == 2
+ # One api call:
+ # - post-mutate() logic used to validate currently selected method
+ assert mock_send_request.call_count == 1
@pytest.mark.django_db
@@ -962,7 +961,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(56):
+ with django_assert_num_queries(53):
variables = {
"checkoutId": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -975,7 +974,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(56):
+ with django_assert_num_queries(53):
variables = {
"checkoutId": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
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 4da6906261..bfc6569351 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
@@ -39,9 +39,9 @@ def test_checkout_shipping_method_update_by_id(
mock_clean_shipping,
staff_api_client,
shipping_method,
- checkout_with_item,
+ checkout_with_item_and_shipping_method,
):
- checkout = checkout_with_item
+ checkout = checkout_with_item_and_shipping_method
old_shipping_method = checkout.shipping_method
query = MUTATION_UPDATE_SHIPPING_METHOD
mock_clean_shipping.return_value = True
@@ -60,13 +60,18 @@ def test_checkout_shipping_method_update_by_id(
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
checkout_info.delivery_method_info = get_delivery_method_info(
- convert_to_shipping_method_data(old_shipping_method), None
+ convert_to_shipping_method_data(
+ old_shipping_method, old_shipping_method.channel_listings.first()
+ ),
+ None,
)
- checkout_info.shipping_method_channel_listings = None
+
mock_clean_shipping.assert_called_once_with(
checkout_info=checkout_info,
lines=lines,
- method=convert_to_shipping_method_data(shipping_method),
+ method=convert_to_shipping_method_data(
+ shipping_method, shipping_method.channel_listings.first()
+ ),
)
errors = data["errors"]
assert not errors
@@ -79,9 +84,9 @@ def test_checkout_shipping_method_update_by_token(
mock_clean_shipping,
staff_api_client,
shipping_method,
- checkout_with_item,
+ checkout_with_item_and_shipping_method,
):
- checkout = checkout_with_item
+ checkout = checkout_with_item_and_shipping_method
old_shipping_method = checkout.shipping_method
query = MUTATION_UPDATE_SHIPPING_METHOD
mock_clean_shipping.return_value = True
@@ -100,13 +105,17 @@ def test_checkout_shipping_method_update_by_token(
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
checkout_info.delivery_method_info = get_delivery_method_info(
- convert_to_shipping_method_data(old_shipping_method), None
+ convert_to_shipping_method_data(
+ old_shipping_method, old_shipping_method.channel_listings.first()
+ ),
+ None,
)
- checkout_info.shipping_method_channel_listings = None
mock_clean_shipping.assert_called_once_with(
checkout_info=checkout_info,
lines=lines,
- method=convert_to_shipping_method_data(shipping_method),
+ method=convert_to_shipping_method_data(
+ shipping_method, shipping_method.channel_listings.first()
+ ),
)
errors = data["errors"]
assert not errors
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 4e44e89366..6ec0d4dddb 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -14,7 +14,7 @@ from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django_countries.fields import Country
from measurement.measures import Weight
-from prices import Money, TaxedMoney
+from prices import Money
from ....account.models import User
from ....channel.utils import DEPRECATION_WARNING_MESSAGE
@@ -38,12 +38,13 @@ from ....checkout.utils import (
from ....core.payments import PaymentInterface
from ....payment import TransactionKind
from ....payment.interface import GatewayResponse
-from ....plugins.manager import PluginsManager, get_plugins_manager
+from ....plugins.manager import get_plugins_manager
from ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway
from ....product.models import ProductChannelListing, ProductVariant
from ....shipping import models as shipping_models
from ....shipping.models import ShippingMethodTranslation
from ....shipping.utils import convert_to_shipping_method_data
+from ....tests.utils import dummy_editorjs
from ....warehouse.models import PreorderReservation, Reservation, Stock, Warehouse
from ...tests.utils import assert_no_permission, get_graphql_content
from ..mutations import (
@@ -66,7 +67,9 @@ def test_clean_delivery_method_after_shipping_address_changes_stay_the_same(
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- delivery_method = convert_to_shipping_method_data(shipping_method)
+ delivery_method = convert_to_shipping_method_data(
+ shipping_method, shipping_method.channel_listings.first()
+ )
is_valid_method = clean_delivery_method(checkout_info, lines, delivery_method)
assert is_valid_method is True
@@ -122,7 +125,6 @@ def test_update_checkout_shipping_method_if_invalid(
assert checkout.shipping_method is None
assert checkout_info.delivery_method_info.delivery_method is None
- assert checkout_info.shipping_method_channel_listings is None
# Ensure the checkout's shipping method was saved
checkout.refresh_from_db(fields=["shipping_method"])
@@ -1587,16 +1589,45 @@ def test_checkout_available_payment_gateways_currency_specified_EUR(
)
-GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS = """
+GET_CHECKOUT_SELECTED_SHIPPING_METHOD = """
query getCheckout($token: UUID!) {
checkout(token: $token) {
- availableShippingMethods {
+ shippingMethod {
+ id
name
+ description
price {
amount
}
- translation (languageCode: PL) {
+ translation(languageCode: PL) {
name
+ description
+ }
+ minimumOrderPrice {
+ amount
+ }
+ maximumOrderPrice {
+ amount
+ }
+ minimumOrderWeight {
+ unit
+ value
+ }
+ maximumOrderWeight {
+ unit
+ value
+ }
+ message
+ active
+ minimumDeliveryDays
+ maximumDeliveryDays
+ metadata {
+ key
+ value
+ }
+ metadata {
+ key
+ value
}
}
}
@@ -1604,20 +1635,204 @@ query getCheckout($token: UUID!) {
"""
-def test_checkout_available_shipping_methods(
+def test_checkout_selected_shipping_method(
api_client, checkout_with_item, address, shipping_zone
):
checkout_with_item.shipping_address = address
checkout_with_item.save()
- query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS
+ 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"
+ description = dummy_editorjs(raw_description)
+ shipping_method.description = description
+ shipping_method.store_value_in_metadata({metadata_key: metadata_value})
+ shipping_method.save()
+ translated_name = "Dostawa ekspresowa"
+ 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
variables = {"token": checkout_with_item.token}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
shipping_method = shipping_zone.shipping_methods.first()
- assert data["availableShippingMethods"][0]["name"] == shipping_method.name
+ # then
+ assert data["shippingMethod"]["id"] == (
+ graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ )
+ assert data["shippingMethod"]["name"] == shipping_method.name
+ assert raw_description in data["shippingMethod"]["description"]
+ assert data["shippingMethod"]["active"]
+ assert data["shippingMethod"]["message"] == ""
+ assert (
+ data["shippingMethod"]["minimumDeliveryDays"]
+ == shipping_method.minimum_delivery_days
+ )
+ assert (
+ 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"]["metadata"][0]["key"] == metadata_key
+ assert data["shippingMethod"]["metadata"][0]["value"] == metadata_value
+ assert data["shippingMethod"]["translation"]["name"] == translated_name
+
+
+GET_CHECKOUT_SELECTED_SHIPPING_METHOD_PRIVATE_FIELDS = """
+query getCheckout($token: UUID!) {
+ checkout(token: $token) {
+ shippingMethod {
+ id
+ privateMetadata {
+ key
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def test_checkout_selected_shipping_method_as_staff(
+ staff_api_client, checkout_with_item, shipping_zone, permission_manage_shipping
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ shipping_method = shipping_zone.shipping_methods.first()
+ 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.save()
+
+ # when
+ query = GET_CHECKOUT_SELECTED_SHIPPING_METHOD_PRIVATE_FIELDS
+ variables = {"token": checkout_with_item.token}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ response_metadata = data["shippingMethod"]["privateMetadata"][0]
+ assert response_metadata["key"] == metadata_key
+ assert response_metadata["value"] == metadata_value
+
+
+GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS_TEMPLATE = """
+query getCheckout($token: UUID!) {
+ checkout(token: $token) {
+ %s {
+ id
+ type
+ name
+ description
+ price {
+ amount
+ }
+ translation(languageCode: PL) {
+ name
+ description
+ }
+ minimumOrderPrice {
+ amount
+ }
+ maximumOrderPrice {
+ amount
+ }
+ minimumOrderWeight {
+ unit
+ value
+ }
+ maximumOrderWeight {
+ unit
+ value
+ }
+ message
+ active
+ minimumDeliveryDays
+ maximumDeliveryDays
+ metadata {
+ key
+ value
+ }
+ }
+ }
+}
+"""
+
+GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS = (
+ GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS_TEMPLATE % "availableShippingMethods"
+)
+
+
[email protected]("field", ["availableShippingMethods", "shippingMethods"])
+def test_checkout_available_shipping_methods(
+ api_client, checkout_with_item, address, shipping_zone, 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"
+ description = dummy_editorjs(raw_description)
+ shipping_method.description = description
+ shipping_method.store_value_in_metadata({metadata_key: metadata_value})
+ shipping_method.save()
+ translated_name = "Dostawa ekspresowa"
+ ShippingMethodTranslation.objects.create(
+ language_code="pl", shipping_method=shipping_method, name=translated_name
+ )
+
+ # when
+ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS_TEMPLATE % field
+ variables = {"token": checkout_with_item.token}
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data[field][0]["id"] == (
+ 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 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]["metadata"][0]["key"] == metadata_key
+ assert data[field][0]["metadata"][0]["value"] == metadata_value
+ assert data[field][0]["translation"]["name"] == translated_name
@pytest.mark.parametrize("minimum_order_weight_value", [0, 2, None])
@@ -1759,15 +1974,8 @@ def test_checkout_available_shipping_methods_excluded_postal_codes(
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
- "expected_price_type, expected_price, display_gross_prices",
- (("gross", 13, True), ("net", 10, False)),
-)
def test_checkout_available_shipping_methods_with_price_displayed(
send_webhook_request_sync,
- expected_price_type,
- expected_price,
- display_gross_prices,
monkeypatch,
api_client,
checkout_with_item,
@@ -1777,16 +1985,14 @@ def test_checkout_available_shipping_methods_with_price_displayed(
shipping_app,
):
shipping_method = shipping_zone.shipping_methods.first()
- shipping_price = shipping_method.channel_listings.get(
- channel_id=checkout_with_item.channel_id
- ).price
- taxed_price = TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD"))
- apply_taxes_to_shipping_mock = mock.Mock(return_value=taxed_price)
- monkeypatch.setattr(
- PluginsManager, "apply_taxes_to_shipping", apply_taxes_to_shipping_mock
- )
- site_settings.display_gross_prices = display_gross_prices
- site_settings.save()
+ listing = shipping_zone.shipping_methods.first().channel_listings.first()
+ expected_shipping_price = Money(10, "USD")
+ expected_min_order_price = Money(10, "USD")
+ expected_max_order_price = Money(999, "USD")
+ listing.price = expected_shipping_price
+ listing.minimum_order_price = expected_min_order_price
+ listing.maximum_order_price = expected_max_order_price
+ listing.save()
checkout_with_item.shipping_address = address
checkout_with_item.save()
translated_name = "Dostawa ekspresowa"
@@ -1801,11 +2007,20 @@ def test_checkout_available_shipping_methods_with_price_displayed(
content = get_graphql_content(response)
data = content["data"]["checkout"]
- apply_taxes_to_shipping_mock.assert_called_once_with(
- shipping_price, mock.ANY, checkout_with_item.channel.slug
- )
+ assert len(data["availableShippingMethods"]) == 1
assert data["availableShippingMethods"][0]["name"] == "DHL"
- assert data["availableShippingMethods"][0]["price"]["amount"] == expected_price
+ assert (
+ 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
@@ -3220,10 +3435,10 @@ def test_checkout_shipping_method_update(
mock_clean_shipping,
staff_api_client,
shipping_method,
- checkout_with_item,
+ checkout_with_item_and_shipping_method,
is_valid_shipping_method,
):
- checkout = checkout_with_item
+ 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
@@ -3232,7 +3447,7 @@ def test_checkout_shipping_method_update(
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
response = staff_api_client.post_graphql(
- query, {"token": checkout_with_item.token, "shippingMethodId": method_id}
+ query, {"token": checkout.token, "shippingMethodId": method_id}
)
data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
checkout.refresh_from_db()
@@ -3241,18 +3456,22 @@ def test_checkout_shipping_method_update(
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
checkout_info.delivery_method_info = get_delivery_method_info(
- convert_to_shipping_method_data(old_shipping_method), None
+ convert_to_shipping_method_data(
+ old_shipping_method, old_shipping_method.channel_listings.first()
+ ),
+ None,
)
- checkout_info.shipping_method_channel_listings = None
mock_clean_shipping.assert_called_once_with(
checkout_info=checkout_info,
lines=lines,
- method=convert_to_shipping_method_data(shipping_method),
+ method=convert_to_shipping_method_data(
+ shipping_method, shipping_method.channel_listings.first()
+ ),
)
errors = data["errors"]
if is_valid_shipping_method:
assert not errors
- assert data["checkout"]["token"] == str(checkout_with_item.token)
+ assert data["checkout"]["token"] == str(checkout.token)
assert checkout.shipping_method == shipping_method
assert checkout.last_change != previous_last_change
else:
@@ -3261,7 +3480,7 @@ def test_checkout_shipping_method_update(
assert (
errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
)
- assert checkout.shipping_method is None
+ assert checkout.shipping_method == old_shipping_method
assert checkout.last_change == previous_last_change
@@ -3328,12 +3547,20 @@ def test_checkout_delivery_method_update(
checkout_with_item_for_cc,
is_valid_delivery_method,
):
+ # given
+ mock_clean_delivery.return_value = is_valid_delivery_method
+
checkout = checkout_with_item_for_cc
- old_delivery_method = getattr(checkout, attribute_name)
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
shipping_method_data = delivery_method
if attribute_name == "shipping_method":
- old_delivery_method = convert_to_shipping_method_data(old_delivery_method)
- shipping_method_data = convert_to_shipping_method_data(delivery_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 = is_valid_delivery_method
@@ -3345,13 +3572,6 @@ def test_checkout_delivery_method_update(
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
- manager = get_plugins_manager()
- lines = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- checkout_info.delivery_method_info = get_delivery_method_info(
- old_delivery_method, None
- )
- checkout_info.shipping_method_channel_listings = None
mock_clean_delivery.assert_called_once_with(
checkout_info=checkout_info, lines=lines, method=shipping_method_data
)
@@ -3366,6 +3586,7 @@ def test_checkout_delivery_method_update(
errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
)
assert checkout.shipping_method is None
+ assert checkout.collection_point is None
@pytest.mark.parametrize("is_valid_delivery_method", (True, False))
diff --git a/saleor/graphql/checkout/tests/test_checkout_digital.py b/saleor/graphql/checkout/tests/test_checkout_digital.py
index beaf4eea47..c0fbcfdbef 100644
--- a/saleor/graphql/checkout/tests/test_checkout_digital.py
+++ b/saleor/graphql/checkout/tests/test_checkout_digital.py
@@ -73,6 +73,9 @@ def test_checkout_has_no_available_shipping_methods(
checkout(token: $token) {
availableShippingMethods {
name
+ price {
+ amount
+ }
}
}
}
diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
index 92efa91159..fd1d14247c 100644
--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
@@ -252,9 +252,15 @@ MUTATION_CHECKOUT_ADD_PROMO_CODE = """
}
availableShippingMethods {
id
+ price {
+ amount
+ }
}
shippingMethod {
id
+ price {
+ amount
+ }
}
}
}
@@ -851,7 +857,7 @@ def test_checkout_add_promo_code_invalidate_shipping_method(
data = _mutate_checkout_add_promo_code(api_client, variables)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
assert data["checkout"]["shippingMethod"] is None
assert shipping_method_id not in data["checkout"]["availableShippingMethods"]
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 8d202a132a..611f430cd2 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -5,12 +5,12 @@ from ...checkout import calculations, models
from ...checkout.utils import (
get_external_shipping_id,
get_valid_collection_points_for_checkout,
- get_valid_shipping_methods_for_checkout,
)
from ...core.exceptions import PermissionDenied
from ...core.permissions import AccountPermissions
from ...core.taxes import zero_taxed_money
from ...core.tracing import traced_resolver
+from ...shipping.interface import ShippingMethodData
from ...shipping.utils import convert_to_shipping_method_data
from ...warehouse.reservations import is_reservation_enabled
from ..account.dataloaders import AddressByIdLoader
@@ -33,7 +33,7 @@ from ..product.dataloaders import (
)
from ..shipping.dataloaders import (
ShippingMethodByIdLoader,
- ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,
+ ShippingMethodChannelListingByChannelSlugLoader,
)
from ..shipping.types import ShippingMethod
from ..utils import get_user_or_app_from_context
@@ -182,7 +182,7 @@ class DeliveryMethod(graphene.Union):
@classmethod
def resolve_type(cls, instance, info):
- if isinstance(instance, ChannelContext):
+ if isinstance(instance, ShippingMethodData):
return ShippingMethod
return super(DeliveryMethod, cls).resolve_type(instance, info)
@@ -191,7 +191,13 @@ class Checkout(CountableDjangoObjectType):
available_shipping_methods = graphene.List(
ShippingMethod,
required=True,
- description="Shipping methods that can be used with this order.",
+ description="Shipping methods that can be used with this checkout.",
+ deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `shippingMethods` instead."),
+ )
+ shipping_methods = graphene.List(
+ ShippingMethod,
+ required=True,
+ description="Shipping methods that can be used with this checkout.",
)
available_collection_points = graphene.List(
graphene.NonNull(Warehouse),
@@ -299,8 +305,8 @@ class Checkout(CountableDjangoObjectType):
def resolve_email(root: models.Checkout, _info):
return root.get_customer_email()
- @staticmethod
- def resolve_shipping_method(root: models.Checkout, info):
+ @classmethod
+ def resolve_shipping_method(cls, root: models.Checkout, info):
external_app_shipping_id = get_external_shipping_id(root)
if external_app_shipping_id:
@@ -310,16 +316,29 @@ class Checkout(CountableDjangoObjectType):
shipping_method_id=external_app_shipping_id,
)
if shipping_method:
- return ChannelContext(
- node=shipping_method, channel_slug=root.channel.slug
- )
+ return shipping_method
if not root.shipping_method_id:
return None
- def wrap_shipping_method_with_channel_context(data):
+ def with_shipping_method_and_channel(data):
shipping_method, channel = data
- return ChannelContext(node=shipping_method, channel_slug=channel.slug)
+
+ def process_listing(listings):
+ for listing in listings:
+ if listing.shipping_method_id == shipping_method.id:
+ shipping_method_channel_listing = listing
+ break
+
+ return convert_to_shipping_method_data(
+ shipping_method, shipping_method_channel_listing # type: ignore
+ )
+
+ return (
+ ShippingMethodChannelListingByChannelSlugLoader(info.context)
+ .load(channel.slug)
+ .then(process_listing)
+ )
shipping_method = ShippingMethodByIdLoader(info.context).load(
root.shipping_method_id
@@ -327,9 +346,14 @@ class Checkout(CountableDjangoObjectType):
channel = ChannelByIdLoader(info.context).load(root.channel_id)
return Promise.all([shipping_method, channel]).then(
- wrap_shipping_method_with_channel_context
+ with_shipping_method_and_channel
)
+ @classmethod
+ @traced_resolver
+ def resolve_shipping_methods(cls, root: models.Checkout, info):
+ return cls.resolve_available_shipping_methods(root, info)
+
@staticmethod
def resolve_delivery_method(root: models.Checkout, info):
external_app_shipping_id = get_external_shipping_id(root)
@@ -442,102 +466,21 @@ class Checkout(CountableDjangoObjectType):
@staticmethod
@traced_resolver
- # TODO: We should optimize it in/after PR#5819
def resolve_available_shipping_methods(root: models.Checkout, info):
- def calculate_available_shipping_methods(data):
- address, lines, checkout_info, discounts, channel = data
- channel_slug = channel.slug
- display_gross = info.context.site.settings.display_gross_prices
- manager = info.context.plugins
- subtotal = manager.calculate_checkout_subtotal(
- checkout_info, lines, address, discounts
- )
- subtotal -= checkout_info.checkout.discount
- if not address:
- return []
- available = get_valid_shipping_methods_for_checkout(
- checkout_info,
- lines,
- subtotal=subtotal,
- country_code=address.country.code,
- )
- if available is None:
- return []
- available_ids = available.values_list("id", flat=True)
-
- def map_shipping_method_with_channel(shippings):
- def apply_price_to_shipping_method(channel_listings):
- channel_listing_map = {
- channel_listing.shipping_method_id: channel_listing
- for channel_listing in channel_listings
- }
- available_with_channel_context = []
- for shipping in shippings:
- shipping_channel_listing = channel_listing_map[shipping.id]
- taxed_price = info.context.plugins.apply_taxes_to_shipping(
- shipping_channel_listing.price, address, channel_slug
- )
- if display_gross:
- shipping.price = taxed_price.gross
- else:
- shipping.price = taxed_price.net
-
- node = convert_to_shipping_method_data(shipping)
- available_with_channel_context.append(
- ChannelContext(node=node, channel_slug=channel_slug)
- )
- return available_with_channel_context
-
- map_shipping_method_and_channel = (
- (shipping_method_id, channel_slug)
- for shipping_method_id in available_ids
- )
- return (
- ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
- info.context
- )
- .load_many(map_shipping_method_and_channel)
- .then(apply_price_to_shipping_method)
- )
-
- return (
- ShippingMethodByIdLoader(info.context)
- .load_many(available_ids)
- .then(map_shipping_method_with_channel)
- )
-
channel = ChannelByIdLoader(info.context).load(root.channel_id)
- address = (
- AddressByIdLoader(info.context).load(root.shipping_address_id)
- if root.shipping_address_id
- else None
- )
lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
discounts = DiscountsByDateTimeLoader(info.context).load(
info.context.request_time
)
- shipping_methods = Promise.all(
- [address, lines, checkout_info, discounts, channel]
- ).then(calculate_available_shipping_methods)
-
- def with_external_shipping_methods(shipping_methods):
- external_shipping_methods = (
- info.context.plugins.list_shipping_methods_for_checkout(
- checkout=root, channel_slug=root.channel.slug
- )
- )
-
- if external_shipping_methods:
- shipping_methods += [
- ChannelContext(node=shipping, channel_slug=root.channel.slug)
- for shipping in external_shipping_methods
- ]
-
- return shipping_methods
+ def calculate_available_shipping_methods(data):
+ lines, checkout_info, discounts, channel = data
+ return checkout_info.valid_shipping_methods
- return shipping_methods.then(with_external_shipping_methods)
+ return Promise.all([lines, checkout_info, discounts, channel]).then(
+ calculate_available_shipping_methods
+ )
@staticmethod
@traced_resolver
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index da36ec0676..1b77f3206e 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -68,8 +68,8 @@ class BaseMetadataMutation(BaseMutation):
)
}
)
- # ShippingMethod type isn't model-based class
- if type_name == "ShippingMethod":
+ # ShippingMethodType represents the ShippingMethod model
+ if type_name == "ShippingMethodType":
qs = shipping_models.ShippingMethod.objects
return cls.get_node_or_error(info, object_id, qs=qs)
except GraphQLError as e:
@@ -138,7 +138,7 @@ class BaseMetadataMutation(BaseMutation):
@classmethod
def get_model_for_type_name(cls, info, type_name):
- if type_name == "ShippingMethod":
+ if type_name in ["ShippingMethodType", "ShippingMethod"]:
return shipping_models.ShippingMethod
graphene_type = info.schema.get_type(type_name).graphene_type
return graphene_type._meta.model
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index 857843103e..d3d0494b82 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -144,7 +144,7 @@ PUBLIC_META_PERMISSION_MAP = {
"ProductType": product_type_permissions,
"ProductVariant": product_permissions,
"Sale": discount_permissions,
- "ShippingMethod": shipping_permissions,
+ "ShippingMethodType": shipping_permissions,
"ShippingZone": shipping_permissions,
"User": public_user_permissions,
"Voucher": discount_permissions,
@@ -173,6 +173,7 @@ PRIVATE_META_PERMISSION_MAP = {
"ProductVariant": product_permissions,
"Sale": discount_permissions,
"ShippingMethod": shipping_permissions,
+ "ShippingMethodType": shipping_permissions,
"ShippingZone": shipping_permissions,
"User": private_user_permissions,
"Voucher": discount_permissions,
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index e47b1a35cc..ba59c71526 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -1,3 +1,4 @@
+import dataclasses
from operator import itemgetter
from ...account import models as account_models
@@ -13,12 +14,13 @@ from ...page import models as page_models
from ...payment import models as payment_models
from ...product import models as product_models
from ...shipping import models as shipping_models
+from ...shipping.interface import ShippingMethodData
from ...warehouse import models as warehouse_models
from ..utils import get_user_or_app_from_context
from .permissions import PRIVATE_META_PERMISSION_MAP
-def resolve_object_with_metadata_type(instance: ModelWithMetadata):
+def resolve_object_with_metadata_type(instance):
# Imports inside resolvers to avoid circular imports.
from ...invoice import models as invoice_models
from ...menu import models as menu_models
@@ -37,33 +39,38 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
from ..shipping import types as shipping_types
from ..warehouse import types as warehouse_types
- MODEL_TO_TYPE_MAP = {
- app_models.App: app_types.App,
- attribute_models.Attribute: attribute_types.Attribute,
- product_models.Category: product_types.Category,
- checkout_models.Checkout: checkout_types.Checkout,
- product_models.Collection: product_types.Collection,
- product_models.DigitalContent: product_types.DigitalContent,
- order_models.Fulfillment: order_types.Fulfillment,
- giftcard_models.GiftCard: giftcard_types.GiftCard,
- order_models.Order: order_types.Order,
- invoice_models.Invoice: invoice_types.Invoice,
- page_models.Page: page_types.Page,
- page_models.PageType: page_types.PageType,
- payment_models.Payment: payment_types.Payment,
- product_models.Product: product_types.Product,
- product_models.ProductType: product_types.ProductType,
- product_models.ProductVariant: product_types.ProductVariant,
- menu_models.Menu: menu_types.Menu,
- menu_models.MenuItem: menu_types.MenuItem,
- shipping_models.ShippingMethod: shipping_types.ShippingMethod,
- shipping_models.ShippingZone: shipping_types.ShippingZone,
- account_models.User: account_types.User,
- warehouse_models.Warehouse: warehouse_types.Warehouse,
- discount_models.Sale: discount_types.Sale,
- discount_models.Voucher: discount_types.Voucher,
- }
- return MODEL_TO_TYPE_MAP.get(instance.__class__, None)
+ if isinstance(instance, ModelWithMetadata):
+ MODEL_TO_TYPE_MAP = {
+ app_models.App: app_types.App,
+ attribute_models.Attribute: attribute_types.Attribute,
+ product_models.Category: product_types.Category,
+ checkout_models.Checkout: checkout_types.Checkout,
+ product_models.Collection: product_types.Collection,
+ product_models.DigitalContent: product_types.DigitalContent,
+ order_models.Fulfillment: order_types.Fulfillment,
+ giftcard_models.GiftCard: giftcard_types.GiftCard,
+ order_models.Order: order_types.Order,
+ invoice_models.Invoice: invoice_types.Invoice,
+ page_models.Page: page_types.Page,
+ page_models.PageType: page_types.PageType,
+ payment_models.Payment: payment_types.Payment,
+ product_models.Product: product_types.Product,
+ product_models.ProductType: product_types.ProductType,
+ product_models.ProductVariant: product_types.ProductVariant,
+ menu_models.Menu: menu_types.Menu,
+ menu_models.MenuItem: menu_types.MenuItem,
+ shipping_models.ShippingMethod: shipping_types.ShippingMethodType,
+ shipping_models.ShippingZone: shipping_types.ShippingZone,
+ account_models.User: account_types.User,
+ warehouse_models.Warehouse: warehouse_types.Warehouse,
+ discount_models.Sale: discount_types.Sale,
+ discount_models.Voucher: discount_types.Voucher,
+ }
+ return MODEL_TO_TYPE_MAP.get(instance.__class__, None), instance.pk
+
+ elif dataclasses.is_dataclass(instance):
+ DATACLASS_TO_TYPE_MAP = {ShippingMethodData: shipping_types.ShippingMethod}
+ return DATACLASS_TO_TYPE_MAP.get(instance.__class__, None), instance.id
def resolve_metadata(metadata: dict):
@@ -74,7 +81,7 @@ def resolve_metadata(metadata: dict):
def resolve_private_metadata(root: ModelWithMetadata, info):
- item_type = resolve_object_with_metadata_type(root)
+ item_type, item_id = resolve_object_with_metadata_type(root)
if not item_type:
raise NotImplementedError(
f"Model {type(root)} can't be mapped to type with metadata. "
@@ -85,7 +92,7 @@ def resolve_private_metadata(root: ModelWithMetadata, info):
if not get_required_permission:
raise PermissionDenied()
- required_permission = get_required_permission(info, root.pk)
+ required_permission = get_required_permission(info, item_id)
if not required_permission:
raise PermissionDenied()
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index f0ee6df8eb..889d7daa1f 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -653,7 +653,7 @@ def test_add_public_metadata_for_shipping_method(
):
# given
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
# when
@@ -661,7 +661,7 @@ def test_add_public_metadata_for_shipping_method(
staff_api_client,
permission_manage_shipping,
shipping_method_id,
- "ShippingMethod",
+ "ShippingMethodType",
)
# then
@@ -1459,7 +1459,7 @@ def test_delete_public_metadata_for_shipping_method(
shipping_method.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
shipping_method.save(update_fields=["metadata"])
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
# when
@@ -1467,7 +1467,7 @@ def test_delete_public_metadata_for_shipping_method(
staff_api_client,
permission_manage_shipping,
shipping_method_id,
- "ShippingMethod",
+ "ShippingMethodType",
)
# then
@@ -2249,7 +2249,7 @@ def test_add_private_metadata_for_shipping_method(
):
# given
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
# when
@@ -2257,7 +2257,7 @@ def test_add_private_metadata_for_shipping_method(
staff_api_client,
permission_manage_shipping,
shipping_method_id,
- "ShippingMethod",
+ "ShippingMethodType",
)
# then
@@ -3127,7 +3127,7 @@ def test_delete_private_metadata_for_shipping_method(
shipping_method.store_value_in_private_metadata({PUBLIC_KEY: PUBLIC_VALUE})
shipping_method.save(update_fields=["metadata"])
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
# when
@@ -3135,7 +3135,7 @@ def test_delete_private_metadata_for_shipping_method(
staff_api_client,
permission_manage_shipping,
shipping_method_id,
- "ShippingMethod",
+ "ShippingMethodType",
)
# then
diff --git a/saleor/graphql/meta/types.py b/saleor/graphql/meta/types.py
index 16cba9d967..5d623c28e8 100644
--- a/saleor/graphql/meta/types.py
+++ b/saleor/graphql/meta/types.py
@@ -44,4 +44,5 @@ class ObjectWithMetadata(graphene.Interface):
if isinstance(instance, ChannelContext):
# Return instance for types that use ChannelContext
instance = instance.node
- return resolve_object_with_metadata_type(instance)
+ item_type, _ = resolve_object_with_metadata_type(instance)
+ return item_type
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 2211b8c8a3..b0619b305e 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -35,6 +35,8 @@ from ....order.utils import (
)
from ....payment import PaymentError, TransactionKind, gateway
from ....shipping import models as shipping_models
+from ....shipping.interface import ShippingMethodData
+from ....shipping.utils import convert_to_shipping_method_data
from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelMutation
from ...core.scalars import PositiveDecimal
@@ -56,27 +58,30 @@ from ..utils import (
ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)
-def clean_order_update_shipping(order, method):
+def clean_order_update_shipping(order, method: ShippingMethodData):
if not order.shipping_address:
raise ValidationError(
{
"order": ValidationError(
"Cannot choose a shipping method for an order without "
"the shipping address.",
- code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS,
+ code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value,
)
}
)
- valid_methods = get_valid_shipping_methods_for_order(order)
- if valid_methods is None or method.pk not in valid_methods.values_list(
- "id", flat=True
- ):
+ valid_methods_ids = {
+ method.id
+ for method in get_valid_shipping_methods_for_order(
+ order, order.channel.shipping_method_listings.all()
+ )
+ }
+ if valid_methods_ids is None or method.id not in valid_methods_ids:
raise ValidationError(
{
"shipping_method": ValidationError(
"Shipping method cannot be used with this order.",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE,
+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
}
)
@@ -300,7 +305,9 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
info,
data.get("id"),
only_type=Order,
- qs=models.Order.objects.prefetch_related("lines"),
+ qs=models.Order.objects.prefetch_related(
+ "lines", "channel__shipping_method_listings"
+ ),
)
cls.validate_order(order)
@@ -362,8 +369,14 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"postal_code_rules"
),
)
-
- clean_order_update_shipping(order, method)
+ shipping_method_data = convert_to_shipping_method_data(
+ method,
+ shipping_models.ShippingMethodChannelListing.objects.filter(
+ shipping_method=method,
+ channel=order.channel,
+ ).first(),
+ )
+ clean_order_update_shipping(order, shipping_method_data)
order.shipping_method = method
shipping_price = info.context.plugins.calculate_order_shipping(order)
diff --git a/saleor/graphql/order/tests/benchmark/test_order.py b/saleor/graphql/order/tests/benchmark/test_order.py
index e8f3b8d313..859d83df3a 100644
--- a/saleor/graphql/order/tests/benchmark/test_order.py
+++ b/saleor/graphql/order/tests/benchmark/test_order.py
@@ -18,7 +18,7 @@ FRAGMENT_DISCOUNTS = """
}
"""
-FRAGMENT_AVAILABLE_SHIPPING_METHODS = """
+FRAGMENT_SHIPPING_METHODS = """
fragment AvailableShippingMethods on ShippingMethod {
id
price {
@@ -28,7 +28,6 @@ FRAGMENT_AVAILABLE_SHIPPING_METHODS = """
amount
currency
}
- type
}
"""
@@ -36,7 +35,7 @@ FRAGMENT_ORDER_DETAILS = (
FRAGMENT_ADDRESS
+ FRAGMENT_PRODUCT_VARIANT
+ FRAGMENT_DISCOUNTS
- + FRAGMENT_AVAILABLE_SHIPPING_METHODS
+ + FRAGMENT_SHIPPING_METHODS
+ """
fragment OrderDetail on Order {
userEmail
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 6f19added1..5534a5957c 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -341,14 +341,77 @@ query OrdersQuery {
}
availableShippingMethods {
id
- price {
- amount
+ name
+ description
+ price{
+ amount
}
minimumOrderPrice {
+ amount
+ }
+ maximumOrderPrice{
+ amount
+ }
+ maximumDeliveryDays
+ minimumDeliveryDays
+ metadata{
+ key
+ value
+ }
+ privateMetadata{
+ key
+ value
+ }
+ }
+ shippingMethods{
+ id
+ name
+ description
+ price{
+ amount
+ }
+ maximumOrderPrice{
+ amount
+ }
+ minimumOrderPrice{
+ amount
+ }
+ maximumDeliveryDays
+ minimumDeliveryDays
+ metadata{
+ key
+ value
+ }
+ privateMetadata{
+ key
+ value
+ }
+ }
+ shippingMethod{
+ id
+ name
+ description
+ active
+ message
+ price{
amount
- currency
}
- type
+ maximumOrderPrice{
+ amount
+ }
+ minimumOrderPrice{
+ amount
+ }
+ maximumDeliveryDays
+ minimumDeliveryDays
+ metadata{
+ key
+ value
+ }
+ privateMetadata{
+ key
+ value
+ }
}
availableCollectionPoints {
id
@@ -380,7 +443,11 @@ query OrdersQuery {
def test_order_query(
- staff_api_client, permission_manage_orders, fulfilled_order, shipping_zone
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+ shipping_zone,
):
# given
order = fulfilled_order
@@ -390,9 +457,15 @@ def test_order_query(
order.shipping_price = shipping_price
shipping_tax_rate = Decimal("0.23")
order.shipping_tax_rate = shipping_tax_rate
+ private_value = "abc123"
+ public_value = "123abc"
+ order.shipping_method.store_value_in_metadata({"test": public_value})
+ order.shipping_method.store_value_in_private_metadata({"test": private_value})
+ order.shipping_method.save()
order.save()
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY)
@@ -419,9 +492,14 @@ def test_order_query(
)
assert expected_price == shipping_price.gross
assert order_data["shippingTaxRate"] == float(shipping_tax_rate)
+ assert order_data["shippingMethod"]["active"] is True
+ assert order_data["shippingMethod"]["message"] == ""
+ assert public_value == order_data["shippingMethod"]["metadata"][0]["value"]
+ assert private_value == order_data["shippingMethod"]["privateMetadata"][0]["value"]
assert len(order_data["lines"]) == order.lines.count()
fulfillment = order.fulfillments.first().fulfillment_order
fulfillment_order = order_data["fulfillments"][0]["fulfillmentOrder"]
+
assert fulfillment_order == fulfillment
assert len(order_data["payments"]) == order.payments.count()
@@ -450,13 +528,13 @@ def test_order_query(
assert float(expected_shipping_price.minimum_order_price.amount) == (
method["minimumOrderPrice"]["amount"]
)
- assert expected_method.type.upper() == method["type"]
assert order_data["deliveryMethod"]["id"] == order_data["shippingMethod"]["id"]
def test_order_query_shipping_method_channel_listing_does_not_exist(
staff_api_client,
permission_manage_orders,
+ permission_manage_shipping,
order_with_lines,
):
# given
@@ -470,6 +548,7 @@ def test_order_query_shipping_method_channel_listing_does_not_exist(
).delete()
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY)
@@ -477,14 +556,13 @@ def test_order_query_shipping_method_channel_listing_does_not_exist(
# then
order_data = content["data"]["orders"]["edges"][0]["node"]
- assert order_data["shippingMethod"]["id"] == graphene.Node.to_global_id(
- "ShippingMethod", order.shipping_method.id
- )
+ assert order_data["shippingMethod"] is None
def test_order_query_external_shipping_method(
staff_api_client,
permission_manage_orders,
+ permission_manage_shipping,
order_with_lines,
):
external_shipping_method_id = graphene.Node.to_global_id("app", "1:external123")
@@ -496,6 +574,7 @@ def test_order_query_external_shipping_method(
order.save()
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY)
@@ -513,6 +592,7 @@ def test_order_query_external_shipping_method(
def test_order_discounts_query(
staff_api_client,
permission_manage_orders,
+ permission_manage_shipping,
draft_order_with_fixed_discount_order,
):
# given
@@ -523,6 +603,7 @@ def test_order_discounts_query(
discount = order.discounts.get()
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY)
@@ -544,6 +625,7 @@ def test_order_discounts_query(
def test_order_line_discount_query(
staff_api_client,
permission_manage_orders,
+ permission_manage_shipping,
draft_order_with_fixed_discount_order,
):
# given
@@ -560,6 +642,7 @@ def test_order_line_discount_query(
line_with_discount_id = graphene.Node.to_global_id("OrderLine", line.pk)
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY)
@@ -602,6 +685,7 @@ def test_order_line_discount_query(
def test_order_query_in_pln_channel(
staff_api_client,
permission_manage_orders,
+ permission_manage_shipping,
order_with_lines_channel_PLN,
shipping_zone,
channel_PLN,
@@ -609,6 +693,7 @@ def test_order_query_in_pln_channel(
shipping_zone.channels.add(channel_PLN)
order = order_with_lines_channel_PLN
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
response = staff_api_client.post_graphql(ORDERS_QUERY)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -650,7 +735,6 @@ def test_order_query_in_pln_channel(
assert float(expected_shipping_price.minimum_order_price.amount) == (
method["minimumOrderPrice"]["amount"]
)
- assert expected_method.type.upper() == method["type"]
ORDERS_QUERY_SHIPPING_METHODS = """
@@ -660,6 +744,9 @@ ORDERS_QUERY_SHIPPING_METHODS = """
node {
availableShippingMethods {
name
+ price {
+ amount
+ }
}
}
}
@@ -789,20 +876,11 @@ def test_order_query_shipping_methods_excluded_postal_codes(
assert order_data["availableShippingMethods"] == []
- "expected_price_type, expected_price, display_gross_prices",
- (("gross", 13, True), ("net", 10, False)),
-)
def test_order_available_shipping_methods_query(
- expected_price_type,
- expected_price,
- display_gross_prices,
- monkeypatch,
staff_api_client,
permission_manage_orders,
fulfilled_order,
shipping_zone,
- site_settings,
):
query = """
query OrdersQuery {
@@ -814,7 +892,6 @@ def test_order_available_shipping_methods_query(
price {
amount
}
- type
}
}
}
@@ -825,13 +902,6 @@ def test_order_available_shipping_methods_query(
shipping_price = shipping_method.channel_listings.get(
channel_id=fulfilled_order.channel_id
).price
- taxed_price = TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD"))
- apply_taxes_to_shipping_mock = Mock(return_value=taxed_price)
- monkeypatch.setattr(
- PluginsManager, "apply_taxes_to_shipping", apply_taxes_to_shipping_mock
- )
- site_settings.display_gross_prices = display_gross_prices
- site_settings.save()
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(query)
@@ -839,10 +909,7 @@ def test_order_available_shipping_methods_query(
order_data = content["data"]["orders"]["edges"][0]["node"]
method = order_data["availableShippingMethods"][0]
- apply_taxes_to_shipping_mock.assert_called_once_with(
- shipping_price, ANY, fulfilled_order.channel.slug
- )
- assert expected_price == method["price"]["amount"]
+ assert shipping_price.amount == method["price"]["amount"]
def test_order_query_customer(api_client):
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 67ac5ed10d..62d90fac33 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1,3 +1,4 @@
+import logging
from decimal import Decimal
from operator import attrgetter
from typing import Optional
@@ -20,7 +21,6 @@ from ...core.permissions import (
ProductPermissions,
has_one_of_permissions,
)
-from ...core.taxes import display_gross_prices
from ...core.tracing import traced_resolver
from ...discount import OrderDiscountType
from ...graphql.checkout.types import DeliveryMethod
@@ -44,6 +44,8 @@ from ...product import ProductMediaTypes
from ...product.models import ALL_PRODUCTS_PERMISSIONS
from ...product.product_images import get_product_image_thumbnail
from ...shipping.interface import ShippingMethodData
+from ...shipping.models import ShippingMethodChannelListing
+from ...shipping.utils import convert_to_shipping_method_data
from ..account.dataloaders import AddressByIdLoader, UserByUserIdLoader
from ..account.types import User
from ..account.utils import requestor_has_access
@@ -74,7 +76,11 @@ from ..product.dataloaders import (
ProductVariantByIdLoader,
)
from ..product.types import ProductVariant
-from ..shipping.dataloaders import ShippingMethodByIdLoader
+from ..shipping.dataloaders import (
+ ShippingMethodByIdLoader,
+ ShippingMethodChannelListingByChannelSlugLoader,
+ ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,
+)
from ..shipping.types import ShippingMethod
from ..warehouse.types import Allocation, Warehouse
from .dataloaders import (
@@ -89,6 +95,8 @@ from .dataloaders import (
from .enums import OrderEventsEmailsEnum, OrderEventsEnum, OrderOriginEnum
from .utils import validate_draft_order
+logger = logging.getLogger(__name__)
+
def get_order_discount_event(discount_obj: dict):
currency = discount_obj["currency"]
@@ -626,6 +634,10 @@ class Order(CountableDjangoObjectType):
ShippingMethod,
required=False,
description="Shipping methods that can be used with this order.",
+ deprecation_reason="Use `shippingMethods`, this field will be removed in 4.0",
+ )
+ shipping_methods = graphene.List(
+ ShippingMethod, description="Shipping methods related to this order."
)
available_collection_points = graphene.List(
graphene.NonNull(Warehouse),
@@ -657,15 +669,14 @@ class Order(CountableDjangoObjectType):
TaxedMoney, description="Undiscounted total amount of the order.", required=True
)
+ shipping_price = graphene.Field(
+ TaxedMoney, description="Total price of shipping.", required=True
+ )
shipping_method = graphene.Field(
ShippingMethod,
- description="The shipping method related with order.",
+ description="Shipping method for this order.",
deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `deliveryMethod` instead."),
)
-
- shipping_price = graphene.Field(
- TaxedMoney, description="Total price of shipping.", required=True
- )
subtotal = graphene.Field(
TaxedMoney,
description="The sum of line prices not including shipping.",
@@ -1064,19 +1075,27 @@ class Order(CountableDjangoObjectType):
if external_app_shipping_id:
keep_gross = info.context.site.settings.include_taxes_in_prices
price = root.shipping_price_gross if keep_gross else root.shipping_price_net
- method = ShippingMethodData(
+ return ShippingMethodData(
id=external_app_shipping_id,
name=root.shipping_method_name,
price=price,
)
- return ChannelContext(node=method, channel_slug=root.channel.slug)
if not root.shipping_method_id:
return None
def wrap_shipping_method_with_channel_context(data):
shipping_method, channel = data
- return ChannelContext(node=shipping_method, channel_slug=channel.slug)
+ listing = (
+ ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
+ info.context
+ ).load((shipping_method.id, channel.slug))
+ )
+
+ def calculate_price(listing: Optional[ShippingMethodChannelListing]):
+ return convert_to_shipping_method_data(shipping_method, listing)
+
+ return listing.then(calculate_price)
shipping_method = ShippingMethodByIdLoader(info.context).load(
root.shipping_method_id
@@ -1098,40 +1117,29 @@ class Order(CountableDjangoObjectType):
return collection_point
return None
- @staticmethod
+ @classmethod
@traced_resolver
# TODO: We should optimize it in/after PR#5819
- def resolve_available_shipping_methods(root: models.Order, info):
- instances = []
- manager = info.context.plugins
- available = get_valid_shipping_methods_for_order(root)
- if available is not None:
- available_shipping_methods = []
- display_gross = display_gross_prices()
- channel_slug = root.channel.slug
- for shipping_method in available:
- # Ignore typing check because it is checked in
- # get_valid_shipping_methods_for_order
- shipping_channel_listing = shipping_method.channel_listings.filter(
- channel=root.channel
- ).first()
- if shipping_channel_listing:
- taxed_price = manager.apply_taxes_to_shipping(
- shipping_channel_listing.price,
- root.shipping_address, # type: ignore
- channel_slug,
- )
- if display_gross:
- shipping_method.price = taxed_price.gross
- else:
- shipping_method.price = taxed_price.net
- available_shipping_methods.append(shipping_method)
- instances = [
- ChannelContext(node=shipping, channel_slug=channel_slug)
- for shipping in available_shipping_methods
- ]
-
- return instances
+ def resolve_shipping_methods(cls, root: models.Order, info):
+ def with_channel(channel):
+ def with_listings(channel_listings):
+ return get_valid_shipping_methods_for_order(root, channel_listings)
+
+ return (
+ ShippingMethodChannelListingByChannelSlugLoader(info.context)
+ .load(channel.slug)
+ .then(with_listings)
+ )
+
+ return ChannelByIdLoader(info.context).load(root.channel_id).then(with_channel)
+
+ @classmethod
+ @traced_resolver
+ # TODO: We should optimize it in/after PR#5819
+ def resolve_available_shipping_methods(cls, root: models.Order, info):
+ return cls.resolve_shipping_methods(root, info).then(
+ lambda methods: [method for method in methods if method.active]
+ )
@classmethod
@traced_resolver
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 221c22489c..b37333da80 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1022,7 +1022,8 @@ type Checkout implements Node & ObjectWithMetadata {
id: ID!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
- availableShippingMethods: [ShippingMethod]!
+ availableShippingMethods: [ShippingMethod]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `shippingMethods` instead.")
+ shippingMethods: [ShippingMethod]!
availableCollectionPoints: [Warehouse!]!
availablePaymentGateways: [PaymentGateway!]!
email: String
@@ -4154,7 +4155,8 @@ type Order implements Node & ObjectWithMetadata {
fulfillments: [Fulfillment]!
lines: [OrderLine]!
actions: [OrderAction]!
- availableShippingMethods: [ShippingMethod]
+ availableShippingMethods: [ShippingMethod] @deprecated(reason: "Use `shippingMethods`, this field will be removed in 4.0")
+ shippingMethods: [ShippingMethod]
availableCollectionPoints: [Warehouse!]!
invoices: [Invoice]
number: String
@@ -6279,20 +6281,19 @@ type ShippingMethod implements Node & ObjectWithMetadata {
id: ID!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
+ type: ShippingMethodTypeEnum @deprecated(reason: "This field will be removed in Saleor 4.0.")
name: String!
description: JSONString
- type: ShippingMethodTypeEnum
+ maximumDeliveryDays: Int
+ minimumDeliveryDays: Int
+ maximumOrderWeight: Weight @deprecated(reason: "This field will be removed in Saleor 4.0.")
+ minimumOrderWeight: Weight @deprecated(reason: "This field will be removed in Saleor 4.0.")
translation(languageCode: LanguageCodeEnum!): ShippingMethodTranslation
- channelListings: [ShippingMethodChannelListing!]
- price: Money
+ price: Money!
maximumOrderPrice: Money
minimumOrderPrice: Money
- postalCodeRules: [ShippingMethodPostalCodeRule]
- excludedProducts(before: String, after: String, first: Int, last: Int): ProductCountableConnection
- minimumOrderWeight: Weight
- maximumOrderWeight: Weight
- maximumDeliveryDays: Int
- minimumDeliveryDays: Int
+ active: Boolean!
+ message: String
}
type ShippingMethodChannelListing implements Node {
@@ -6316,7 +6317,7 @@ input ShippingMethodChannelListingInput {
}
type ShippingMethodChannelListingUpdate {
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
shippingErrors: [ShippingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ShippingError!]!
}
@@ -6333,7 +6334,7 @@ type ShippingMethodTranslatableContent implements Node {
name: String!
description: JSONString
translation(languageCode: LanguageCodeEnum!): ShippingMethodTranslation
- shippingMethod: ShippingMethod @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")
+ shippingMethod: ShippingMethodType @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")
}
type ShippingMethodTranslation implements Node {
@@ -6343,6 +6344,25 @@ type ShippingMethodTranslation implements Node {
language: LanguageDisplay!
}
+type ShippingMethodType implements Node & ObjectWithMetadata {
+ id: ID!
+ privateMetadata: [MetadataItem]!
+ metadata: [MetadataItem]!
+ name: String!
+ description: JSONString
+ type: ShippingMethodTypeEnum
+ translation(languageCode: LanguageCodeEnum!): ShippingMethodTranslation
+ channelListings: [ShippingMethodChannelListing!]
+ maximumOrderPrice: Money
+ minimumOrderPrice: Money
+ postalCodeRules: [ShippingMethodPostalCodeRule]
+ excludedProducts(before: String, after: String, first: Int, last: Int): ProductCountableConnection
+ minimumOrderWeight: Weight
+ maximumOrderWeight: Weight
+ maximumDeliveryDays: Int
+ minimumDeliveryDays: Int
+}
+
enum ShippingMethodTypeEnum {
PRICE
WEIGHT
@@ -6361,20 +6381,20 @@ type ShippingPriceBulkDelete {
type ShippingPriceCreate {
shippingZone: ShippingZone
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
shippingErrors: [ShippingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ShippingError!]!
}
type ShippingPriceDelete {
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
shippingZone: ShippingZone
shippingErrors: [ShippingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ShippingError!]!
}
type ShippingPriceExcludeProducts {
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
shippingErrors: [ShippingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ShippingError!]!
}
@@ -6398,7 +6418,7 @@ input ShippingPriceInput {
}
type ShippingPriceRemoveProductFromExclude {
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
shippingErrors: [ShippingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ShippingError!]!
}
@@ -6406,7 +6426,7 @@ type ShippingPriceRemoveProductFromExclude {
type ShippingPriceTranslate {
translationErrors: [TranslationError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [TranslationError!]!
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
}
input ShippingPriceTranslationInput {
@@ -6416,7 +6436,7 @@ input ShippingPriceTranslationInput {
type ShippingPriceUpdate {
shippingZone: ShippingZone
- shippingMethod: ShippingMethod
+ shippingMethod: ShippingMethodType
shippingErrors: [ShippingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ShippingError!]!
}
@@ -6429,7 +6449,7 @@ type ShippingZone implements Node & ObjectWithMetadata {
metadata: [MetadataItem]!
priceRange: MoneyRange
countries: [CountryDisplay]
- shippingMethods: [ShippingMethod]
+ shippingMethods: [ShippingMethodType]
warehouses: [Warehouse!]!
channels: [Channel!]!
description: String
diff --git a/saleor/graphql/shipping/bulk_mutations.py b/saleor/graphql/shipping/bulk_mutations.py
index e3a5b47597..182843ba9b 100644
--- a/saleor/graphql/shipping/bulk_mutations.py
+++ b/saleor/graphql/shipping/bulk_mutations.py
@@ -40,5 +40,5 @@ class ShippingPriceBulkDelete(ModelBulkDeleteMutation):
@classmethod
def get_nodes_or_error(cls, ids, field, only_type=None, qs=None):
return super().get_nodes_or_error(
- ids, field, "ShippingMethod", qs=models.ShippingMethod.objects
+ ids, field, "ShippingMethodType", qs=models.ShippingMethod.objects
)
diff --git a/saleor/graphql/shipping/dataloaders.py b/saleor/graphql/shipping/dataloaders.py
index 5a67671193..78440fdf40 100644
--- a/saleor/graphql/shipping/dataloaders.py
+++ b/saleor/graphql/shipping/dataloaders.py
@@ -101,30 +101,50 @@ class ShippingMethodChannelListingByShippingMethodIdLoader(DataLoader):
]
-class ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(DataLoader):
- context_key = "shippingmethodchannellisting_by_shippingmethod_and_channel"
+class ShippingMethodChannelListingByChannelSlugLoader(DataLoader):
+ context_key = "shippingmethodchannellisting_by_channel"
def batch_load(self, keys):
- shipping_method_ids = [key[0] for key in keys]
- channel_slugs = [key[1] for key in keys]
shipping_method_channel_listings = ShippingMethodChannelListing.objects.filter(
- shipping_method_id__in=shipping_method_ids, channel__slug__in=channel_slugs
+ channel__slug__in=keys
).annotate(channel_slug=F("channel__slug"))
- shipping_method_channel_listings_by_shipping_method_and_channel_map = {}
+ shipping_method_channel_listings_by_channel_slug = defaultdict(list)
for shipping_method_channel_listing in shipping_method_channel_listings:
- key = (
- shipping_method_channel_listing.shipping_method_id,
- shipping_method_channel_listing.channel_slug,
- )
- shipping_method_channel_listings_by_shipping_method_and_channel_map[
- key
- ] = shipping_method_channel_listing
+ shipping_method_channel_listings_by_channel_slug[
+ shipping_method_channel_listing.channel_slug
+ ].append(shipping_method_channel_listing)
return [
- shipping_method_channel_listings_by_shipping_method_and_channel_map.get(key)
- for key in keys
+ shipping_method_channel_listings_by_channel_slug.get(channel_slug, [])
+ for channel_slug in keys
]
+class ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(DataLoader):
+ context_key = "shippingmethodchannellisting_by_shippingmethod_and_channel"
+
+ def batch_load(self, keys):
+ shipping_method_ids = [key[0] for key in keys]
+ channel_slugs = [key[1] for key in keys]
+
+ def _find_listing_by_shipping_method_id(listings_by_channel):
+ listings_by_method = []
+ for method_id, listings in zip(shipping_method_ids, listings_by_channel):
+ for listing in listings:
+ if method_id == listing.shipping_method_id:
+ listings_by_method.append(listing)
+ break
+ else:
+ listings_by_method.append(None)
+
+ return listings_by_method
+
+ return (
+ ShippingMethodChannelListingByChannelSlugLoader(self.context)
+ .load_many(channel_slugs)
+ .then(_find_listing_by_shipping_method_id)
+ )
+
+
class ChannelsByShippingZoneIdLoader(DataLoader):
context_key = "channels_by_shippingzone"
diff --git a/saleor/graphql/shipping/mutations/channels.py b/saleor/graphql/shipping/mutations/channels.py
index 9d023f181d..149cbd6bb1 100644
--- a/saleor/graphql/shipping/mutations/channels.py
+++ b/saleor/graphql/shipping/mutations/channels.py
@@ -17,7 +17,7 @@ from ...core.scalars import PositiveDecimal
from ...core.types.common import ShippingError
from ...core.validators import validate_decimal_max_value, validate_price_precision
from ...shipping.utils import get_shipping_model_by_object_id
-from ..types import ShippingMethod
+from ..types import ShippingMethodType
if TYPE_CHECKING:
from ....shipping.models import ShippingMethod as ShippingMethodModel
@@ -55,7 +55,7 @@ class ShippingMethodChannelListingInput(graphene.InputObjectType):
class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):
shipping_method = graphene.Field(
- ShippingMethod, description="An updated shipping method instance."
+ ShippingMethodType, description="An updated shipping method instance."
)
class Arguments:
diff --git a/saleor/graphql/shipping/mutations/shippings.py b/saleor/graphql/shipping/mutations/shippings.py
index 42388d64e8..a24062b01b 100644
--- a/saleor/graphql/shipping/mutations/shippings.py
+++ b/saleor/graphql/shipping/mutations/shippings.py
@@ -25,7 +25,7 @@ from ...shipping import types as shipping_types
from ...utils import resolve_global_ids_to_primary_keys
from ...utils.validators import check_for_duplicates
from ..enums import PostalCodeRuleInclusionTypeEnum, ShippingMethodTypeEnum
-from ..types import ShippingMethod, ShippingMethodPostalCodeRule, ShippingZone
+from ..types import ShippingMethodPostalCodeRule, ShippingMethodType, ShippingZone
class ShippingPostalCodeRulesCreateInputRange(graphene.InputObjectType):
@@ -260,7 +260,7 @@ class ShippingZoneDelete(ModelDeleteMutation):
class ShippingMethodTypeMixin:
@classmethod
def get_type_for_model(cls):
- return shipping_types.ShippingMethod
+ return shipping_types.ShippingMethodType
@classmethod
def get_instance(cls, info, **data):
@@ -275,6 +275,10 @@ class ShippingMethodTypeMixin:
class ShippingPriceMixin:
+ @classmethod
+ def get_type_for_model(cls):
+ return ShippingMethodType
+
@classmethod
def clean_input(cls, info, instance, data, input_cls=None):
cleaned_input = super().clean_input(info, instance, data)
@@ -433,7 +437,7 @@ class ShippingPriceCreate(ShippingPriceMixin, ShippingMethodTypeMixin, ModelMuta
description="A shipping zone to which the shipping method belongs.",
)
shipping_method = graphene.Field(
- ShippingMethod, description="A shipping method to create."
+ ShippingMethodType, description="A shipping method to create."
)
class Arguments:
@@ -464,7 +468,9 @@ class ShippingPriceUpdate(ShippingPriceMixin, ShippingMethodTypeMixin, ModelMuta
ShippingZone,
description="A shipping zone to which the shipping method belongs.",
)
- shipping_method = graphene.Field(ShippingMethod, description="A shipping method.")
+ shipping_method = graphene.Field(
+ ShippingMethodType, description="A shipping method."
+ )
class Arguments:
id = graphene.ID(description="ID of a shipping price to update.", required=True)
@@ -493,7 +499,7 @@ class ShippingPriceUpdate(ShippingPriceMixin, ShippingMethodTypeMixin, ModelMuta
class ShippingPriceDelete(BaseMutation):
shipping_method = graphene.Field(
- ShippingMethod, description="A shipping method to delete."
+ ShippingMethodType, description="A shipping method to delete."
)
shipping_zone = graphene.Field(
ShippingZone,
@@ -534,7 +540,7 @@ class ShippingPriceExcludeProductsInput(graphene.InputObjectType):
class ShippingPriceExcludeProducts(BaseMutation):
shipping_method = graphene.Field(
- ShippingMethod,
+ ShippingMethodType,
description="A shipping method with new list of excluded products.",
)
@@ -578,7 +584,7 @@ class ShippingPriceExcludeProducts(BaseMutation):
class ShippingPriceRemoveProductFromExclude(BaseMutation):
shipping_method = graphene.Field(
- ShippingMethod,
+ ShippingMethodType,
description="A shipping method with new list of excluded products.",
)
diff --git a/saleor/graphql/shipping/resolvers.py b/saleor/graphql/shipping/resolvers.py
index 2ab406c022..7af0730950 100644
--- a/saleor/graphql/shipping/resolvers.py
+++ b/saleor/graphql/shipping/resolvers.py
@@ -1,7 +1,9 @@
from prices import MoneyRange
from ...shipping import models
+from ...shipping.interface import ShippingMethodData
from ..channel import ChannelQsContext
+from ..translations.resolvers import resolve_translation
def resolve_shipping_zones(channel_slug):
@@ -20,3 +22,9 @@ def resolve_price_range(channel_slug):
prices = [shipping.get_total() for shipping in channel_listing]
return MoneyRange(min(prices), max(prices)) if prices else None
+
+
+def resolve_shipping_translation(root: ShippingMethodData, info, language_code):
+ if root.is_external:
+ return None
+ return resolve_translation(root, info, language_code)
diff --git a/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py b/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
index b400245c06..4835618904 100644
--- a/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
+++ b/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
@@ -27,18 +27,6 @@ query GetShippingMethods($channel: String) {
name
}
}
- price {
- amount
- currency
- }
- maximumOrderPrice {
- currency
- amount
- }
- minimumOrderPrice {
- currency
- amount
- }
}
}
}
@@ -134,7 +122,7 @@ def test_exclude_products_for_shipping_method(
]
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
variables = {
"id": shipping_method_id,
@@ -164,7 +152,7 @@ def test_exclude_products_for_shipping_method_already_has_excluded_products(
permission_manage_shipping,
):
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
shipping_method.excluded_products.add(product, product_list[0])
product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
@@ -220,7 +208,7 @@ def test_remove_products_from_excluded_products_for_shipping_method(
product,
):
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
shipping_method.excluded_products.set(product_list)
shipping_method.excluded_products.add(product)
diff --git a/saleor/graphql/shipping/tests/test_bulk_delete.py b/saleor/graphql/shipping/tests/test_bulk_delete.py
index 3714a8ec82..87fdc9bfe7 100644
--- a/saleor/graphql/shipping/tests/test_bulk_delete.py
+++ b/saleor/graphql/shipping/tests/test_bulk_delete.py
@@ -40,7 +40,7 @@ def test_delete_shipping_methods(
variables = {
"ids": [
- graphene.Node.to_global_id("ShippingMethod", method.id)
+ graphene.Node.to_global_id("ShippingMethodType", method.id)
for method in shipping_method_list
]
}
diff --git a/saleor/graphql/shipping/tests/test_shipping_method.py b/saleor/graphql/shipping/tests/test_shipping_method.py
index ad51971293..ac9c2a2c51 100644
--- a/saleor/graphql/shipping/tests/test_shipping_method.py
+++ b/saleor/graphql/shipping/tests/test_shipping_method.py
@@ -1032,7 +1032,7 @@ def test_update_shipping_method(
shipping_method = shipping_zone.shipping_methods.first()
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
max_del_days = 8
min_del_days = 2
@@ -1066,7 +1066,7 @@ def test_update_shipping_method_postal_codes(
"ShippingZone", shipping_method_excluded_by_postal_code.shipping_zone.pk
)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method_excluded_by_postal_code.pk
+ "ShippingMethodType", shipping_method_excluded_by_postal_code.pk
)
postal_code_rule_id = graphene.Node.to_global_id(
"ShippingMethodPostalCodeRule",
@@ -1103,7 +1103,7 @@ def test_update_shipping_method_minimum_delivery_days_higher_than_maximum(
shipping_method = shipping_zone.shipping_methods.first()
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
max_del_days = 2
min_del_days = 8
@@ -1136,7 +1136,7 @@ def test_update_shipping_method_minimum_delivery_days_below_0(
shipping_method = shipping_zone.shipping_methods.first()
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
max_del_days = 2
min_del_days = -1
@@ -1169,7 +1169,7 @@ def test_update_shipping_method_maximum_delivery_days_below_0(
shipping_method = shipping_zone.shipping_methods.first()
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
max_del_days = -1
min_del_days = 10
@@ -1204,7 +1204,7 @@ def test_update_shipping_method_minimum_delivery_days_higher_than_max_from_insta
shipping_method.save(update_fields=["maximum_delivery_days"])
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
min_del_days = 8
variables = {
@@ -1237,7 +1237,7 @@ def test_update_shipping_method_maximum_delivery_days_lower_than_min_from_instan
shipping_method.save(update_fields=["minimum_delivery_days"])
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
max_del_days = 5
variables = {
@@ -1270,7 +1270,7 @@ def test_update_shipping_method_multiple_errors(
shipping_method.save(update_fields=["minimum_delivery_days"])
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
max_del_days = 5
variables = {
@@ -1319,7 +1319,7 @@ def test_update_shipping_method_delivery_days_without_value(
shipping_method = shipping_zone.shipping_methods.first()
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
variables = {
"shippingZone": shipping_zone_id,
@@ -1361,7 +1361,7 @@ def test_delete_shipping_method(
}
"""
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
shipping_zone_id = graphene.Node.to_global_id(
"ShippingZone", shipping_method.shipping_zone.pk
@@ -1416,7 +1416,7 @@ def test_exclude_products_for_shipping_method_only_products(
):
api = staff_api_client if requestor == "staff" else app_api_client
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
variables = {"id": shipping_method_id, "input": {"products": product_ids}}
@@ -1444,7 +1444,7 @@ def test_exclude_products_for_shipping_method_already_has_excluded_products(
):
api = staff_api_client if requestor == "staff" else app_api_client
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
shipping_method.excluded_products.add(product, product_list[0])
product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
@@ -1501,7 +1501,7 @@ def test_remove_products_from_excluded_products_for_shipping_method_delete_all_p
):
api = staff_api_client if requestor == "staff" else app_api_client
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
shipping_method.excluded_products.set(product_list)
@@ -1536,7 +1536,7 @@ def test_remove_products_from_excluded_products_for_shipping_method(
):
api = staff_api_client if requestor == "staff" else app_api_client
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
shipping_method.excluded_products.set(product_list)
shipping_method.excluded_products.add(product)
diff --git a/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py b/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py
index a0fba2585e..1e8c81542c 100644
--- a/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py
+++ b/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py
@@ -50,7 +50,7 @@ def test_shipping_method_channel_listing_create_as_staff_user(
# given
shipping_method.shipping_zone.channels.add(channel_PLN)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 1
@@ -109,7 +109,7 @@ def test_shipping_method_channel_listing_update_as_staff_user(
):
# given
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
min_value = 20
@@ -179,7 +179,7 @@ def test_shipping_method_channel_listing_update_with_negative_price(
shipping_method.shipping_zone.channels.add(channel_PLN)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = -10
@@ -220,7 +220,7 @@ def test_shipping_method_channel_listing_update_with_negative_min_value(
shipping_method.shipping_zone.channels.add(channel_PLN)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 10
@@ -261,7 +261,7 @@ def test_shipping_method_channel_listing_update_with_negative_max_value(
shipping_method.shipping_zone.channels.add(channel_PLN)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 10
@@ -299,7 +299,7 @@ def test_shipping_method_channel_listing_update_with_max_less_than_min(
# given
shipping_method.shipping_zone.channels.add(channel_PLN)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 1
@@ -344,7 +344,7 @@ def test_shipping_method_channel_listing_create_without_price(
# given
shipping_method.shipping_zone.channels.add(channel_PLN)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
min_value = 10
@@ -387,7 +387,7 @@ def test_shipping_method_channel_listing_update_with_to_many_decimal_places_in_p
# given
shipping_method.shipping_zone.channels.add(channel_PLN)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 10.1234
@@ -432,7 +432,7 @@ def test_shipping_method_channel_listing_update_with_to_many_decimal_places_in_m
# given
shipping_method.shipping_zone.channels.add(channel_PLN)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 10
@@ -477,7 +477,7 @@ def test_shipping_method_channel_listing_update_with_to_many_decimal_places_in_m
# given
shipping_method.shipping_zone.channels.add(channel_PLN)
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 10
@@ -521,7 +521,7 @@ def test_shipping_method_channel_listing_create_channel_not_valid(
):
# given
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
price = 1
@@ -573,7 +573,7 @@ def test_shipping_method_channel_listing_update_remove_channels(
):
# given
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.pk
+ "ShippingMethodType", shipping_method.pk
)
assert shipping_method.channel_listings.count() == 1
channel_listing = shipping_method.channel_listings.first()
diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.py
index 1d9f89a733..84874a2bf1 100644
--- a/saleor/graphql/shipping/types.py
+++ b/saleor/graphql/shipping/types.py
@@ -1,5 +1,3 @@
-from typing import Union
-
import graphene
from graphene import relay
@@ -23,11 +21,12 @@ from ..core.connection import (
CountableDjangoObjectType,
create_connection_slice,
)
+from ..core.descriptions import DEPRECATED_IN_3X_FIELD
from ..core.fields import ConnectionField
from ..core.types import CountryDisplay, Money, MoneyRange, Weight
from ..decorators import permission_required
from ..meta.types import ObjectWithMetadata
-from ..shipping.resolvers import resolve_price_range
+from ..shipping.resolvers import resolve_price_range, resolve_shipping_translation
from ..translations.fields import TranslationField
from ..translations.types import ShippingMethodTranslation
from ..warehouse.types import Warehouse
@@ -78,7 +77,13 @@ class ShippingMethodPostalCodeRule(CountableDjangoObjectType):
]
-class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
+class ShippingMethodType(ChannelContextTypeWithMetadataForObjectType):
+ """Represents internal shipping method managed within Saleor.
+
+ Internal and external (fetched by sync webhooks) shipping methods are later
+ represented by `ShippingMethod` objects as part of orders and checkouts.
+ """
+
id = graphene.ID(required=True, description="Shipping method ID.")
name = graphene.String(required=True, description="Shipping method name.")
description = graphene.JSONString(description="Shipping method description.")
@@ -92,9 +97,6 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
graphene.NonNull(ShippingMethodChannelListing),
description="List of channels available for the method.",
)
- price = graphene.Field(
- Money, description="The price of the cheapest variant (including discounts)."
- )
maximum_order_price = graphene.Field(
Money, description="The price of the cheapest variant (including discounts)."
)
@@ -131,59 +133,15 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
"them. They are directly exposed to the customers."
)
interfaces = [relay.Node, ObjectWithMetadata]
+ model = models.ShippingMethod
@staticmethod
def resolve_id(root: ChannelContext, _info):
- if getattr(root.node, "is_external", False):
- # todo external shipping to base64
- return root.node.id
- return graphene.Node.to_global_id("ShippingMethod", root.node.id)
-
- @staticmethod
- def resolve_translation(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- language_code,
- ):
- if getattr(root.node, "is_external", False):
- return None
-
- return ChannelContextType.resolve_translation(root, info, language_code)
-
- @staticmethod
- def resolve_price(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- **_kwargs
- ):
- # Price field are dynamically generated in available_shipping_methods resolver
- price = getattr(root.node, "price", None)
- if price is not None:
- return price
-
- if not root.channel_slug:
- return None
-
- if getattr(root.node, "is_external", False):
- return None
-
- return (
- ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
- info.context
- )
- .load((root.node.id, root.channel_slug))
- .then(
- lambda channel_listing: channel_listing.price
- if channel_listing
- else None
- )
- )
+ return graphene.Node.to_global_id("ShippingMethodType", root.node.id)
@staticmethod
def resolve_maximum_order_price(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- **_kwargs
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
):
maximum_order_price = getattr(root.node, "maximum_order_price", None)
if maximum_order_price is not None:
@@ -192,9 +150,6 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
if not root.channel_slug:
return None
- if getattr(root.node, "is_external", False):
- return None
-
return (
ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
info.context
@@ -205,9 +160,7 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
@staticmethod
def resolve_minimum_order_price(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- **_kwargs
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
):
minimum_order_price = getattr(root.node, "minimum_order_price", None)
if minimum_order_price is not None:
@@ -216,9 +169,6 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
if not root.channel_slug:
return None
- if getattr(root.node, "is_external", False):
- return None
-
return (
ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
info.context
@@ -229,37 +179,27 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
@staticmethod
def resolve_maximum_order_weight(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]], *_args
+ root: ChannelContext[models.ShippingMethod], *_args
):
return convert_weight_to_default_weight_unit(root.node.maximum_order_weight)
@staticmethod
def resolve_postal_code_rules(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- **_kwargs
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
):
- if getattr(root.node, "is_external", False):
- return None
-
return PostalCodeRulesByShippingMethodIdLoader(info.context).load(root.node.id)
@staticmethod
def resolve_minimum_order_weight(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]], *_args
+ root: ChannelContext[models.ShippingMethod], *_args
):
return convert_weight_to_default_weight_unit(root.node.minimum_order_weight)
@staticmethod
@permission_required(ShippingPermissions.MANAGE_SHIPPING)
def resolve_channel_listings(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- **_kwargs
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
):
- if getattr(root.node, "is_external", False):
- return None
-
return ShippingMethodChannelListingByShippingMethodIdLoader(info.context).load(
root.node.id
)
@@ -267,9 +207,7 @@ class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):
@staticmethod
@permission_required(ShippingPermissions.MANAGE_SHIPPING)
def resolve_excluded_products(
- root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],
- info,
- **kwargs
+ root: ChannelContext[models.ShippingMethod], info, **kwargs
):
from ..product.types import ProductCountableConnection
@@ -291,7 +229,7 @@ class ShippingZone(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
CountryDisplay, description="List of countries available for the method."
)
shipping_methods = graphene.List(
- ShippingMethod,
+ ShippingMethodType,
description=(
"List of shipping methods available for orders"
" shipped to countries within this shipping zone."
@@ -366,6 +304,76 @@ class ShippingZone(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
return ChannelsByShippingZoneIdLoader(info.context).load(root.node.id)
+class ShippingMethod(graphene.ObjectType):
+ id = graphene.ID(
+ required=True, description="Unique ID of ShippingMethod available for Order."
+ )
+ type = ShippingMethodTypeEnum(
+ description="Type of the shipping method.",
+ deprecation_reason=DEPRECATED_IN_3X_FIELD,
+ )
+ name = graphene.String(required=True, description="Shipping method name.")
+ description = graphene.JSONString(description="Shipping method description (JSON).")
+ maximum_delivery_days = graphene.Int(
+ description="Maximum delivery days for this shipping method."
+ )
+ minimum_delivery_days = graphene.Int(
+ description="Minimum delivery days for this shipping method."
+ )
+ maximum_order_weight = graphene.Field(
+ Weight,
+ description="Maximum order weight for this shipping method.",
+ deprecation_reason="This field will be removed in Saleor 4.0.",
+ )
+ minimum_order_weight = graphene.Field(
+ Weight,
+ description="Minimum order weight for this shipping method.",
+ deprecation_reason="This field will be removed in Saleor 4.0.",
+ )
+ translation = TranslationField(
+ ShippingMethodTranslation,
+ type_name="shipping method",
+ resolver=resolve_shipping_translation,
+ )
+ price = graphene.Field(
+ Money, required=True, description="The price of selected shipping method."
+ )
+ maximum_order_price = graphene.Field(
+ Money, description="Maximum order price for this shipping method."
+ )
+ minimum_order_price = graphene.Field(
+ Money, description="Minimal order price for this shipping method."
+ )
+ active = graphene.Boolean(
+ required=True,
+ description="Describes if this shipping method is active and can be selected.",
+ )
+ message = graphene.String(description="Message connected to this shipping method.")
+
+ class Meta:
+ interfaces = [relay.Node, ObjectWithMetadata]
+ description = (
+ (
+ "Shipping methods that can be used as means of shipping"
+ "for orders and checkouts."
+ ),
+ )
+
+ @staticmethod
+ def resolve_id(root: ShippingMethodData, _info):
+ if root.is_external:
+ return root.id
+ return graphene.Node.to_global_id("ShippingMethod", root.id)
+
+ @staticmethod
+ def resolve_maximum_order_weight(root: ShippingMethodData, *_args):
+ return convert_weight_to_default_weight_unit(root.maximum_order_weight)
+
+ @staticmethod
+ def resolve_minimum_order_weight(root: ShippingMethodData, *_args):
+ return convert_weight_to_default_weight_unit(root.minimum_order_weight)
+
+
class ShippingZoneCountableConnection(CountableConnection):
class Meta:
node = ShippingZone
diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.py
index 9a09e8c301..addb761ce7 100644
--- a/saleor/graphql/shop/resolvers.py
+++ b/saleor/graphql/shop/resolvers.py
@@ -2,13 +2,12 @@ from ...account.models import Address
from ...core.tracing import traced_resolver
from ...shipping.models import ShippingMethod, ShippingMethodChannelListing
from ...shipping.postal_codes import filter_shipping_methods_by_postal_code_rules
-from ..channel import ChannelContext
+from ...shipping.utils import convert_to_shipping_method_data
@traced_resolver
def resolve_available_shipping_methods(info, channel_slug: str, address):
instances = []
- manager = info.context.plugins
available = ShippingMethod.objects.for_channel(channel_slug)
if address and address.country:
available = available.filter(
@@ -17,41 +16,24 @@ def resolve_available_shipping_methods(info, channel_slug: str, address):
available = filter_shipping_methods_by_postal_code_rules(
available, Address(**address)
)
- # Address instance needed for apply_taxes_to_shipping method
- address = Address(country=address.country)
- else:
- address = Address()
if available is not None:
- display_gross = info.context.site.settings.display_gross_prices
- shipping_mapping = get_shipping_method_to_shipping_price_mapping(
- available, channel_slug
- )
- for shipping_method in available:
- shipping_price = shipping_mapping[shipping_method.pk]
- taxed_price = manager.apply_taxes_to_shipping(
- shipping_price, address, channel_slug
- )
- if display_gross:
- shipping_method.price = taxed_price.gross
- else:
- shipping_method.price = taxed_price.net
-
+ mapping = get_shipping_method_to_listing_mapping(available, channel_slug)
instances += [
- ChannelContext(node=shipping, channel_slug=channel_slug)
- for shipping in available
+ convert_to_shipping_method_data(method, mapping[method.id])
+ for method in available
]
return instances
-def get_shipping_method_to_shipping_price_mapping(shipping_methods, channel_slug):
- """Prepare mapping shipping method to price from channel listings."""
+def get_shipping_method_to_listing_mapping(shipping_methods, channel_slug):
+ """Prepare mapping shipping method to its channel listings."""
shipping_mapping = {}
shipping_listings = ShippingMethodChannelListing.objects.filter(
shipping_method__in=shipping_methods, channel__slug=channel_slug
)
for listing in shipping_listings:
- shipping_mapping[listing.shipping_method.id] = listing.price
+ shipping_mapping[listing.shipping_method_id] = listing
return shipping_mapping
diff --git a/saleor/graphql/shop/tests/benchmark/test_homepage.py b/saleor/graphql/shop/tests/benchmark/test_homepage.py
index 9137e4746b..ae19b9e697 100644
--- a/saleor/graphql/shop/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/shop/tests/benchmark/test_homepage.py
@@ -1,6 +1,6 @@
import pytest
-from ....order.tests.benchmark.test_order import FRAGMENT_AVAILABLE_SHIPPING_METHODS
+from ....order.tests.benchmark.test_order import FRAGMENT_SHIPPING_METHODS
from ....tests.utils import get_graphql_content
@@ -8,7 +8,7 @@ from ....tests.utils import get_graphql_content
@pytest.mark.count_queries(autouse=False)
def test_retrieve_shop(api_client, channel_USD, count_queries):
query = (
- FRAGMENT_AVAILABLE_SHIPPING_METHODS
+ FRAGMENT_SHIPPING_METHODS
+ """
query getShop($channel: String!) {
shop {
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index 7340ffb830..4fd0a1c1bf 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -896,9 +896,13 @@ def test_query_available_shipping_methods_for_given_address(
content = get_graphql_content(response)
data = content["data"]["shop"]["availableShippingMethods"]
assert len(data) == shipping_method_count - 1
- assert graphene.Node.to_global_id(
- "ShippingMethod", shipping_zone_without_countries.shipping_methods.first().pk
- ) not in {ship_meth["id"] for ship_meth in data}
+ assert (
+ graphene.Node.to_global_id(
+ "ShippingMethodType",
+ shipping_zone_without_countries.shipping_methods.first().pk,
+ )
+ not in {ship_meth["id"] for ship_meth in data}
+ )
def test_query_available_shipping_methods_no_address_vatlayer_set(
@@ -949,7 +953,7 @@ def test_query_available_shipping_methods_for_given_address_vatlayer_set(
data = content["data"]["shop"]["availableShippingMethods"]
assert len(data) == shipping_method_count - 1
assert graphene.Node.to_global_id(
- "ShippingMethod", shipping_zone_without_countries.pk
+ "ShippingMethodType", shipping_zone_without_countries.pk
) not in {ship_meth["id"] for ship_meth in data}
@@ -972,7 +976,7 @@ def test_query_available_shipping_methods_for_excluded_postal_code(
# then
content = get_graphql_content(response)
data = content["data"]["shop"]["availableShippingMethods"]
- assert graphene.Node.to_global_id("ShippingMethod", shipping_method.pk) not in {
+ assert graphene.Node.to_global_id("ShippingMethodType", shipping_method.pk) not in {
ship_meth["id"] for ship_meth in data
}
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 4e41a9813b..3ffaaf60e8 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -10,11 +10,15 @@ from ...menu import models as menu_models
from ...page import models as page_models
from ...product import models as product_models
from ...shipping import models as shipping_models
+from ..attribute import types as attribute_types
from ..channel import ChannelContext
from ..core.enums import LanguageCodeEnum
from ..core.mutations import BaseMutation, ModelMutation, registry
from ..core.types.common import TranslationError
-from ..product.types import Product, ProductVariant
+from ..discount import types as discount_types
+from ..menu import types as menu_types
+from ..page import types as page_types
+from ..product import types as product_types
from ..shipping import types as shipping_types
from ..shop.types import Shop
from . import types as translation_types
@@ -25,38 +29,24 @@ from ..discount import types # noqa # pylint: disable=unused-import, isort:skip
from ..menu import types # type: ignore # noqa # pylint: disable=unused-import, isort:skip
-TRANSLATABLE_CONTENT_TO_MODEL = {
- str(
- translation_types.ProductTranslatableContent
- ): product_models.Product._meta.object_name,
- str(
- translation_types.CollectionTranslatableContent
- ): product_models.Collection._meta.object_name,
- str(
- translation_types.CategoryTranslatableContent
- ): product_models.Category._meta.object_name,
- str(
- translation_types.AttributeTranslatableContent
- ): attribute_models.Attribute._meta.object_name,
- str(
- translation_types.AttributeValueTranslatableContent
- ): attribute_models.AttributeValue._meta.object_name,
- str(
- translation_types.ProductVariantTranslatableContent
- ): product_models.ProductVariant._meta.object_name,
- str(translation_types.PageTranslatableContent): page_models.Page._meta.object_name,
- str(
- translation_types.ShippingMethodTranslatableContent
- ): shipping_models.ShippingMethod._meta.object_name,
- str(
- translation_types.SaleTranslatableContent
- ): discount_models.Sale._meta.object_name,
- str(
- translation_types.VoucherTranslatableContent
- ): discount_models.Voucher._meta.object_name,
- str(
- translation_types.MenuItemTranslatableContent
- ): menu_models.MenuItem._meta.object_name,
+TRANSLATABLE_CONTENT_TO_TYPE = {
+ str(translation_types.ProductTranslatableContent): str(product_types.Product),
+ str(translation_types.CollectionTranslatableContent): str(product_types.Collection),
+ str(translation_types.CategoryTranslatableContent): str(product_types.Category),
+ str(translation_types.AttributeTranslatableContent): str(attribute_types.Attribute),
+ str(translation_types.AttributeValueTranslatableContent): str(
+ attribute_types.AttributeValue
+ ),
+ str(translation_types.ProductVariantTranslatableContent): str(
+ product_types.ProductVariant
+ ),
+ str(translation_types.PageTranslatableContent): str(page_types.Page),
+ str(translation_types.ShippingMethodTranslatableContent): str(
+ shipping_types.ShippingMethodType
+ ),
+ str(translation_types.SaleTranslatableContent): str(discount_types.Sale),
+ str(translation_types.VoucherTranslatableContent): str(discount_types.Voucher),
+ str(translation_types.MenuItemTranslatableContent): str(menu_types.MenuItem),
}
@@ -79,7 +69,7 @@ class BaseTranslateMutation(ModelMutation):
# check if provided ID refers to a translatable content which matches with the
# expected model_type. If so, we transform the translatable content ID to model
# ID.
- tc_model_type = TRANSLATABLE_CONTENT_TO_MODEL.get(node_type)
+ tc_model_type = TRANSLATABLE_CONTENT_TO_TYPE.get(node_type)
if tc_model_type and tc_model_type == str(model_type):
node_id = graphene.Node.to_global_id(tc_model_type, node_pk)
@@ -167,7 +157,7 @@ class ProductTranslate(BaseTranslateMutation):
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
node_id = cls.clean_node_id(**data)[0]
- product = cls.get_node_or_error(info, node_id, only_type=Product)
+ product = cls.get_node_or_error(info, node_id, only_type=product_types.Product)
translation, created = product.translations.update_or_create(
language_code=data["language_code"], defaults=data["input"]
@@ -232,7 +222,9 @@ class ProductVariantTranslate(BaseTranslateMutation):
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
node_id = cls.clean_node_id(**data)[0]
- variant_pk = cls.get_global_id_or_error(node_id, only_type=ProductVariant)
+ variant_pk = cls.get_global_id_or_error(
+ node_id, only_type=product_types.ProductVariant
+ )
variant = product_models.ProductVariant.objects.prefetched_for_webhook().get(
pk=variant_pk
)
@@ -344,7 +336,9 @@ class ShippingPriceTranslate(BaseTranslateMutation):
class Arguments:
id = graphene.ID(
required=True,
- description="ShippingMethod ID or ShippingMethodTranslatableContent ID.",
+ description=(
+ "ShippingMethodType ID or ShippingMethodTranslatableContent ID.",
+ ),
)
language_code = graphene.Argument(
LanguageCodeEnum, required=True, description="Translation language code."
@@ -366,7 +360,7 @@ class ShippingPriceTranslate(BaseTranslateMutation):
@classmethod
def get_type_for_model(cls):
- return shipping_types.ShippingMethod
+ return shipping_types.ShippingMethodType
@classmethod
def get_node_or_error(cls, info, node_id, field="id", only_type=None, qs=None):
@@ -421,6 +415,13 @@ class PageTranslate(BaseTranslateMutation):
error_type_field = "translation_errors"
permissions = (SitePermissions.MANAGE_TRANSLATIONS,)
+ @classmethod
+ def get_type_for_model(cls):
+ # This method prevents type PageTranslate page field in GraphQL schema
+ # to be automatically changed to Page model, since we want to address that
+ # problem in a separate PR.
+ return translation_types.PageTranslatableContent
+
class ShopSettingsTranslationInput(graphene.InputObjectType):
header_text = graphene.String()
diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.py
index a227bcc357..c9e9319005 100644
--- a/saleor/graphql/translations/schema.py
+++ b/saleor/graphql/translations/schema.py
@@ -58,7 +58,7 @@ class TranslatableKinds(graphene.Enum):
PAGE = "Page"
PRODUCT = "Product"
SALE = "Sale"
- SHIPPING_METHOD = "ShippingMethod"
+ SHIPPING_METHOD = "ShippingMethodType"
VARIANT = "ProductVariant"
VOUCHER = "Voucher"
diff --git a/saleor/graphql/translations/tests/deprecated/test_translations.py b/saleor/graphql/translations/tests/deprecated/test_translations.py
index 619575ecac..0b54078b15 100644
--- a/saleor/graphql/translations/tests/deprecated/test_translations.py
+++ b/saleor/graphql/translations/tests/deprecated/test_translations.py
@@ -362,7 +362,7 @@ def test_translation_query_shipping_method(
permission_manage_shipping,
):
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.id
+ "ShippingMethodType", shipping_method.id
)
variables = {
"id": shipping_method_id,
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index 560b124d6c..13613de47a 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -1862,6 +1862,10 @@ SHIPPING_PRICE_TRANSLATE = """
}
}
}
+ errors {
+ message
+ code
+ }
}
}
"""
@@ -1878,7 +1882,7 @@ def test_shipping_method_create_translation(
):
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.id
+ "ShippingMethodType", shipping_method.id
)
description = dummy_editorjs("description", True)
variables = {
@@ -1959,7 +1963,7 @@ def test_shipping_method_update_translation(
"""
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.id
+ "ShippingMethodType", shipping_method.id
)
response = staff_api_client.post_graphql(
query,
@@ -2558,7 +2562,7 @@ def test_translation_query_shipping_method(
return_shipping_method,
):
shipping_method_id = graphene.Node.to_global_id(
- "ShippingMethod", shipping_method.id
+ "ShippingMethodType", shipping_method.id
)
perms = list(Permission.objects.filter(codename__in=perm_codenames))
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 6b58a18238..d1bcacc41a 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -531,7 +531,7 @@ class ShippingMethodTranslatableContent(CountableDjangoObjectType):
ShippingMethodTranslation, type_name="shipping method"
)
shipping_method = graphene.Field(
- "saleor.graphql.shipping.types.ShippingMethod",
+ "saleor.graphql.shipping.types.ShippingMethodType",
description=(
"Shipping method are the methods you'll use to get customer's orders "
" to them. They are directly exposed to the customers."
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index adbe5b8931..154e74b5b5 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -174,7 +174,9 @@ def test_get_valid_shipping_methods_for_order(order_line_with_one_allocation, ad
order.save(update_fields=["shipping_address"])
# when
- valid_shipping_methods = get_valid_shipping_methods_for_order(order)
+ valid_shipping_methods = get_valid_shipping_methods_for_order(
+ order, order.channel.shipping_method_listings.all()
+ )
# then
assert len(valid_shipping_methods) == 1
@@ -194,7 +196,9 @@ def test_get_valid_shipping_methods_for_order_no_channel_shipping_zones(
order.save(update_fields=["shipping_address"])
# when
- valid_shipping_methods = get_valid_shipping_methods_for_order(order)
+ valid_shipping_methods = get_valid_shipping_methods_for_order(
+ order, order.channel.shipping_method_listings.all()
+ )
# then
assert len(valid_shipping_methods) == 0
@@ -211,10 +215,12 @@ def test_get_valid_shipping_methods_for_order_no_shipping_address(
order.currency = "USD"
# when
- valid_shipping_methods = get_valid_shipping_methods_for_order(order)
+ valid_shipping_methods = get_valid_shipping_methods_for_order(
+ order, order.channel.shipping_method_listings.all()
+ )
# then
- assert valid_shipping_methods is None
+ assert valid_shipping_methods == []
def test_get_valid_shipping_methods_for_order_shipping_not_required(
@@ -230,10 +236,12 @@ def test_get_valid_shipping_methods_for_order_shipping_not_required(
order.save(update_fields=["shipping_address"])
# when
- valid_shipping_methods = get_valid_shipping_methods_for_order(order)
+ valid_shipping_methods = get_valid_shipping_methods_for_order(
+ order, order.channel.shipping_method_listings.all()
+ )
# then
- assert valid_shipping_methods is None
+ assert valid_shipping_methods == []
def test_update_taxes_for_order_lines(order_with_lines):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 127011cc9b..8a4642857d 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -25,7 +25,9 @@ from ..order import FulfillmentStatus, OrderStatus
from ..order.fetch import OrderLineInfo
from ..order.models import Order, OrderLine
from ..product.utils.digital_products import get_default_digital_content_settings
-from ..shipping.models import ShippingMethod
+from ..shipping.interface import ShippingMethodData
+from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
+from ..shipping.utils import convert_to_shipping_method_data
from ..warehouse.management import (
decrease_allocations,
get_order_lines_with_track_inventory,
@@ -650,17 +652,39 @@ def sum_order_totals(qs, currency_code):
return sum([order.total for order in qs], taxed_zero)
-def get_valid_shipping_methods_for_order(order: Order):
+def get_valid_shipping_methods_for_order(
+ order: Order, shipping_channel_listings: Iterable["ShippingMethodChannelListing"]
+) -> List[ShippingMethodData]:
+ """Return a list of shipping methods according to Saleor's own business logic.
+
+ The resulting methods are not yet filtered by plugins.
+ """
if not order.is_shipping_required():
- return None
+ return []
+
if not order.shipping_address:
- return None
- return ShippingMethod.objects.applicable_shipping_methods_for_instance(
+ return []
+
+ valid_methods = []
+
+ shipping_methods = ShippingMethod.objects.applicable_shipping_methods_for_instance(
order,
channel_id=order.channel_id,
price=order.get_subtotal().gross,
country_code=order.shipping_address.country.code,
- )
+ ).prefetch_related("channel_listings")
+
+ listing_map = {
+ listing.shipping_method_id: listing for listing in shipping_channel_listings
+ }
+
+ for method in shipping_methods:
+ listing = listing_map.get(method.id)
+ shipping_method_data = convert_to_shipping_method_data(method, listing)
+ if shipping_method_data:
+ valid_methods.append(shipping_method_data)
+
+ return valid_methods
def is_shipping_required(lines: Iterable["OrderLine"]):
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 748fdad51a..e8b67b7727 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -218,18 +218,17 @@ def append_line_to_data(
def append_shipping_to_data(
data: List[Dict],
- shipping_method_channel_listings: Optional["ShippingMethodChannelListing"],
+ shipping_price_amount: Optional[Decimal],
shipping_tax_code: str,
):
charge_taxes_on_shipping = (
Site.objects.get_current().settings.charge_taxes_on_shipping
)
- if charge_taxes_on_shipping and shipping_method_channel_listings:
- shipping_price = shipping_method_channel_listings.price
+ if charge_taxes_on_shipping and shipping_price_amount:
append_line_to_data(
data,
quantity=1,
- amount=shipping_price.amount,
+ amount=shipping_price_amount,
tax_code=shipping_tax_code,
item_code="Shipping",
)
@@ -298,9 +297,15 @@ def get_checkout_lines_data(
ref2=line_info.variant.sku,
)
- append_shipping_to_data(
- data, checkout_info.shipping_method_channel_listings, config.shipping_tax_code
- )
+ delivery_method = checkout_info.delivery_method_info.delivery_method
+ if delivery_method:
+ price = getattr(delivery_method, "price", None)
+ append_shipping_to_data(
+ data,
+ price.amount if price else None,
+ config.shipping_tax_code,
+ )
+
return data
@@ -378,9 +383,12 @@ def get_order_lines_data(
shipping_method_channel_listing = ShippingMethodChannelListing.objects.filter(
shipping_method=order.shipping_method_id, channel=order.channel_id
).first()
- append_shipping_to_data(
- data, shipping_method_channel_listing, config.shipping_tax_code
- )
+ if shipping_method_channel_listing:
+ append_shipping_to_data(
+ data,
+ shipping_method_channel_listing.price.amount,
+ config.shipping_tax_code,
+ )
return data
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 351744a47d..0e4316ad2b 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -229,7 +229,7 @@ class AvataxPlugin(BasePlugin):
taxed_line_total_data.price_with_discounts
)
- base_shipping_price = base_calculations.base_checkout_shipping_price(
+ base_shipping_price = base_calculations.base_checkout_delivery_price(
checkout_info, lines
)
shipping_price = self._calculate_checkout_shipping(
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale.yaml
index 34b1ae0626..73eed7bf46 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale.yaml
@@ -1,106 +1,4 @@
interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 1, "amount":
- "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode": "Shipping",
- "description": null}], "code": "80fdf5c9-1035-40bf-9c43-b7f3a7045493", "date":
- "2021-12-20", "customerCode": 0, "addresses": {"shipFrom": {"line1": "Teczowa
- 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL", "postalCode":
- "53-601"}, "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW",
- "region": "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":
- "USD", "email": ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate, br
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '756'
- User-Agent:
- - python-requests/2.26.0
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- i/8BAICqqqrq/3RNkLOag9oWbqY3B/M4OECCJ0CEeR4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- aUlqLGOP9xYnOA4AAFRVVVX/p2sAn9UN1M3D0wP05uABAeAABu4G7g4QAOngBzFTAXcNUFM1UBX1
- cAsHt9h5/xXDWKu2cPj4ODwMxxiGAeIY58bG+CJmkv18XzwJW5h59bFS8I46551Mp2lkGBzZe054
- XRRCDC3lLLcUy/X2yULOZ5jzReGWN9EyDKDQxyzbkEui0PNXYne9CYyutMKdZBMtw6BtjrN6ob9m
- s7aBwp1kV4aO02kaeWth9OuiQNYmzpkzzPkJZ2G0giQKmXpxMWwtWOx1sQRLaWr4zh4G/924xDRY
- Bp7D4MT9X/yltxV47fVVNUv6ItTd3skEg+/DftOsv6GQ+OpiECiNMQv5EQMvF7N/eo5B4SVIqsTY
- NlAQehzqJF9rUevlXNcKnsRJsSa6j+FKJX+pJ2b6NCjF3tMvvo7hopDLMJAtsPMTFh0vT4thz09J
- Lj82CAabWLyUlmlWv6S2owGgdt+sd59mK62L3GLa0rT3vlTIQsLrnN01sN1FmF2ECT0aBd4XGYuA
- FjuWLhMr2brYUWiRMLdvBxKGQiJhcTjTtWZGnWeYRV0ta6VOYHRVL7TWuokQzKp6/wjFNuR/WKoJ
- DzGcjonlV6z5wcMoLgYYXenX5TU=
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - br
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Mon, 20 Dec 2021 16:56:39 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0173753'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- referrer-policy:
- - same-origin
- strict-transport-security:
- - max-age=31536000; includeSubdomains
- x-avalara-uid:
- - f8532e7e-e3fe-40a4-8218-8c03e7e62866
- x-correlation-id:
- - f8532e7e-e3fe-40a4-8218-8c03e7e62866
- x-frame-options:
- - sameorigin
- x-permitted-cross-domain-policies:
- - none
- x-xss-protection:
- - 1; mode=block
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher.yaml
index 92316d1e67..5512ad0ed9 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher.yaml
@@ -1,120 +1,4 @@
interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 3, "amount":
- "21.00", "taxCode": "O9999999", "taxIncluded": true, "itemCode": "123", "description":
- "Test product", "ref2": "123"}, {"quantity": 1, "amount": "10.000", "taxCode":
- "FR000000", "taxIncluded": true, "itemCode": "Shipping", "description": null}],
- "code": "dc5134f4-ff06-4cc8-8252-f1f182955a73", "date": "2021-12-20", "customerCode":
- 0, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2": null, "city": "Wroclaw",
- "region": "", "country": "PL", "postalCode": "53-601"}, "shipTo": {"line1":
- "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country":
- "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode": "USD", "email":
- ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate, br
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '901'
- User-Agent:
- - python-requests/2.26.0
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- i/8BAICqqqrq/3QNkLOag6m6mbub3hzM4+AACR4AEeZ5yDyJq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5cXFFMh1fApshlGgR6J/kXgtrsvrZrfPTptNXULkWZWmlkOzzvzSQ2dNcaC+DxwjN4L/wEiI
- FSSQi9SJ8c7MXyq0PrmewlryF1to/DPzAQrWOM6h0XD333/T3SP41HcYlbul7Z9ptTOyQuPtci7K
- 4xsUAg/GO0OS2UchO7rpYb95yHIsipGchEq0egcMoeVSx32sk112yLOdgiUxkk6FCgXr3UCV/qt2
- ujgk+M7SN66Ow00hpmmiWODvP4ho+8r0Edj8TMHEjw2BRuFTlqxKjfrN6hVNgNbn8lg9I2zKMcno
- w5WWpfuDQhQSPsZoBsd95RE6XWhpZPOcZE5/I0RouaZWyQ0kaxe/Ch0S4v7uQsJQCCRstqccQUFo
- odYysAUQOjQ5LjU5LCJyYXRlIjowLjIzMDAwMCwidGF4IjoxMS40MSwidGF4Q2FsY3VsYXRlZCI6
- MTEuNDEsIm5vblRheGFibGUiOjAuMCwiZXhlbXB0aW9uIjowLjB9XX0D
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - br
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Mon, 20 Dec 2021 16:56:39 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0215381'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- referrer-policy:
- - same-origin
- strict-transport-security:
- - max-age=31536000; includeSubdomains
- x-avalara-uid:
- - f02a95bd-499b-4fdb-95ab-8dec0e51eea7
- x-correlation-id:
- - f02a95bd-499b-4fdb-95ab-8dec0e51eea7
- x-frame-options:
- - sameorigin
- x-permitted-cross-domain-policies:
- - none
- x-xss-protection:
- - 1; mode=block
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher_only_once.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher_only_once.yaml
index 9ab641a14c..19d62d8eea 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher_only_once.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_total_with_variant_on_sale_and_voucher_only_once.yaml
@@ -1,120 +1,4 @@
interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 3, "amount":
- "27.00", "taxCode": "O9999999", "taxIncluded": true, "itemCode": "123", "description":
- "Test product", "ref2": "123"}, {"quantity": 1, "amount": "10.000", "taxCode":
- "FR000000", "taxIncluded": true, "itemCode": "Shipping", "description": null}],
- "code": "892bda21-8c10-4f2b-98a5-8659c808c039", "date": "2021-12-20", "customerCode":
- 0, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2": null, "city": "Wroclaw",
- "region": "", "country": "PL", "postalCode": "53-601"}, "shipTo": {"line1":
- "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country":
- "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode": "USD", "email":
- ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate, br
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '901'
- User-Agent:
- - python-requests/2.26.0
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- i/8BAICqqqrq/3RNkLOag6m6mYeZ3hzM4+AACZ4AEeZ5yDyJq4q5a6apqoGoWIAZhJmTfRoo1kLR
- rlt3kZOTlZWRkeU4rI+cjEQicUPXcyCQivvPNwQPtlbgsiew0PXm4dHoqnO6rprJPKq+w7bqTm3v
- urpz9bEH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NBru/vtvunsEn/oOo3K3tP0zrXZGVmi8Xc5F
- eXyDQuDBeGdIMvsoZEc3Pew3D1mORTGSk1CJVu+AIbRc6riPdbLLDnm2U7AkRtKpUKFgvRuo0n/V
- TheHBN9Z+sbVcbgpxDRNFAv8/QcRbV+ZPgKbnymY+LEh0Ch8ypJVqVG/Wb2iCdD6XB6rZ4RNOSYZ
- fbjSsnR/UIhCwscYzeC4rzxCpwstjWyek8zpb4QILdfUKrmBZO3iV6FDQtzfXUgYCoGEzfaUIygI
- LdRaBrYAAjo1NC40NywicmF0ZSI6MC4yMzAwMDAsInRheCI6MTIuNTMsInRheENhbGN1bGF0ZWQi
- OjEyLjUzLCJub25UYXhhYmxlIjowLjAsImV4ZW1wdGlvbiI6MC4wfV19Aw==
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - br
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Mon, 20 Dec 2021 16:56:41 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0223396'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- referrer-policy:
- - same-origin
- strict-transport-security:
- - max-age=31536000; includeSubdomains
- x-avalara-uid:
- - 1aa6ad19-c4d9-4da7-b0b2-e7a18e7d455d
- x-correlation-id:
- - 1aa6ad19-c4d9-4da7-b0b2-e7a18e7d455d
- x-frame-options:
- - sameorigin
- x-permitted-cross-domain-policies:
- - none
- x-xss-protection:
- - 1; mode=block
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale.yaml
index beb29ca436..102f56f6f6 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale.yaml
@@ -1,106 +1,4 @@
interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 1, "amount":
- "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode": "Shipping",
- "description": null}], "code": "9928b7dc-7660-4103-928e-53061e9a0e96", "date":
- "2021-12-20", "customerCode": 0, "addresses": {"shipFrom": {"line1": "Teczowa
- 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL", "postalCode":
- "53-601"}, "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW",
- "region": "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":
- "USD", "email": ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate, br
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '756'
- User-Agent:
- - python-requests/2.26.0
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- i/8BAICqqqrq/3QNkLOagy1u5m56c3CPgwMkeABEmOch8ySuyuaumaaqBqpiAWYQZpv4IRuzdqPa
- UdqLRFYikZGR7HazHlkZWSHrhq7nQCAVd88POUu6VGSiBWnq+/r4OFhTHLquLPZV2RR9fUTRNmVX
- oecSfUcKuPzMYbta0vW+7g+tIstiAl9d1lVR1UVdkqKZN48gl3LanYVlyaRpgJ9j4rSRItlmH3i+
- eEL+SBaJFD1YzOvcYZiRIrOkhGA2lD33rwspwmpeHJ74ZMGZtHBilizRI90zPzH8KWStCeJku2c4
- shA7qt8INqYa53l2mxG2WOFnuUVS05UEE4NxEyzpkacMRVM0LC4GHQsRYeaYx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A0xizkRwy8XMz+6TkGhZcgqRJj
- 20BB6HGok3ytRa2Xc10reBInxZroPoYrlfylnpjp06AUe0+/+DqGi0Iuw0C2wM5PWHS8PC2GPT8l
- ufzYIBhsYvFSWqZZ/ZLajgaA2n2z3n2arbQucotpS9Pe+1IhCwmvc3bXwHYXYXYRJvRoFHhfZCwC
- WuxYukysZOtiR6FFwty+HUgYComExeFM15oZdZ5hFnW1rJU6gdFVvdBa6yZCMKvq/SMU25D/Yakm
- PMRwOiaWX7HmBw+juBhgdKVfl9c=
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - br
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Mon, 20 Dec 2021 16:56:43 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0169622'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- referrer-policy:
- - same-origin
- strict-transport-security:
- - max-age=31536000; includeSubdomains
- x-avalara-uid:
- - 5e538057-7d29-41f7-ae57-2bca7a490a88
- x-correlation-id:
- - 5e538057-7d29-41f7-ae57-2bca7a490a88
- x-frame-options:
- - sameorigin
- x-permitted-cross-domain-policies:
- - none
- x-xss-protection:
- - 1; mode=block
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher.yaml
index e24859b7f8..337235c6a5 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher.yaml
@@ -1,120 +1,4 @@
interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 3, "amount":
- "21.00", "taxCode": "O9999999", "taxIncluded": true, "itemCode": "123", "description":
- "Test product", "ref2": "123"}, {"quantity": 1, "amount": "10.000", "taxCode":
- "FR000000", "taxIncluded": true, "itemCode": "Shipping", "description": null}],
- "code": "fe05eab8-de9d-4624-a1e0-cde484675101", "date": "2021-12-20", "customerCode":
- 0, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2": null, "city": "Wroclaw",
- "region": "", "country": "PL", "postalCode": "53-601"}, "shipTo": {"line1":
- "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country":
- "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode": "USD", "email":
- ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate, br
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '901'
- User-Agent:
- - python-requests/2.26.0
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- i/8BAICqqqrq/3RNkLOag6mF+qY3B/c4OECCJ0CEeR4yT+KqbO6aaapqoCoWYAZh5mSfBoq10GnX
- rbvIycnKysjIchzWR05GIiRu6HoOBFJx//mm4Mm2ilz2IEsD2i34cWg8jr4xu840rNE2zsMczG6/
- 1a0mBUJx4rRePdnOdMf9VpFnMUGsazvd6K7pWlI08RqR5FIuh6uwzJUs9YhTLlxWUiTr5IPIJ4+o
- v4pHIUUPFvc6d5g8UuTmUpDcinLk/nkhRVjci9MTHyw4kxYu3FwlR5R75Sf6P6WqNUmCrPcKRxZi
- Z/UbyedS4zrPbjPDFgviJLdMavqlwOXkwghPduCxQtGYHUvIScdCRJgpFwnp+bNcMtNc3IsrhqfJ
- WA0oSK7Lh9QN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paJTeQrF38KnRIiPu7CwlDIZCw2Z5yBAWhhVrL
- wBZAOjQ5LjU5LCJyYXRlIjowLjIzMDAwMCwidGF4IjoxMS40MSwidGF4Q2FsY3VsYXRlZCI6MTEu
- NDEsIm5vblRheGFibGUiOjAuMCwiZXhlbXB0aW9uIjowLjB9XX0D
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - br
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Mon, 20 Dec 2021 16:56:44 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0203705'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- referrer-policy:
- - same-origin
- strict-transport-security:
- - max-age=31536000; includeSubdomains
- x-avalara-uid:
- - 5e22d65a-8032-43a7-ab3c-514b6e0674ab
- x-correlation-id:
- - 5e22d65a-8032-43a7-ab3c-514b6e0674ab
- x-frame-options:
- - sameorigin
- x-permitted-cross-domain-policies:
- - none
- x-xss-protection:
- - 1; mode=block
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher_only_once.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher_only_once.yaml
index bd62acb73c..8d6f77c02d 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher_only_once.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher_only_once.yaml
@@ -1,120 +1,4 @@
interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 3, "amount":
- "27.00", "taxCode": "O9999999", "taxIncluded": true, "itemCode": "123", "description":
- "Test product", "ref2": "123"}, {"quantity": 1, "amount": "10.000", "taxCode":
- "FR000000", "taxIncluded": true, "itemCode": "Shipping", "description": null}],
- "code": "694bae4a-f2b4-41b2-959e-8107cd4ed9c8", "date": "2021-12-20", "customerCode":
- 0, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2": null, "city": "Wroclaw",
- "region": "", "country": "PL", "postalCode": "53-601"}, "shipTo": {"line1":
- "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country":
- "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode": "USD", "email":
- ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate, br
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '901'
- User-Agent:
- - python-requests/2.26.0
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- i/8BAICqqqrq/3QNkLOag5m6mbuZ3hzM4+AACR4AEeZ5yDyJqYq5a6apqoGoWIAZhJmTfRoo1kKn
- XbfuIicnKysjI8txWB85GYmQuKHrORBIxf3nB7wDUyqwyREYOHX1iFRjMemxLupq1EXXdFS0VXm2
- ribX2RYUCIUF435zYHStu3OjwKGYIKZLXRWVLnQJChbcA0W5lsvhLChrBgMDhSUx8g4KZF98EPnC
- mfIHO2JQMKLYV99h8kCBXZkp2h3lyOPrCgposy+MT/pEoZ60cGHXLCkQPzI+afhTqloTxcv+yOTI
- AuysflN0iWtc59ltZtjSRmGRewI1/cJkU7R+JgdmwjmTgjlZFJ+ijgWIMEti8fH5q1wyy8r2hZmG
- p8lYTcQUbZcPyRtCX4iz91NAkuB8CWmNAqapD/UZZ3nvkwaY8lCi3K8+W26acGfADUylD82RyHrA
- DceZ/F68AbceZ7vOKIOiaRS6f2uWrOF/Eu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XhDYWxjdWxhdGVkIjoxMi41Mywibm9u
- VGF4YWJsZSI6MC4wLCJleGVtcHRpb24iOjAuMH1dfQM=
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - br
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Mon, 20 Dec 2021 16:56:43 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0203088'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- referrer-policy:
- - same-origin
- strict-transport-security:
- - max-age=31536000; includeSubdomains
- x-avalara-uid:
- - 78901ef1-315a-462c-bc24-036fbe7e7c35
- x-correlation-id:
- - 78901ef1-315a-462c-bc24-036fbe7e7c35
- x-frame-options:
- - sameorigin
- x-permitted-cross-domain-policies:
- - none
- x-xss-protection:
- - 1; mode=block
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/cassettes/test_plugin_uses_configuration_from_db.yaml b/saleor/plugins/avatax/tests/cassettes/test_plugin_uses_configuration_from_db.yaml
index 1f06d2c68a..dc94ced68c 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_plugin_uses_configuration_from_db.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_plugin_uses_configuration_from_db.yaml
@@ -73,80 +73,6 @@ interactions:
status:
code: 201
message: Created
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "15.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": "Test product"}, {"quantity": 1, "amount":
- "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode": "Shipping",
- "description": null}], "code": "c1b86a21-352b-43f5-bdc9-4e41c79489cd", "date":
- "2021-03-02", "customerCode": 0, "addresses": {"shipFrom": {"line1": "T\u0119czowa
- 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode":
- "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
- "region": "", "country": "PL", "postalCode": "53-105"}}, "commit": false, "currencyCode":
- "USD", "email": ""}}'
- headers:
- Accept:
- - '*/*'
- Accept-Encoding:
- - gzip, deflate
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '765'
- User-Agent:
- - python-requests/2.25.1
- method: POST
- uri: https://rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: !!binary |
- H4sIAAAAAAAEA+1X227bOBD9lUDPsaGbY8dvXqcBAhh2EDtboIs+0BJts9VtSSqNt8i/7xmSUuTY
- 2aZ7ydMGeZCGw9HMmcPD8XdPpN7YP/eSMuXe2EuC9eiChUEvGoTrXhxtBr11mlz2Yh4HyfAyHl0m
- qUfeecWK/Q32hnF4ORyceynTFCD0sdmPen4It4rtc17oqxNLSjNdK2xY8bwqJZN7+Ot9RTGWLONq
- IVMuYVszneymNjv6ci0lL5K9s9wvr2Dkj8mOFVt+hw9NTzkktdJlzuW9Ylu+sl+hfYUWen+veDe+
- 9fyVF2kpnd03H7YLHRN/RO56XiJlOEielEUiMg5QNixT/NzLyoRpURbP4SVHsVoU29nRUlVLVKG4
- Kfw56IZTvZ0MFaFTcam6cXWpWTbJy7rQaInfjyKgSbYPJke0uI8mG8uVUIn1e7at2KM3jvsXQ+eD
- d7bO0ItuKBinLEvqDCijRuvO0i/Alrp8xxlSAhbzUk+MFV4Gg68dSB6QOBDxxsFh2z5sNjzR4oGf
- Iku3v9hJpfCcicwCn5ep2AieHu1c+cNxHI+joB8MB7F/EX9CPo03ui4Nf0dRcBmibvZ4IoA/9umf
- Nmai4CDsb9+bI6MlKxRD0mVBgZAUuczrfA3ijr0Ae97Ou5SrRIqKgmHviit9VskyrRONMKlrWdNg
- 0zjLvhOmKZfaJXTIUKFuNM/b3mpZg6MCJsfPIIxcnU3UIOwDmt9rZg6KN44Iesk3gUUeT2Hz5Hh9
- hCEiAlowqT8yT8Srw/BY7vKqcXRJLS7tn41DRqptEMXE5xM9s343RZLVKfHOVplyDb681r4Z+uYQ
- O26qOSyQp7F3O0Nwybe2R+btRBO+1FIol7zxMYY5y0nabhezyZwki/SPT5QS24KnzWk3nk6epvMV
- 3IwlFYZkzQIdXiOXRVm4ZjaAGmJII7d+P4x8/L0Ffhd5UeuqJr4B12W9Jiuh4i2syZWw1KxImUzP
- SG3tyqTWu1JCSpstMS6EU22l1NzHmjCI0FgdaEuY6kLoxeYXpgTdEbdcNrJ+jwWsCzUvi1um1Gon
- 61ZvhbrmQNmpb6u1DiTaimiW0+0i4hyuWwwbnbb66bYeLmGbo3UbDKYjKmeCrUXmwEExS55lEIin
- z+ceGkg16J0s6+3uquUolnYNhVBsUip9U6gaepPwa8nFdgeVN8k8MN1SbdlDxxe9niEdFqwSNS3x
- n87fqlx0df+Ecr2POC13oqpwcSI3ktmG8aN+EHUVylwOf0+hgv6I7j979R3Gh7Hb19bTYX9954d+
- 4NOYQJ5Oo+LhKDaGVzTxf416oVEtrN07wjYYsDrd+E9FymbQ6BEdVid26GxjfR+VsmW3wvIPVcrV
- 1Yja6hSd31enrl/XKagfS1PJlfrRvLXGVYiraD/jD5yGwU+iGjh9oAllkbFv6is7C+hgkmi4YYUe
- I6zDmkCX8fTxbjGdTT5Sl5vrHc8VdJdlrt+DqBf4FP3FPABm3pk9dFWG/iDwMTFhRBYa84f9SFYW
- 2/b1L2X4BwWtePJH+Y2dDZHGv1DPhW9mVDdPuPnmp+tBu1Sd5/QLjobjF/C0eD6PQu4gT9s55m0T
- ExI7mDPwCwRTBjp0PEfB9XW1IGIAP/i8MtA0Bx2OneMP/4OfRORFl/DBlOV+Qh0eL2vEXb9qQpir
- 246OZpbE+9Pnpz8BRg/uIowPAAA=
- headers:
- Connection:
- - keep-alive
- Content-Encoding:
- - gzip
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Tue, 02 Mar 2021 07:44:31 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- Server:
- - Kestrel
- ServerDuration:
- - '00:00:00.0200552'
- Transfer-Encoding:
- - chunked
- Vary:
- - Accept-Encoding
- status:
- code: 201
- message: Created
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
"lines": [{"quantity": 3, "amount": "15.00", "taxCode": "O9999999", "taxIncluded":
diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.py
index 8ae37df232..43f4897001 100644
--- a/saleor/plugins/avatax/tests/conftest.py
+++ b/saleor/plugins/avatax/tests/conftest.py
@@ -90,9 +90,10 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):
channel = checkout.channel
shipping_address = checkout.shipping_address
shipping_method = checkout.shipping_method
- shipping_channel_listings = ShippingMethodChannelListing.objects.filter(
- shipping_method=shipping_method, channel=channel
- ).first()
+ shipping_channel_listing = ShippingMethodChannelListing.objects.get(
+ channel=channel,
+ shipping_method=shipping_method,
+ )
checkout_info = CheckoutInfo(
checkout=checkout,
user=checkout.user,
@@ -100,11 +101,11 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):
billing_address=checkout.billing_address,
shipping_address=shipping_address,
delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(shipping_method), shipping_address
+ convert_to_shipping_method_data(shipping_method, shipping_channel_listing),
+ shipping_address,
),
- shipping_method_channel_listings=shipping_channel_listings,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
return checkout_info
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 683e01f3d5..df6ae05fe5 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -14,7 +14,7 @@ from ....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
get_delivery_method_info,
- get_valid_shipping_method_list_for_checkout_info,
+ update_delivery_method_lists_for_checkout_info,
)
from ....checkout.utils import add_variant_to_checkout
from ....core.prices import quantize_price
@@ -45,6 +45,20 @@ from .. import (
from ..plugin import AvataxPlugin
+def avatax_config():
+ return AvataxConfiguration(
+ username_or_account="test",
+ password_or_license="test",
+ use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
+ )
+
+
@pytest.mark.vcr()
@pytest.mark.parametrize(
"with_discount, expected_net, expected_gross, taxes_in_prices",
@@ -1082,10 +1096,16 @@ def test_calculate_checkout_subtotal_for_product_without_tax(
lines = fetch_checkout_lines(checkout)
assert len(lines) == 1
- valid_methods = get_valid_shipping_method_list_for_checkout_info(
- checkout_info, ship_to_pl_address, lines, [], manager
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info,
+ checkout_info.checkout.shipping_method,
+ checkout_info.checkout.collection_point,
+ ship_to_pl_address,
+ lines,
+ [],
+ manager,
+ checkout.channel.shipping_method_listings.all(),
)
- checkout_info.valid_shipping_methods = valid_methods
total = manager.calculate_checkout_subtotal(checkout_info, lines, address, [])
total = quantize_price(total, total.currency)
@@ -1761,18 +1781,9 @@ def test_preprocess_order_creation_wrong_data(
@pytest.mark.vcr
-def test_get_cached_tax_codes_or_fetch(monkeypatch):
+def test_get_cached_tax_codes_or_fetch(monkeypatch, avatax_config):
monkeypatch.setattr("saleor.plugins.avatax.cache.get", lambda x, y: {})
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
tax_codes = get_cached_tax_codes_or_fetch(config)
assert len(tax_codes) > 0
@@ -1856,19 +1867,21 @@ def test_get_checkout_line_tax_rate(
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"])
-
+ delivery_method = checkout_with_item.shipping_method
checkout_info = CheckoutInfo(
checkout=checkout_with_item,
delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(checkout_with_item.shipping_method)
+ convert_to_shipping_method_data(
+ delivery_method,
+ delivery_method.channel_listings.first(),
+ )
),
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
lines = fetch_checkout_lines(checkout_with_item)
checkout_line_info = lines[0]
@@ -1912,19 +1925,22 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(
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"])
+ delivery_method = checkout_with_item.shipping_method
checkout_info = CheckoutInfo(
checkout=checkout_with_item,
delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(checkout_with_item.shipping_method)
+ convert_to_shipping_method_data(
+ delivery_method,
+ delivery_method.channel_listings.first(),
+ )
),
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
lines = fetch_checkout_lines(checkout_with_item)
checkout_line_info = lines[0]
@@ -1981,20 +1997,23 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
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"])
+ delivery_method = checkout_with_item.shipping_method
variant2 = product2.variants.first()
checkout_info = CheckoutInfo(
checkout=checkout_with_item,
delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(checkout_with_item.shipping_method)
+ convert_to_shipping_method_data(
+ delivery_method,
+ delivery_method.channel_listings.first(),
+ )
),
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
add_variant_to_checkout(checkout_info, variant2, 1)
@@ -2209,20 +2228,23 @@ def test_get_checkout_shipping_tax_rate(
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"])
+ delivery_method = checkout_with_item.shipping_method
lines = fetch_checkout_lines(checkout_with_item)
checkout_info = CheckoutInfo(
checkout=checkout_with_item,
delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(checkout_with_item.shipping_method)
+ convert_to_shipping_method_data(
+ delivery_method,
+ delivery_method.channel_listings.first(),
+ )
),
shipping_address=address,
billing_address=None,
channel=checkout_with_item.channel,
user=None,
- shipping_method_channel_listings=None,
- valid_shipping_methods=[],
valid_pick_up_points=[],
+ all_shipping_methods=[],
)
# when
@@ -2702,20 +2724,11 @@ def test_get_tax_code_from_object_meta(product, settings, plugin_configuration):
assert tax_type.description == "DESC"
-def test_api_get_request_handles_request_errors(product, monkeypatch):
+def test_api_get_request_handles_request_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=RequestException())
monkeypatch.setattr("saleor.plugins.avatax.requests.get", mocked_response)
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
response = api_get_request(
@@ -2726,20 +2739,11 @@ def test_api_get_request_handles_request_errors(product, monkeypatch):
assert mocked_response.called
-def test_api_get_request_handles_json_errors(product, monkeypatch):
+def test_api_get_request_handles_json_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=JSONDecodeError("", "", 0))
monkeypatch.setattr("saleor.plugins.avatax.requests.get", mocked_response)
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
response = api_get_request(
@@ -2750,20 +2754,11 @@ def test_api_get_request_handles_json_errors(product, monkeypatch):
assert mocked_response.called
-def test_api_post_request_handles_request_errors(product, monkeypatch):
+def test_api_post_request_handles_request_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=RequestException())
monkeypatch.setattr("saleor.plugins.avatax.requests.post", mocked_response)
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
response = api_post_request(url, {}, config)
@@ -2772,20 +2767,11 @@ def test_api_post_request_handles_request_errors(product, monkeypatch):
assert response == {}
-def test_api_post_request_handles_json_errors(product, monkeypatch):
+def test_api_post_request_handles_json_errors(product, monkeypatch, avatax_config):
mocked_response = Mock(side_effect=JSONDecodeError("", "", 0))
monkeypatch.setattr("saleor.plugins.avatax.requests.post", mocked_response)
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
url = "https://www.avatax.api.com/some-get-path"
response = api_post_request(url, {}, config)
@@ -2943,7 +2929,7 @@ def test_validate_adddress_details(
def test_get_checkout_lines_data_sets_different_tax_code_for_zero_amount(
- settings, channel_USD, plugin_configuration, checkout_with_item
+ settings, channel_USD, plugin_configuration, checkout_with_item, avatax_config
):
# given
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
@@ -2962,16 +2948,7 @@ def test_get_checkout_lines_data_sets_different_tax_code_for_zero_amount(
checkout_with_item, lines, [], get_plugins_manager()
)
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
# when
lines_data = get_checkout_lines_data(checkout_info, lines, config)
@@ -2982,7 +2959,7 @@ def test_get_checkout_lines_data_sets_different_tax_code_for_zero_amount(
def test_get_checkout_lines_data_sets_different_tax_code_only_for_zero_amount(
- settings, channel_USD, plugin_configuration, checkout_with_item
+ settings, channel_USD, plugin_configuration, checkout_with_item, avatax_config
):
# given
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
@@ -3004,16 +2981,7 @@ def test_get_checkout_lines_data_sets_different_tax_code_only_for_zero_amount(
checkout_with_item, lines, [], get_plugins_manager()
)
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
# when
lines_data = get_checkout_lines_data(checkout_info, lines, config)
@@ -3023,6 +2991,87 @@ def test_get_checkout_lines_data_sets_different_tax_code_only_for_zero_amount(
assert lines_data[0]["taxCode"] == "taxcode"
+def test_get_checkout_lines_data_with_collection_point(
+ settings,
+ channel_USD,
+ plugin_configuration,
+ checkout_with_item,
+ avatax_config,
+ warehouse,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
+ plugin_configuration(channel=channel_USD)
+
+ line = checkout_with_item.lines.first()
+ line.quantity = 1
+ line.save()
+
+ variant = line.variant
+ variant.channel_listings.all().update(price_amount=Decimal("11"))
+ variant.product.store_value_in_metadata(
+ {META_CODE_KEY: "taxcode", META_DESCRIPTION_KEY: "tax_description"}
+ )
+ variant.product.save()
+
+ checkout_with_item.shipping_method = None
+ checkout_with_item.collection_point = warehouse
+ checkout_with_item.save()
+
+ lines = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(
+ checkout_with_item, lines, [], get_plugins_manager()
+ )
+ config = avatax_config
+
+ # when
+ lines_data = get_checkout_lines_data(checkout_info, lines, config)
+
+ # then
+ assert len(lines_data) == checkout_with_item.lines.count()
+
+
+def test_get_checkout_lines_data_with_shipping_method(
+ settings,
+ channel_USD,
+ plugin_configuration,
+ checkout_with_item,
+ avatax_config,
+ shipping_method,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
+ plugin_configuration(channel=channel_USD)
+
+ line = checkout_with_item.lines.first()
+ line.quantity = 1
+ line.save()
+
+ variant = line.variant
+ variant.channel_listings.all().update(price_amount=Decimal("11"))
+ variant.product.store_value_in_metadata(
+ {META_CODE_KEY: "taxcode", META_DESCRIPTION_KEY: "tax_description"}
+ )
+ variant.product.save()
+
+ checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.collection_point = None
+ checkout_with_item.save()
+
+ lines = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(
+ checkout_with_item, lines, [], get_plugins_manager()
+ )
+ config = avatax_config
+
+ # when
+ lines_data = get_checkout_lines_data(checkout_info, lines, config)
+
+ # then
+ assert len(lines_data) == checkout_with_item.lines.count() + 1
+ assert lines_data[-1]["itemCode"] == "Shipping"
+
+
def test_get_order_lines_data_sets_different_tax_code_for_zero_amount(
settings, channel_USD, plugin_configuration, order_with_lines
):
@@ -3065,7 +3114,7 @@ def test_get_order_lines_data_sets_different_tax_code_for_zero_amount(
def test_get_order_lines_data_sets_different_tax_code_only_for_zero_amount(
- settings, channel_USD, plugin_configuration, order_with_lines
+ settings, channel_USD, plugin_configuration, order_with_lines, avatax_config
):
# given
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
@@ -3088,16 +3137,7 @@ def test_get_order_lines_data_sets_different_tax_code_only_for_zero_amount(
)
variant.product.save()
- config = AvataxConfiguration(
- username_or_account="test",
- password_or_license="test",
- use_sandbox=False,
- from_street_address="Tęczowa 7",
- from_city="WROCŁAW",
- from_country_area="",
- from_postal_code="53-601",
- from_country="PL",
- )
+ config = avatax_config
# when
lines_data = get_order_lines_data(order_with_lines, config)
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index f4992b7b01..207a879643 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -119,12 +119,6 @@ class BasePlugin:
["Product", Money, Country, TaxedMoney], TaxedMoney
]
- # Apply taxes to the shipping costs based on the shipping address.
- #
- # Overwrite this method if you want to show available shipping methods with
- # taxes.
- apply_taxes_to_shipping: Callable[[Money, "Address", TaxedMoney], TaxedMoney]
-
# Assign tax code dedicated to plugin.
assign_tax_code_to_object_meta: Callable[
[Union["Product", "ProductType"], Union[str, NoneType], Any], Any
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index b13043f6b9..f1aea93fe5 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -253,7 +253,7 @@ class PluginsManager(PaymentInterface):
address: Optional["Address"],
discounts: Iterable[DiscountInfo],
) -> TaxedMoney:
- default_value = base_calculations.base_checkout_shipping_price(
+ default_value = base_calculations.base_checkout_delivery_price(
checkout_info, lines
)
return quantize_price(
@@ -504,23 +504,6 @@ class PluginsManager(PaymentInterface):
price.currency,
)
- def apply_taxes_to_shipping(
- self, price: Money, shipping_address: "Address", channel_slug: str
- ) -> TaxedMoney:
- default_value = quantize_price(
- TaxedMoney(net=price, gross=price), price.currency
- )
- return quantize_price(
- self.__run_method_on_plugins(
- "apply_taxes_to_shipping",
- default_value,
- price,
- shipping_address,
- channel_slug=channel_slug,
- ),
- price.currency,
- )
-
def preprocess_order_creation(
self,
checkout_info: "CheckoutInfo",
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 98405fbbf5..9383fe64b3 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -161,12 +161,6 @@ class PluginSample(BasePlugin):
price = Money("1.0", price.currency)
return TaxedMoney(price, price)
- def apply_taxes_to_shipping(
- self, price, shipping_address, previous_value
- ) -> TaxedMoney:
- price = Money("1.0", price.currency)
- return TaxedMoney(price, price)
-
def get_tax_rate_percentage_value(
self, obj: Union["Product", "ProductType"], country: Country, previous_value
) -> Decimal:
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 2fd1af4c70..90bb5ae39c 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -554,23 +554,6 @@ def test_manager_apply_taxes_to_product(product, plugins, price, channel_USD):
assert TaxedMoney(expected_price, expected_price) == taxed_price
- "plugins, price_amount",
- [(["saleor.plugins.tests.sample_plugins.PluginSample"], "1.0"), ([], "10.0")],
-)
-def test_manager_apply_taxes_to_shipping(
- shipping_method, address, plugins, price_amount, channel_USD
-):
- shipping_price = shipping_method.channel_listings.get(
- channel_id=channel_USD.id
- ).price
- expected_price = Money(price_amount, "USD")
- taxed_price = PluginsManager(plugins=plugins).apply_taxes_to_shipping(
- shipping_price, address, channel_slug=channel_USD.slug
- )
- assert TaxedMoney(expected_price, expected_price) == taxed_price
-
-
def test_manager_sale_created(sale):
plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index 099c72c3ed..dfbd4f9a18 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -243,14 +243,8 @@ class VatlayerPlugin(BasePlugin):
if not checkout_info.delivery_method_info.delivery_method:
return previous_value
shipping_price = getattr(
- checkout_info.delivery_method_info.delivery_method, "price", None
+ checkout_info.delivery_method_info.delivery_method, "price", previous_value
)
- if shipping_price is None:
- if checkout_info.shipping_method_channel_listings:
- shipping_price = checkout_info.shipping_method_channel_listings.price
- else:
- shipping_price = previous_value
-
return get_taxed_shipping_price(shipping_price, taxes)
def calculate_order_shipping(
@@ -485,15 +479,6 @@ class VatlayerPlugin(BasePlugin):
return previous_value
return True
- def apply_taxes_to_shipping(
- self, price: Money, shipping_address: "Address", previous_value: TaxedMoney
- ) -> TaxedMoney:
- if self._skip_plugin(previous_value):
- return previous_value
-
- taxes = self._get_taxes_for_country(shipping_address.country)
- return get_taxed_shipping_price(price, taxes)
-
def apply_taxes_to_product(
self,
product: "Product",
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index 7c30b559f3..cb49ff1fde 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -1,5 +1,4 @@
from decimal import Decimal
-from unittest.mock import Mock
from urllib.parse import urlparse
import pytest
@@ -184,27 +183,6 @@ def test_apply_tax_to_price_no_taxes_raise_typeerror_for_invalid_type():
assert apply_tax_to_price(None, "standard", 100)
-def test_vatlayer_plugin_caches_taxes(
- vatlayer, monkeypatch, product, address, channel_USD
-):
- mocked_taxes = Mock(wraps=get_taxes_for_country)
- monkeypatch.setattr(
- "saleor.plugins.vatlayer.plugin.get_taxes_for_country", mocked_taxes
- )
-
- manager = get_plugins_manager()
- plugin = manager.get_plugin(VatlayerPlugin.PLUGIN_ID, channel_slug=channel_USD.slug)
- variant = product.variants.first()
- channel_listing = variant.channel_listings.get(channel=channel_USD)
- price = variant.get_price(product, [], channel_USD, channel_listing, None)
- address.country = Country("de")
- plugin.apply_taxes_to_product(
- product, price, address.country, TaxedMoney(price, price)
- )
- plugin.apply_taxes_to_shipping(price, address, TaxedMoney(price, price))
- assert mocked_taxes.call_count == 1
-
-
@pytest.mark.parametrize(
"with_discount, expected_net, expected_gross, voucher_amount, taxes_in_prices",
[
diff --git a/saleor/shipping/interface.py b/saleor/shipping/interface.py
index af280fc0a6..798cb67de4 100644
--- a/saleor/shipping/interface.py
+++ b/saleor/shipping/interface.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Dict, Optional
+from typing import Dict, Optional
import graphql
from measurement.measures import Weight
@@ -7,29 +7,26 @@ from prices import Money
from ..graphql.core.utils import from_global_id_or_error
-if TYPE_CHECKING:
- from django.db.models.manager import RelatedManager
-
@dataclass
class ShippingMethodData:
"""Dataclass for storing information about a shipping method."""
id: str
- price: Optional[Money]
+ price: Money
name: Optional[str] = None
description: Optional[str] = None
type: Optional[str] = None
maximum_order_price: Optional[Money] = None
minimum_order_price: Optional[Money] = None
- excluded_products: Optional["RelatedManager"] = None
- channel_listings: Optional["RelatedManager"] = None
minimum_order_weight: Optional[Weight] = None
maximum_order_weight: Optional[Weight] = None
maximum_delivery_days: Optional[int] = None
minimum_delivery_days: Optional[int] = None
metadata: Dict[str, str] = field(default_factory=dict)
private_metadata: Dict[str, str] = field(default_factory=dict)
+ active: bool = True
+ message: str = ""
@property
def is_external(self) -> bool:
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index 99f4fca494..dca6f46b4e 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -1,3 +1,4 @@
+import logging
from typing import TYPE_CHECKING, Optional
from django_countries import countries
@@ -5,7 +6,10 @@ from django_countries import countries
from .interface import ShippingMethodData
if TYPE_CHECKING:
- from .models import ShippingMethod
+ from .models import ShippingMethod, ShippingMethodChannelListing
+
+
+logger = logging.getLogger(__name__)
def default_shipping_zone_exists(zone_pk=None):
@@ -25,23 +29,27 @@ def get_countries_without_shipping_zone():
def convert_to_shipping_method_data(
- shipping_method: Optional["ShippingMethod"],
+ shipping_method: "ShippingMethod", listing: Optional["ShippingMethodChannelListing"]
) -> Optional["ShippingMethodData"]:
- if not shipping_method:
+ if not listing:
return None
+ price = listing.price
+ minimum_order_price = listing.minimum_order_price
+ maximum_order_price = listing.maximum_order_price
+
return ShippingMethodData(
id=str(shipping_method.id),
name=shipping_method.name,
- price=getattr(shipping_method, "price", None),
description=shipping_method.description,
type=shipping_method.type,
- excluded_products=shipping_method.excluded_products,
- channel_listings=shipping_method.channel_listings,
minimum_order_weight=shipping_method.minimum_order_weight,
maximum_order_weight=shipping_method.maximum_order_weight,
maximum_delivery_days=shipping_method.maximum_delivery_days,
minimum_delivery_days=shipping_method.minimum_delivery_days,
metadata=shipping_method.metadata,
private_metadata=shipping_method.private_metadata,
+ price=price,
+ minimum_order_price=minimum_order_price,
+ maximum_order_price=maximum_order_price,
)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index be7a6d54a1..29797b7da1 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -115,6 +115,7 @@ from ..shipping.models import (
ShippingMethodType,
ShippingZone,
)
+from ..shipping.utils import convert_to_shipping_method_data
from ..site.models import SiteSettings
from ..warehouse import WarehouseClickAndCollectOption
from ..warehouse.models import (
@@ -404,6 +405,14 @@ def checkout_with_shipping_required(checkout_with_item, product):
return checkout
+def checkout_with_item_and_shipping_method(checkout_with_item, shipping_method):
+ checkout = checkout_with_item
+ checkout.shipping_method = shipping_method
+ checkout.save()
+ return checkout
+
+
@pytest.fixture
def other_shipping_method(shipping_zone, channel_USD):
method = ShippingMethod.objects.create(
@@ -1014,6 +1023,14 @@ def shipping_method(shipping_zone, channel_USD):
return method
+def shipping_method_data(shipping_method, channel_USD):
+ listing = ShippingMethodChannelListing.objects.filter(
+ channel=channel_USD, shipping_method=shipping_method
+ ).get()
+ return convert_to_shipping_method_data(shipping_method, listing)
+
+
@pytest.fixture
def shipping_method_weight_based(shipping_zone, channel_USD):
method = ShippingMethod.objects.create(