Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow using shipping methods from plugins. (#7975)
Adam Bogdałcd91227c1580
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.pyindex f438352bd1..6c0c86818d 100644--- a/saleor/checkout/base_calculations.py+++ b/saleor/checkout/base_calculations.py@@ -34,7 +34,9 @@ def base_checkout_shipping_price(def calculate_price_for_shipping_method(- checkout_info: "CheckoutInfo", shipping_method_info: ShippingMethodInfo, lines=None+ checkout_info: "CheckoutInfo",+ shipping_method_info: ShippingMethodInfo,+ lines=None,) -> TaxedMoney:"""Return checkout shipping price."""# FIXME: Optimize checkout.is_shipping_required@@ -49,9 +51,14 @@ def calculate_price_for_shipping_method(if not shipping_method or not shipping_required:return zero_taxed_money(checkout_info.checkout.currency)- shipping_price = shipping_method.channel_listings.get(- channel_id=checkout_info.checkout.channel_id,- ).get_total()++ # 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()return quantize_price(TaxedMoney(net=shipping_price, gross=shipping_price), shipping_price.currencydiff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex c1c67f1645..1f2b3428ac 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -86,10 +86,6 @@ def _process_shipping_data_for_order(delivery_method_info = checkout_info.delivery_method_infoshipping_address = delivery_method_info.shipping_address- delivery_method_dict = {- delivery_method_info.order_key: delivery_method_info.delivery_method- }-if checkout_info.user and shipping_address:store_user_address(checkout_info.user, shipping_address, AddressType.SHIPPING, manager=manager@@ -102,7 +98,7 @@ def _process_shipping_data_for_order("shipping_price": shipping_price,"weight": checkout_info.checkout.get_total_weight(lines),}- result.update(delivery_method_dict)+ result.update(delivery_method_info.delivery_method_order_field)result.update(delivery_method_info.delivery_method_name)return resultdiff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 121984411a..d260c2b7a9 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -5,7 +5,9 @@ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Unionfrom django.utils.encoding import smart_text-from ..shipping.models import ShippingMethod, ShippingMethodChannelListing+from ..shipping.interface import ShippingMethodData+from ..shipping.models import ShippingMethodChannelListing+from ..shipping.utils import convert_to_shipping_method_datafrom ..warehouse import WarehouseClickAndCollectOptionfrom ..warehouse.models import Warehouse@@ -42,14 +44,19 @@ class CheckoutInfo:billing_address: Optional["Address"]shipping_address: Optional["Address"]delivery_method_info: "DeliveryMethodBase"- valid_shipping_methods: List["ShippingMethod"]+ valid_shipping_methods: List["ShippingMethodData"]valid_pick_up_points: List["Warehouse"]shipping_method_channel_listings: Optional[ShippingMethodChannelListing]@property- def valid_delivery_methods(self) -> List[Union["ShippingMethod", "Warehouse"]]:+ def valid_delivery_methods(+ self,+ ) -> List[Union["ShippingMethodData", "Warehouse"]]:return list(- itertools.chain(self.valid_shipping_methods, self.valid_pick_up_points)+ itertools.chain(+ self.valid_shipping_methods,+ self.valid_pick_up_points,+ ))def get_country(self) -> str:@@ -64,14 +71,17 @@ class CheckoutInfo:@dataclass(frozen=True)class DeliveryMethodBase:- delivery_method: Optional[Union["ShippingMethod", "Warehouse"]] = None+ delivery_method: Optional[Union["ShippingMethodData", "Warehouse"]] = Noneshipping_address: Optional["Address"] = None- order_key: str = "shipping_method"@propertydef warehouse_pk(self) -> Optional[str]:pass+ @property+ def delivery_method_order_field(self) -> dict:+ return {"shipping_method": self.delivery_method}+@propertydef is_local_collection_point(self) -> bool:return False@@ -95,13 +105,18 @@ class DeliveryMethodBase:@dataclass(frozen=True)class ShippingMethodInfo(DeliveryMethodBase):- delivery_method: "ShippingMethod"+ delivery_method: "ShippingMethodData"shipping_address: Optional["Address"]- order_key: str = "shipping_method"@propertydef delivery_method_name(self) -> Dict[str, Optional[str]]:- return {"shipping_method_name": smart_text(self.delivery_method)}+ return {"shipping_method_name": smart_text(self.delivery_method.name)}++ @property+ def delivery_method_order_field(self) -> dict:+ if not self.delivery_method.is_external:+ return {"shipping_method_id": self.delivery_method.id}+ return {}def is_valid_delivery_method(self) -> bool:return bool(self.shipping_address)@@ -113,23 +128,28 @@ class ShippingMethodInfo(DeliveryMethodBase):)def update_channel_listings(self, checkout_info: "CheckoutInfo") -> None:- checkout_info.shipping_method_channel_listings = (- ShippingMethodChannelListing.objects.filter(- shipping_method=self.delivery_method, channel=checkout_info.channel- ).first()- )+ 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):delivery_method: "Warehouse"shipping_address: Optional["Address"]- order_key: str = "collection_point"@propertydef warehouse_pk(self):return self.delivery_method.pk+ @property+ def delivery_method_order_field(self) -> dict:+ return {"collection_point": self.delivery_method}+@propertydef is_local_collection_point(self):return (@@ -163,12 +183,12 @@ class CollectionPointInfo(DeliveryMethodBase):@singledispatchdef get_delivery_method_info(- delivery_method: Optional[Union["ShippingMethod", "Warehouse"]],+ delivery_method: Optional[Union["ShippingMethodData", "Warehouse"]],address=Optional["Address"],) -> DeliveryMethodBase:if delivery_method is None:return DeliveryMethodBase()- if isinstance(delivery_method, ShippingMethod):+ if isinstance(delivery_method, ShippingMethodData):return ShippingMethodInfo(delivery_method, address)if isinstance(delivery_method, Warehouse):return CollectionPointInfo(delivery_method, delivery_method.address)@@ -222,13 +242,31 @@ def fetch_checkout_info() -> CheckoutInfo:"""Fetch checkout as CheckoutInfo object."""+ from .utils import get_external_shipping_id+channel = checkout.channelshipping_address = checkout.shipping_address+ shipping_channel_listings = None+shipping_method = checkout.shipping_method- shipping_channel_listings = ShippingMethodChannelListing.objects.filter(- shipping_method=shipping_method, channel=channel- ).first()- delivery_method = checkout.collection_point or shipping_method+ if shipping_method:+ shipping_channel_listings = ShippingMethodChannelListing.objects.filter(+ shipping_method=shipping_method, channel=channel+ ).first()+ delivery_method: Optional[+ Union["ShippingMethodData", "Warehouse"]+ ] = convert_to_shipping_method_data(shipping_method)+ else:+ delivery_method = checkout.collection_point++ if not delivery_method:+ external_shipping_method_id = get_external_shipping_id(checkout)+ delivery_method = manager.get_shipping_method(+ checkout=checkout,+ channel_slug=channel.slug,+ shipping_method_id=external_shipping_method_id,+ )+delivery_method_info = get_delivery_method_info(delivery_method, shipping_address)checkout_info = CheckoutInfo(checkout=checkout,@@ -242,8 +280,15 @@ def fetch_checkout_info(valid_pick_up_points=[],)- valid_shipping_methods = get_valid_shipping_method_list_for_checkout_info(- checkout_info, shipping_address, lines, discounts, manager+ valid_shipping_methods: List["ShippingMethodData"] = list(+ itertools.chain(+ get_valid_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+ ),+ ))valid_pick_up_points = get_valid_collection_points_for_checkout_info(shipping_address, lines, checkout_info@@ -263,10 +308,20 @@ def update_checkout_info_shipping_address(manager: "PluginsManager",):checkout_info.shipping_address = address- valid_methods = get_valid_shipping_method_list_for_checkout_info(- checkout_info, address, lines, discounts, manager++ valid_shipping_methods: List["ShippingMethodData"] = list(+ itertools.chain(+ get_valid_shipping_method_list_for_checkout_info(+ checkout_info, address, lines, discounts, manager+ ),+ get_valid_external_shipping_method_list_for_checkout_info(+ checkout_info, address, lines, discounts, manager+ ),+ ))- checkout_info.valid_shipping_methods = valid_methods++ checkout_info.valid_shipping_methods = valid_shipping_methods+delivery_method = checkout_info.delivery_method_info.delivery_methodcheckout_info.delivery_method_info = get_delivery_method_info(delivery_method, address@@ -279,7 +334,7 @@ def get_valid_shipping_method_list_for_checkout_info(lines: Iterable[CheckoutLineInfo],discounts: Iterable["DiscountInfo"],manager: "PluginsManager",-):+) -> List["ShippingMethodData"]:from .utils import get_valid_shipping_methods_for_checkoutcountry_code = shipping_address.country.code if shipping_address else None@@ -290,10 +345,27 @@ def get_valid_shipping_method_list_for_checkout_info(valid_shipping_method = get_valid_shipping_methods_for_checkout(checkout_info, lines, subtotal, country_code=country_code)- valid_shipping_method = (- list(valid_shipping_method) if valid_shipping_method is not None else []++ if valid_shipping_method is None:+ return []++ return [+ convert_to_shipping_method_data(shipping) # type: ignore+ for shipping in valid_shipping_method+ ]+++def get_valid_external_shipping_method_list_for_checkout_info(+ checkout_info: "CheckoutInfo",+ shipping_address: Optional["Address"],+ lines: Iterable[CheckoutLineInfo],+ discounts: Iterable["DiscountInfo"],+ manager: "PluginsManager",+) -> List["ShippingMethodData"]:++ return manager.list_shipping_methods_for_checkout(+ checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug)- return valid_shipping_methoddef get_valid_collection_points_for_checkout_info(@@ -316,7 +388,7 @@ def get_valid_collection_points_for_checkout_info(def update_checkout_info_delivery_method(checkout_info: CheckoutInfo,- delivery_method: Optional[Union["ShippingMethod", "Warehouse"]],+ delivery_method: Optional[Union["ShippingMethodData", "Warehouse"]],):checkout_info.delivery_method_info = get_delivery_method_info(delivery_method, checkout_info.shipping_addressdiff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex 525e42a8c6..0dea85ae41 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -1,6 +1,7 @@import datetimefrom unittest.mock import Mock, patch+import grapheneimport pytestimport pytzfrom django.utils import timezone@@ -16,6 +17,7 @@ from ...discount.models import NotApplicable, Voucher, VoucherChannelListingfrom ...payment.models import Paymentfrom ...plugins.manager import get_plugins_managerfrom ...shipping.models import ShippingMethod, ShippingZone+from ...shipping.utils import convert_to_shipping_method_datafrom .. import AddressType, calculationsfrom ..fetch import (CheckoutInfo,@@ -27,17 +29,21 @@ from ..fetch import ()from ..models import Checkoutfrom ..utils import (+ PRIVATE_META_APP_SHIPPING_ID,add_voucher_to_checkout,calculate_checkout_quantity,cancel_active_payments,change_billing_address_in_checkout,change_shipping_address_in_checkout,clear_delivery_method,+ delete_external_shipping_id,+ get_external_shipping_id,get_voucher_discount_for_checkout,get_voucher_for_checkout,is_fully_paid,recalculate_checkout_discount,remove_voucher_from_checkout,+ set_external_shipping_id,)@@ -68,6 +74,39 @@ def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):assert not delivery_method_info.is_method_in_valid_methods(checkout_info)+@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_is_valid_delivery_method_external_method(+ mock_send_request, checkout_with_item, address, settings, shipping_app+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ mock_send_request.return_value = mock_json_response+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: method_id}+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info++ assert delivery_method_info.is_method_in_valid_methods(checkout_info)++def test_clear_delivery_method(checkout, shipping_method):checkout.shipping_method = shipping_methodcheckout.save()@@ -429,7 +468,7 @@ def test_get_discount_for_checkout_shipping_voucher(checkout=checkout,shipping_address=shipping_address,delivery_method_info=get_delivery_method_info(- shipping_method, shipping_address+ convert_to_shipping_method_data(shipping_method), shipping_address),billing_address=None,channel=channel_USD,@@ -489,7 +528,9 @@ 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(shipping_method, None),+ delivery_method_info=get_delivery_method_info(+ convert_to_shipping_method_data(shipping_method), None+ ),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,@@ -682,7 +723,9 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable()checkout_info = CheckoutInfo(checkout=checkout,- delivery_method_info=get_delivery_method_info(shipping_method),+ delivery_method_info=get_delivery_method_info(+ convert_to_shipping_method_data(shipping_method)+ ),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,@@ -1238,3 +1281,18 @@ def test_chckout_without_delivery_method_creates_empty_delivery_method(assert not delivery_method_info.is_valid_delivery_method()assert not delivery_method_info.is_local_collection_pointassert not delivery_method_info.is_method_in_valid_methods(checkout_info)+++def test_manage_external_shipping_id(checkout):+ app_shipping_id = "abcd"+ initial_private_metadata = {"test": 123}+ checkout.private_metadata = initial_private_metadata++ set_external_shipping_id(checkout, app_shipping_id)+ assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata++ shipping_id = get_external_shipping_id(checkout)+ assert shipping_id == app_shipping_id++ delete_external_shipping_id(checkout)+ assert checkout.private_metadata == initial_private_metadatadiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 96901e6cc7..fdd8ac3c93 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -1,5 +1,5 @@"""Checkout-related utility functions."""-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Unionimport graphenefrom django.core.exceptions import ValidationError@@ -46,9 +46,13 @@ if TYPE_CHECKING:from prices import TaxedMoneyfrom ..account.models import Address+ from ..order.models import Orderfrom .fetch import CheckoutInfo, CheckoutLineInfo+PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"++def get_user_checkout(user: User, checkout_queryset=Checkout.objects.all()) -> Tuple[Optional[Checkout], bool]:@@ -685,7 +689,15 @@ def clear_delivery_method(checkout_info: "CheckoutInfo"):checkout.collection_point = Nonecheckout.shipping_method = Noneupdate_checkout_info_delivery_method(checkout_info, None)- checkout.save(update_fields=["shipping_method", "collection_point", "last_change"])+ delete_external_shipping_id(checkout=checkout)+ checkout.save(+ update_fields=[+ "shipping_method",+ "collection_point",+ "private_metadata",+ "last_change",+ ]+ )def is_fully_paid(@@ -752,3 +764,17 @@ def validate_variants_in_checkout_lines(lines: Iterable["CheckoutLineInfo"]):)})+++def set_external_shipping_id(checkout: Checkout, app_shipping_id: str):+ checkout.store_value_in_private_metadata(+ {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}+ )+++def get_external_shipping_id(container: Union["Checkout", "Order"]):+ return container.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)+++def delete_external_shipping_id(checkout: Checkout):+ checkout.delete_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex 4cf4b6bba6..2f727fb487 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -17,7 +17,7 @@ from . import ChannelContextfrom .dataloaders import ChannelWithHasOrdersByIdLoader-class ChannelContextType(DjangoObjectType):+class ChannelContextTypeForObjectType(graphene.ObjectType):"""A Graphene type that supports resolvers' root as ChannelContext objects."""class Meta:@@ -34,6 +34,18 @@ class ChannelContextType(DjangoObjectType):def resolve_id(root: ChannelContext, _info):return root.node.pk+ @staticmethod+ def resolve_translation(root: ChannelContext, info, language_code):+ # Resolver for TranslationField; needs to be manually specified.+ return resolve_translation(root.node, info, language_code)+++class ChannelContextType(ChannelContextTypeForObjectType, DjangoObjectType):+ """A Graphene type that supports resolvers' root as ChannelContext objects."""++ class Meta:+ abstract = True+@classmethoddef is_type_of(cls, root: Union[ChannelContext, Model], info):# Unwrap node from ChannelContext if it didn't happen already@@ -43,13 +55,8 @@ class ChannelContextType(DjangoObjectType):# Check type that was already unwrapped by the Entity union checkreturn super().is_type_of(root, info)- @staticmethod- def resolve_translation(root: ChannelContext, info, language_code):- # Resolver for TranslationField; needs to be manually specified.- return resolve_translation(root.node, info, language_code)--class ChannelContextTypeWithMetadata(ChannelContextType):+class ChannelContextTypeWithMetadataForObjectType(ChannelContextTypeForObjectType):"""A Graphene type for that uses ChannelContext as root in resolvers.Same as ChannelContextType, but for types that implement ObjectWithMetadata@@ -70,6 +77,19 @@ class ChannelContextTypeWithMetadata(ChannelContextType):return ObjectWithMetadata.resolve_private_metadata(root.node, info)+class ChannelContextTypeWithMetadata(+ ChannelContextTypeWithMetadataForObjectType, ChannelContextType+):+ """A Graphene type for that uses ChannelContext as root in resolvers.++ Same as ChannelContextType, but for types that implement ObjectWithMetadata+ interface.+ """++ class Meta:+ abstract = True++class Channel(CountableDjangoObjectType):has_orders = graphene.Boolean(required=True, description="Whether a channel has associated orders."diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 6971b2d836..1c0d671c2a 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -5,6 +5,7 @@ from promise import Promisefrom ...checkout.fetch import CheckoutInfo, CheckoutLineInfo, get_delivery_method_infofrom ...checkout.models import Checkout, CheckoutLine+from ...shipping.utils import convert_to_shipping_method_datafrom ..account.dataloaders import AddressByIdLoader, UserByUserIdLoaderfrom ..core.dataloaders import DataLoaderfrom ..product.dataloaders import (@@ -224,9 +225,17 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):checkout_info_map = {}for key, checkout, channel in zip(keys, checkouts, channels):- delivery_method = shipping_method_map.get(+ shipping_method = shipping_method_map.get(checkout.shipping_method_id- ) or collection_points_map.get(checkout.collection_point_id)+ )+ if shipping_method:+ delivery_method = convert_to_shipping_method_data(+ shipping_method+ )+ else:+ delivery_method = collection_points_map.get(+ checkout.collection_point_id+ )shipping_address = (address_map.get(checkout.shipping_address_id),)diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex a732e62420..e0c2f32dfc 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -26,10 +26,12 @@ from ...checkout.utils import (change_billing_address_in_checkout,change_shipping_address_in_checkout,clear_delivery_method,+ delete_external_shipping_id,is_shipping_required,recalculate_checkout_discount,remove_promo_code_from_checkout,remove_voucher_from_checkout,+ set_external_shipping_id,validate_variants_in_checkout_lines,)from ...core import analytics@@ -40,7 +42,9 @@ from ...core.transactions import transaction_with_commit_on_errorsfrom ...order import models as order_modelsfrom ...product import models as product_modelsfrom ...product.models import ProductChannelListing+from ...shipping import interface as shipping_interfacefrom ...shipping import models as shipping_models+from ...shipping.utils import convert_to_shipping_method_datafrom ...warehouse import models as warehouse_modelsfrom ...warehouse.availability import check_stock_and_preorder_quantity_bulkfrom ...warehouse.reservations import get_reservation_length, is_reservation_enabled@@ -82,7 +86,12 @@ if TYPE_CHECKING:def clean_delivery_method(checkout_info: "CheckoutInfo",lines: Iterable[CheckoutLineInfo],- method: Optional[Union[models.ShippingMethod, warehouse_models.Warehouse]],+ method: Optional[+ Union[+ shipping_interface.ShippingMethodData,+ warehouse_models.Warehouse,+ ]+ ],) -> bool:"""Check if current shipping method is valid."""@@ -95,7 +104,9 @@ def clean_delivery_method(ERROR_DOES_NOT_SHIP, code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED.value)- if not checkout_info.shipping_address and isinstance(method, models.ShippingMethod):+ if not checkout_info.shipping_address and isinstance(+ method, shipping_interface.ShippingMethodData+ ):raise ValidationError("Cannot choose a shipping method for a checkout without the ""shipping address.",@@ -1089,6 +1100,27 @@ class CheckoutShippingMethodUpdate(BaseMutation):error_type_class = CheckoutErrorerror_type_field = "checkout_errors"+ @staticmethod+ def _resolve_delivery_method_type(id_) -> Optional[str]:+ if id_ is None:+ return None++ possible_types = ("ShippingMethod", "app")+ type_, id_ = from_global_id_or_error(id_)+ str_type = str(type_)++ if str_type not in possible_types:+ raise ValidationError(+ {+ "shipping_method_id": ValidationError(+ "ID does not belong to known shipping methods",+ code=CheckoutErrorCode.INVALID.value,+ )+ }+ )++ return str_type+@classmethoddef perform_mutation(cls, _root, info, shipping_method_id, checkout_id=None, token=None@@ -1116,38 +1148,94 @@ class CheckoutShippingMethodUpdate(BaseMutation):{"shipping_method": ValidationError(ERROR_DOES_NOT_SHIP,- code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED,+ code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED.value,)})- shipping_method = cls.get_node_or_error(- info,- shipping_method_id,- only_type=ShippingMethod,- field="shipping_method_id",- qs=shipping_models.ShippingMethod.objects.prefetch_related(- "postal_code_rules"- ),+ type_name = cls._resolve_delivery_method_type(shipping_method_id)++ if type_name == "ShippingMethod":+ return cls.perform_on_shipping_method(+ info, shipping_method_id, checkout_info, lines, checkout, manager+ )+ return cls.perform_on_external_shipping_method(+ info, shipping_method_id, checkout_info, lines, checkout, manager)- shipping_method_is_valid = clean_delivery_method(+ @staticmethod+ def _check_delivery_method(+ checkout_info,+ lines,+ *,+ delivery_method: Optional[shipping_interface.ShippingMethodData],+ ) -> None:+ delivery_method_is_valid = clean_delivery_method(checkout_info=checkout_info,lines=lines,- method=shipping_method,+ method=delivery_method,)- if not shipping_method_is_valid:+ if not delivery_method_is_valid or not delivery_method:raise ValidationError({"shipping_method": ValidationError("This shipping method is not applicable.",- code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE,+ code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,)})+ @classmethod+ def perform_on_shipping_method(+ cls, info, shipping_method_id, checkout_info, lines, checkout, manager+ ):+ shipping_method = cls.get_node_or_error(+ info,+ shipping_method_id,+ only_type=ShippingMethod,+ field="shipping_method_id",+ qs=shipping_models.ShippingMethod.objects.prefetch_related(+ "postal_code_rules"+ ),+ )+ delivery_method = convert_to_shipping_method_data(shipping_method)++ cls._check_delivery_method(+ checkout_info, lines, delivery_method=delivery_method+ )++ delete_external_shipping_id(checkout=checkout)checkout.shipping_method = shipping_method- checkout.save(update_fields=["shipping_method", "last_change"])+ checkout.save(+ update_fields=["private_metadata", "shipping_method", "last_change"]+ )++ recalculate_checkout_discount(+ manager, checkout_info, lines, info.context.discounts+ )+ manager.checkout_updated(checkout)+ return CheckoutShippingMethodUpdate(checkout=checkout)++ @classmethod+ def perform_on_external_shipping_method(+ cls, info, shipping_method_id, checkout_info, lines, checkout, manager+ ):+ delivery_method = manager.get_shipping_method(+ checkout=checkout,+ channel_slug=checkout.channel.slug,+ shipping_method_id=shipping_method_id,+ )++ cls._check_delivery_method(+ checkout_info, lines, delivery_method=delivery_method+ )++ set_external_shipping_id(checkout=checkout, app_shipping_id=delivery_method.id)+ checkout.shipping_method = None+ checkout.save(+ update_fields=["private_metadata", "shipping_method", "last_change"]+ )+recalculate_checkout_discount(manager, checkout_info, lines, info.context.discounts)@@ -1186,14 +1274,42 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):),)+ delivery_method = convert_to_shipping_method_data(shipping_method)cls._check_delivery_method(- checkout_info, lines, shipping_method=shipping_method, collection_point=None+ checkout_info, lines, shipping_method=delivery_method, collection_point=None)cls._update_delivery_method(manager,checkout,shipping_method=shipping_method,+ external_shipping_method=None,+ collection_point=None,+ )+ recalculate_checkout_discount(+ manager, checkout_info, lines, info.context.discounts+ )+ return CheckoutDeliveryMethodUpdate(checkout=checkout)++ @classmethod+ def perform_on_external_shipping_method(+ cls, info, shipping_method_id, checkout_info, lines, checkout, manager+ ):+ delivery_method = manager.get_shipping_method(+ checkout=checkout,+ channel_slug=checkout.channel.slug,+ shipping_method_id=shipping_method_id,+ )++ cls._check_delivery_method(+ checkout_info, lines, shipping_method=delivery_method, collection_point=None+ )++ cls._update_delivery_method(+ manager,+ checkout,+ shipping_method=None,+ external_shipping_method=delivery_method,collection_point=None,)recalculate_checkout_discount(@@ -1219,7 +1335,11 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):collection_point=collection_point,)cls._update_delivery_method(- manager, checkout, shipping_method=None, collection_point=collection_point+ manager,+ checkout,+ shipping_method=None,+ external_shipping_method=None,+ collection_point=collection_point,)return CheckoutDeliveryMethodUpdate(checkout=checkout)@@ -1228,7 +1348,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):checkout_info,lines,*,- shipping_method: Optional[ShippingMethod],+ shipping_method: Optional[shipping_interface.ShippingMethodData],collection_point: Optional[Warehouse]) -> None:delivery_method = shipping_method@@ -1257,12 +1377,24 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):checkout: Checkout,*,shipping_method: Optional[ShippingMethod],+ external_shipping_method: Optional[shipping_interface.ShippingMethodData],collection_point: Optional[Warehouse]) -> None:+ if external_shipping_method:+ set_external_shipping_id(+ checkout=checkout, app_shipping_id=external_shipping_method.id+ )+ else:+ delete_external_shipping_id(checkout=checkout)checkout.shipping_method = shipping_methodcheckout.collection_point = collection_pointcheckout.save(- update_fields=["shipping_method", "collection_point", "last_change"]+ update_fields=[+ "private_metadata",+ "shipping_method",+ "collection_point",+ "last_change",+ ])manager.checkout_updated(checkout)@@ -1271,7 +1403,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):if id_ is None:return None- possible_types = ("Warehouse", "ShippingMethod")+ possible_types = ("Warehouse", "ShippingMethod", "app")type_, id_ = from_global_id_or_error(id_)str_type = str(type_)@@ -1318,7 +1450,11 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):return cls.perform_on_collection_point(info, delivery_method_id, checkout_info, lines, checkout, manager)- return cls.perform_on_shipping_method(+ if type_name == "ShippingMethod":+ return cls.perform_on_shipping_method(+ info, delivery_method_id, checkout_info, lines, checkout, manager+ )+ return cls.perform_on_external_shipping_method(info, delivery_method_id, checkout_info, lines, checkout, manager)diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 671c6b206a..2303f124d7 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -706,7 +706,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(59):+ with django_assert_num_queries(58):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(59):+ with django_assert_num_queries(58):variables = {"token": checkout.token,"lines": [],@@ -859,7 +859,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(58):+ with django_assert_num_queries(57):variables = {"checkoutId": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -872,7 +872,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(58):+ with django_assert_num_queries(57):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.pyindex e704d2db15..4da6906261 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@@ -9,6 +9,7 @@ from .....checkout.fetch import (get_delivery_method_info,)from .....plugins.manager import get_plugins_manager+from .....shipping.utils import convert_to_shipping_method_datafrom ....tests.utils import get_graphql_contentMUTATION_UPDATE_SHIPPING_METHOD = """@@ -59,11 +60,13 @@ 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(- old_shipping_method, None+ convert_to_shipping_method_data(old_shipping_method), None)checkout_info.shipping_method_channel_listings = Nonemock_clean_shipping.assert_called_once_with(- checkout_info=checkout_info, lines=lines, method=shipping_method+ checkout_info=checkout_info,+ lines=lines,+ method=convert_to_shipping_method_data(shipping_method),)errors = data["errors"]assert not errors@@ -97,11 +100,13 @@ 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(- old_shipping_method, None+ convert_to_shipping_method_data(old_shipping_method), None)checkout_info.shipping_method_channel_listings = Nonemock_clean_shipping.assert_called_once_with(- checkout_info=checkout_info, lines=lines, method=shipping_method+ checkout_info=checkout_info,+ lines=lines,+ method=convert_to_shipping_method_data(shipping_method),)errors = data["errors"]assert not errorsdiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 3be5508b1e..54a4894f96 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -30,7 +30,11 @@ from ....checkout.fetch import (get_delivery_method_info,)from ....checkout.models import Checkout-from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity+from ....checkout.utils import (+ PRIVATE_META_APP_SHIPPING_ID,+ add_variant_to_checkout,+ calculate_checkout_quantity,+)from ....core.payments import PaymentInterfacefrom ....payment import TransactionKindfrom ....payment.interface import GatewayResponse@@ -38,6 +42,7 @@ from ....plugins.manager import PluginsManager, get_plugins_managerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGatewayfrom ....product.models import ProductChannelListing, ProductVariantfrom ....shipping import models as shipping_models+from ....shipping.utils import convert_to_shipping_method_datafrom ....warehouse.models import Reservation, Stockfrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (@@ -60,7 +65,8 @@ 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)- is_valid_method = clean_delivery_method(checkout_info, lines, shipping_method)+ delivery_method = convert_to_shipping_method_data(shipping_method)+ is_valid_method = clean_delivery_method(checkout_info, lines, delivery_method)assert is_valid_method is True@@ -2902,11 +2908,13 @@ 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(- old_shipping_method, None+ convert_to_shipping_method_data(old_shipping_method), None)checkout_info.shipping_method_channel_listings = Nonemock_clean_shipping.assert_called_once_with(- checkout_info=checkout_info, lines=lines, method=shipping_method+ checkout_info=checkout_info,+ lines=lines,+ method=convert_to_shipping_method_data(shipping_method),)errors = data["errors"]if is_valid_shipping_method:@@ -2922,6 +2930,50 @@ def test_checkout_shipping_method_update(assert checkout.shipping_method is None[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_checkout_shipping_method_update_external_shipping_method(+ mock_send_request,+ staff_api_client,+ address,+ checkout_with_item,+ shipping_app,+ channel_USD,+ settings,+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])++ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_SHIPPING_METHOD,+ {"token": checkout_with_item.token, "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]+ checkout.refresh_from_db()++ errors = data["errors"]+ assert not errors+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata++@pytest.mark.parametrize("is_valid_delivery_method", (True, False))@pytest.mark.parametrize("delivery_method, node_name, attribute_name",@@ -2943,6 +2995,10 @@ def test_checkout_delivery_method_update():checkout = checkout_with_item_for_ccold_delivery_method = getattr(checkout, attribute_name)+ 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)query = MUTATION_UPDATE_DELIVERY_METHODmock_clean_delivery.return_value = is_valid_delivery_method@@ -2962,7 +3018,7 @@ def test_checkout_delivery_method_update()checkout_info.shipping_method_channel_listings = Nonemock_clean_delivery.assert_called_once_with(- checkout_info=checkout_info, lines=lines, method=delivery_method+ checkout_info=checkout_info, lines=lines, method=shipping_method_data)errors = data["errors"]if is_valid_delivery_method:@@ -2977,6 +3033,59 @@ def test_checkout_delivery_method_update(assert checkout.shipping_method is None[email protected]("is_valid_delivery_method", (True, False))[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")+def test_checkout_delivery_method_update_external_shipping(+ mock_clean_delivery,+ mock_send_request,+ api_client,+ checkout_with_item_for_cc,+ is_valid_delivery_method,+ settings,+ shipping_app,+ channel_USD,+):+ checkout = checkout_with_item_for_cc+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = is_valid_delivery_method++ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ response = api_client.post_graphql(+ query, {"token": checkout.token, "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ errors = data["errors"]+ if is_valid_delivery_method:+ assert not errors+ assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata+ else:+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert (+ errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ )+ assert PRIVATE_META_APP_SHIPPING_ID not in checkout.private_metadata++@patch("saleor.graphql.checkout.mutations.clean_delivery_method")def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_error(mock_clean_delivery,diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 2bba7df4e1..f07bc2a5d8 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -3,6 +3,7 @@ from promise import Promisefrom ...checkout import calculations, modelsfrom ...checkout.utils import (+ get_external_shipping_id,get_valid_collection_points_for_checkout,get_valid_shipping_methods_for_checkout,)@@ -10,6 +11,7 @@ from ...core.exceptions import PermissionDeniedfrom ...core.permissions import AccountPermissionsfrom ...core.taxes import zero_taxed_moneyfrom ...core.tracing import traced_resolver+from ...shipping.utils import convert_to_shipping_method_datafrom ...warehouse.reservations import is_reservation_enabledfrom ..account.dataloaders import AddressByIdLoaderfrom ..account.utils import requestor_has_access@@ -294,6 +296,19 @@ class Checkout(CountableDjangoObjectType):@staticmethoddef resolve_shipping_method(root: models.Checkout, info):+ external_app_shipping_id = get_external_shipping_id(root)++ if external_app_shipping_id:+ shipping_method = info.context.plugins.get_shipping_method(+ checkout=root,+ channel_slug=root.channel.slug,+ shipping_method_id=external_app_shipping_id,+ )+ if shipping_method:+ return ChannelContext(+ node=shipping_method, channel_slug=root.channel.slug+ )+if not root.shipping_method_id:return None@@ -459,8 +474,10 @@ class Checkout(CountableDjangoObjectType):shipping.price = taxed_price.grosselse:shipping.price = taxed_price.net++ node = convert_to_shipping_method_data(shipping)available_with_channel_context.append(- ChannelContext(node=shipping, channel_slug=channel_slug)+ ChannelContext(node=node, channel_slug=channel_slug))return available_with_channel_context@@ -493,9 +510,27 @@ class Checkout(CountableDjangoObjectType):discounts = DiscountsByDateTimeLoader(info.context).load(info.context.request_time)- return Promise.all([address, lines, checkout_info, discounts, channel]).then(- calculate_available_shipping_methods- )++ 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++ return shipping_methods.then(with_external_shipping_methods)@staticmethod@traced_resolverdiff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.pyindex 45468f1735..38f32db367 100644--- a/saleor/graphql/meta/mutations.py+++ b/saleor/graphql/meta/mutations.py@@ -162,7 +162,29 @@ class MetadataInput(graphene.InputObjectType):value = graphene.String(required=True, description="Value of a metadata item.")-class UpdateMetadata(BaseMetadataMutation):+class ShippingMethodMetadataMixin:+ @classmethod+ def get_instance(cls, info, **data):+ object_id = data.get("id")+ qs = data.get("qs", None)++ type_name, _ = from_global_id_or_error(object_id)+ # ShippingMethod type isn't model-based class+ if type_name == "ShippingMethod":+ qs = shipping_models.ShippingMethod.objects++ return cls.get_node_or_error(info, object_id, qs=qs)++ @classmethod+ def get_model_for_type_name(cls, info, type_name):+ # ShippingMethod type isn't model-based class+ if type_name == "ShippingMethod":+ return shipping_models.ShippingMethod+ graphene_type = info.schema.get_type(type_name).graphene_type+ return graphene_type._meta.model+++class UpdateMetadata(ShippingMethodMetadataMixin, BaseMetadataMutation):class Meta:description = "Updates metadata of an object."permission_map = PUBLIC_META_PERMISSION_MAP@@ -189,7 +211,7 @@ class UpdateMetadata(BaseMetadataMutation):return cls.success_response(instance)-class DeleteMetadata(BaseMetadataMutation):+class DeleteMetadata(ShippingMethodMetadataMixin, BaseMetadataMutation):class Meta:description = "Delete metadata of an object."permission_map = PUBLIC_META_PERMISSION_MAP@@ -215,7 +237,7 @@ class DeleteMetadata(BaseMetadataMutation):return cls.success_response(instance)-class UpdatePrivateMetadata(BaseMetadataMutation):+class UpdatePrivateMetadata(ShippingMethodMetadataMixin, BaseMetadataMutation):class Meta:description = "Updates private metadata of an object."permission_map = PRIVATE_META_PERMISSION_MAP@@ -242,7 +264,7 @@ class UpdatePrivateMetadata(BaseMetadataMutation):return cls.success_response(instance)-class DeletePrivateMetadata(BaseMetadataMutation):+class DeletePrivateMetadata(ShippingMethodMetadataMixin, BaseMetadataMutation):class Meta:description = "Delete object's private metadata."permission_map = PRIVATE_META_PERMISSION_MAPdiff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 09d012e286..08e99e5523 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -28,6 +28,7 @@ from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types.common import OrderErrorfrom ...product.types import ProductVariant+from ...shipping.utils import get_shipping_model_by_object_idfrom ..types import Orderfrom ..utils import (prepare_insufficient_stock_order_validation_errors,@@ -105,6 +106,10 @@ class DraftOrderCreate(ModelMutation, I18nMixin):redirect_url = data.pop("redirect_url", None)channel_id = data.pop("channel_id", None)+ shipping_method = get_shipping_model_by_object_id(+ object_id=data.pop("shipping_method", None), raise_error=False+ )+cleaned_input = super().clean_input(info, instance, data)channel = cls.clean_channel_id(info, instance, cleaned_input, channel_id)@@ -119,6 +124,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):lines = data.pop("lines", None)cls.clean_lines(cleaned_input, lines, channel)+ cleaned_input["shipping_method"] = shipping_methodcleaned_input["status"] = OrderStatus.DRAFTcleaned_input["origin"] = OrderOrigin.DRAFTdisplay_gross_prices = info.context.site.settings.display_gross_pricesdiff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 5df0031784..002574dd71 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -10,6 +10,7 @@ from graphene import relayfrom promise import Promisefrom ...account.models import Address+from ...checkout.utils import get_external_shipping_idfrom ...core.anonymize import obfuscate_address, obfuscate_emailfrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import (@@ -1042,6 +1043,19 @@ class Order(CountableDjangoObjectType):@staticmethoddef resolve_shipping_method(root: models.Order, info):+ external_app_shipping_id = get_external_shipping_id(root)++ if external_app_shipping_id:+ shipping_method = info.context.plugins.get_shipping_method(+ checkout=root,+ channel_slug=root.channel.slug,+ shipping_method_id=external_app_shipping_id,+ )+ if shipping_method:+ return ChannelContext(+ node=shipping_method, channel_slug=root.channel.slug+ )+if not root.shipping_method_id:return None@@ -1073,34 +1087,34 @@ class Order(CountableDjangoObjectType):@traced_resolver# TODO: We should optimize it in/after PR#5819def resolve_available_shipping_methods(root: models.Order, info):- available = get_valid_shipping_methods_for_order(root)- if available is None:- return []- available_shipping_methods = []+ instances = []manager = info.context.plugins- 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- ]+ 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 instancesdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3d27e1846b..e9b75ed170 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6118,14 +6118,10 @@ enum ShippingErrorCode {type ShippingMethod implements Node & ObjectWithMetadata {id: ID!- name: String!- description: JSONString- minimumOrderWeight: Weight- maximumOrderWeight: Weight- maximumDeliveryDays: Int- minimumDeliveryDays: IntprivateMetadata: [MetadataItem]!metadata: [MetadataItem]!+ name: String!+ description: JSONStringtype: ShippingMethodTypeEnumtranslation(languageCode: LanguageCodeEnum!): ShippingMethodTranslationchannelListings: [ShippingMethodChannelListing!]@@ -6134,6 +6130,10 @@ type ShippingMethod implements Node & ObjectWithMetadata {minimumOrderPrice: MoneypostalCodeRules: [ShippingMethodPostalCodeRule]excludedProducts(before: String, after: String, first: Int, last: Int): ProductCountableConnection+ minimumOrderWeight: Weight+ maximumOrderWeight: Weight+ maximumDeliveryDays: Int+ minimumDeliveryDays: Int}type ShippingMethodChannelListing implements Node {@@ -7265,6 +7265,7 @@ enum WebhookEventTypeEnum {PAYMENT_PROCESSPAYMENT_REFUNDPAYMENT_VOID+ SHIPPING_LIST_METHODS_FOR_CHECKOUTTRANSLATION_CREATEDTRANSLATION_UPDATED}@@ -7310,6 +7311,7 @@ enum WebhookSampleEventTypeEnum {PAYMENT_PROCESSPAYMENT_REFUNDPAYMENT_VOID+ SHIPPING_LIST_METHODS_FOR_CHECKOUTTRANSLATION_CREATEDTRANSLATION_UPDATED}diff --git a/saleor/graphql/shipping/bulk_mutations.py b/saleor/graphql/shipping/bulk_mutations.pyindex d31b61bb54..e3a5b47597 100644--- a/saleor/graphql/shipping/bulk_mutations.py+++ b/saleor/graphql/shipping/bulk_mutations.py@@ -36,3 +36,9 @@ class ShippingPriceBulkDelete(ModelBulkDeleteMutation):permissions = (ShippingPermissions.MANAGE_SHIPPING,)error_type_class = ShippingErrorerror_type_field = "shipping_errors"++ @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+ )diff --git a/saleor/graphql/shipping/mutations/channels.py b/saleor/graphql/shipping/mutations/channels.pyindex e3188ebb7e..3ce3f56f74 100644--- a/saleor/graphql/shipping/mutations/channels.py+++ b/saleor/graphql/shipping/mutations/channels.py@@ -16,6 +16,7 @@ from ...channel.mutations import BaseChannelListingMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types.common import ShippingErrorfrom ...core.validators import validate_price_precision+from ...shipping.utils import get_shipping_model_by_object_idfrom ..types import ShippingMethodif TYPE_CHECKING:@@ -232,9 +233,8 @@ class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):@classmethoddef perform_mutation(cls, _root, info, id, input):- shipping_method = cls.get_node_or_error(- info, id, only_type=ShippingMethod, field="id"- )+ shipping_method = get_shipping_model_by_object_id(id)+errors = defaultdict(list)clean_channels = cls.clean_channels(info, input, errors, ShippingErrorCode.DUPLICATED_INPUT_ITEM.valuediff --git a/saleor/graphql/shipping/mutations/shippings.py b/saleor/graphql/shipping/mutations/shippings.pyindex 011e200ae6..afc46455bd 100644--- a/saleor/graphql/shipping/mutations/shippings.py+++ b/saleor/graphql/shipping/mutations/shippings.py@@ -21,6 +21,7 @@ from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.scalars import WeightScalarfrom ...core.types.common import ShippingErrorfrom ...product import types as product_types+from ...shipping import types as shipping_typesfrom ...utils import resolve_global_ids_to_primary_keysfrom ...utils.validators import check_for_duplicatesfrom ..enums import PostalCodeRuleInclusionTypeEnum, ShippingMethodTypeEnum@@ -36,7 +37,7 @@ class ShippingPostalCodeRulesCreateInputRange(graphene.InputObjectType):class ShippingPriceInput(graphene.InputObjectType):name = graphene.String(description="Name of the shipping method.")- description = graphene.JSONString(description="Shipping method description (JSON).")+ description = graphene.JSONString(description="Shipping method description.")minimum_order_weight = WeightScalar(description="Minimum order weight to use this shipping method.")@@ -256,6 +257,23 @@ class ShippingZoneDelete(ModelDeleteMutation):return response+class ShippingMethodTypeMixin:+ @classmethod+ def get_type_for_model(cls):+ return shipping_types.ShippingMethod++ @classmethod+ def get_instance(cls, info, **data):+ object_id = data.get("id")+ if object_id:+ instance = cls.get_node_or_error(+ info, object_id, qs=models.ShippingMethod.objects+ )+ else:+ instance = cls._meta.model()+ return instance++class ShippingPriceMixin:@classmethoddef clean_input(cls, info, instance, data, input_cls=None):@@ -409,7 +427,7 @@ class ShippingPriceMixin:)-class ShippingPriceCreate(ShippingPriceMixin, ModelMutation):+class ShippingPriceCreate(ShippingPriceMixin, ShippingMethodTypeMixin, ModelMutation):shipping_zone = graphene.Field(ShippingZone,description="A shipping zone to which the shipping method belongs.",@@ -441,7 +459,7 @@ class ShippingPriceCreate(ShippingPriceMixin, ModelMutation):return response-class ShippingPriceUpdate(ShippingPriceMixin, ModelMutation):+class ShippingPriceUpdate(ShippingPriceMixin, ShippingMethodTypeMixin, ModelMutation):shipping_zone = graphene.Field(ShippingZone,description="A shipping zone to which the shipping method belongs.",@@ -494,7 +512,7 @@ class ShippingPriceDelete(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, **data):shipping_method = cls.get_node_or_error(- info, data.get("id"), only_type=ShippingMethod+ info, data.get("id"), qs=models.ShippingMethod.objects)shipping_method_id = shipping_method.idshipping_zone = shipping_method.shipping_zone@@ -536,7 +554,7 @@ class ShippingPriceExcludeProducts(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, **data):shipping_method = cls.get_node_or_error(- info, data.get("id"), only_type=ShippingMethod+ info, data.get("id"), qs=models.ShippingMethod.objects)input = data.get("input")product_ids = input.get("products", [])@@ -581,8 +599,9 @@ class ShippingPriceRemoveProductFromExclude(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, **data):shipping_method = cls.get_node_or_error(- info, data.get("id"), only_type=ShippingMethod+ info, data.get("id"), qs=models.ShippingMethod.objects)+product_ids = data.get("products")if product_ids:product_db_ids = cls.get_global_ids_or_error(diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.pyindex 51a64cd1a9..2fdb6a8acc 100644--- a/saleor/graphql/shipping/types.py+++ b/saleor/graphql/shipping/types.py@@ -1,3 +1,5 @@+from typing import Union+import graphenefrom graphene import relay@@ -5,6 +7,7 @@ from ...core.permissions import ShippingPermissionsfrom ...core.tracing import traced_resolverfrom ...core.weight import convert_weight_to_default_weight_unitfrom ...shipping import models+from ...shipping.interface import ShippingMethodDatafrom ..channel import ChannelQsContextfrom ..channel.dataloaders import ChannelByIdLoaderfrom ..channel.types import (@@ -12,10 +15,11 @@ from ..channel.types import (ChannelContext,ChannelContextType,ChannelContextTypeWithMetadata,+ ChannelContextTypeWithMetadataForObjectType,)from ..core.connection import CountableDjangoObjectTypefrom ..core.fields import ChannelContextFilterConnectionField-from ..core.types import CountryDisplay, Money, MoneyRange+from ..core.types import CountryDisplay, Money, MoneyRange, Weightfrom ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..shipping.resolvers import resolve_price_range@@ -69,7 +73,10 @@ class ShippingMethodPostalCodeRule(CountableDjangoObjectType):]-class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):+class ShippingMethod(ChannelContextTypeWithMetadataForObjectType):+ 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.")type = ShippingMethodTypeEnum(description="Type of the shipping method.")translation = TranslationField(ShippingMethodTranslation,@@ -99,6 +106,18 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):"saleor.graphql.product.types.products.Product",description="List of excluded products for the shipping method.",)+ minimum_order_weight = graphene.Field(+ Weight, description="Minimum order weight to use this shipping method."+ )+ maximum_order_weight = graphene.Field(+ Weight, description="Maximum order weight to use this shipping method."+ )+ maximum_delivery_days = graphene.Int(+ description="Maximum number of days for delivery."+ )+ minimum_delivery_days = graphene.Int(+ description="Minimal number of days for delivery."+ )class Meta:default_resolver = ChannelContextType.resolver_with_context@@ -106,28 +125,32 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):"Shipping method are the methods you'll use to get customer's orders to ""them. They are directly exposed to the customers.")- model = models.ShippingMethodinterfaces = [relay.Node, ObjectWithMetadata]- only_fields = [- "id",- "maximum_order_weight",- "minimum_order_weight",- "maximum_delivery_days",- "minimum_delivery_days",- "name",- "description",- ]@staticmethod- def resolve_price(root: ChannelContext[models.ShippingMethod], info, **_kwargs):+ 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_price(+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],+ info,+ **_kwargs+ ):# Price field are dynamically generated in available_shipping_methods resolverprice = getattr(root.node, "price", None)- if price:+ if price is not None:return priceif not root.channel_slug:return None+ if getattr(root.node, "is_external", False):+ return None+return (ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(info.context@@ -138,11 +161,20 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@staticmethoddef resolve_maximum_order_price(- root: ChannelContext[models.ShippingMethod], info, **_kwargs+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],+ info,+ **_kwargs):+ maximum_order_price = getattr(root.node, "maximum_order_price", None)+ if maximum_order_price is not None:+ return maximum_order_price+if not root.channel_slug:return None+ if getattr(root.node, "is_external", False):+ return None+return (ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(info.context@@ -153,11 +185,20 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@staticmethoddef resolve_minimum_order_price(- root: ChannelContext[models.ShippingMethod], info, **_kwargs+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],+ info,+ **_kwargs):+ minimum_order_price = getattr(root.node, "minimum_order_price", None)+ if minimum_order_price is not None:+ return minimum_order_price+if not root.channel_slug:return None+ if getattr(root.node, "is_external", False):+ return None+return (ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(info.context@@ -168,27 +209,37 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@staticmethoddef resolve_maximum_order_weight(- root: ChannelContext[models.ShippingMethod], *_args+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]], *_args):return convert_weight_to_default_weight_unit(root.node.maximum_order_weight)@staticmethoddef resolve_postal_code_rules(- root: ChannelContext[models.ShippingMethod], info, **_kwargs+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],+ info,+ **_kwargs):+ if getattr(root.node, "is_external", False):+ return None+return PostalCodeRulesByShippingMethodIdLoader(info.context).load(root.node.id)@staticmethoddef resolve_minimum_order_weight(- root: ChannelContext[models.ShippingMethod], *_args+ root: ChannelContext[Union[ShippingMethodData, 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[models.ShippingMethod], info, **_kwargs+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],+ info,+ **_kwargs):+ if getattr(root.node, "is_external", False):+ return None+return ShippingMethodChannelListingByShippingMethodIdLoader(info.context).load(root.node.id)@@ -196,9 +247,16 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@staticmethod@permission_required(ShippingPermissions.MANAGE_SHIPPING)def resolve_excluded_products(- root: ChannelContext[models.ShippingMethod], _info, **_kwargs+ root: ChannelContext[Union[ShippingMethodData, models.ShippingMethod]],+ _info,+ **_kwargs):- return ChannelQsContext(qs=root.node.excluded_products.all(), channel_slug=None)+ if root.node.excluded_products is None:+ return None++ return ChannelQsContext(+ qs=root.node.excluded_products.all(), channel_slug=None # type: ignore+ )class ShippingZone(ChannelContextTypeWithMetadata, CountableDjangoObjectType):diff --git a/saleor/graphql/shipping/utils.py b/saleor/graphql/shipping/utils.pynew file mode 100644index 0000000000..3c20b84dd0--- /dev/null+++ b/saleor/graphql/shipping/utils.py@@ -0,0 +1,32 @@+from typing import List, Optional++from django.core.exceptions import ValidationError++from ...shipping.models import ShippingMethod+from ..core.utils import from_global_id_or_error+++def get_shipping_model_by_object_id(+ object_id: Optional[str], raise_error: bool = True+) -> Optional[ShippingMethod]:+ if object_id:+ _, object_pk = from_global_id_or_error(object_id)+ shipping_method = ShippingMethod.objects.filter(pk=object_pk).first()+ if not shipping_method and raise_error:+ raise ValidationError(+ {+ "id": ValidationError(+ "Couldn't resolve to a node: %s" % object_id, code="not_found"+ )+ }+ )+ return shipping_method+ return None+++def get_instances_by_object_ids(object_ids: List[str]) -> List[ShippingMethod]:+ model_ids = []+ for object_id in object_ids:+ _, object_pk = from_global_id_or_error(object_id)+ model_ids.append(object_pk)+ return ShippingMethod.objects.filter(pk__in=model_ids)diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.pyindex 53277fd237..9a09e8c301 100644--- a/saleor/graphql/shop/resolvers.py+++ b/saleor/graphql/shop/resolvers.py@@ -7,6 +7,8 @@ from ..channel import ChannelContext@traced_resolverdef resolve_available_shipping_methods(info, channel_slug: str, address):+ instances = []+ manager = info.context.pluginsavailable = ShippingMethod.objects.for_channel(channel_slug)if address and address.country:available = available.filter(@@ -20,27 +22,27 @@ def resolve_available_shipping_methods(info, channel_slug: str, address):else:address = Address()- if available is None:- return []- manager = info.context.plugins- 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 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)- if display_gross:- shipping_method.price = taxed_price.gross- else:- shipping_method.price = taxed_price.net-- return [- ChannelContext(node=shipping, channel_slug=channel_slug)- for shipping in available- ]+ 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++ instances += [+ ChannelContext(node=shipping, channel_slug=channel_slug)+ for shipping in available+ ]++ return instancesdef get_shipping_method_to_shipping_price_mapping(shipping_methods, channel_slug):diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.pyindex 228af69b4f..4e41a9813b 100644--- a/saleor/graphql/translations/mutations.py+++ b/saleor/graphql/translations/mutations.py@@ -15,6 +15,7 @@ from ..core.enums import LanguageCodeEnumfrom ..core.mutations import BaseMutation, ModelMutation, registryfrom ..core.types.common import TranslationErrorfrom ..product.types import Product, ProductVariant+from ..shipping import types as shipping_typesfrom ..shop.types import Shopfrom . import types as translation_types@@ -363,6 +364,16 @@ class ShippingPriceTranslate(BaseTranslateMutation):instance = ChannelContext(node=response.shippingMethod, channel_slug=None)return cls(**{cls._meta.return_field_name: instance})+ @classmethod+ def get_type_for_model(cls):+ return shipping_types.ShippingMethod++ @classmethod+ def get_node_or_error(cls, info, node_id, field="id", only_type=None, qs=None):+ return super().get_node_or_error(+ info, node_id, field, qs=shipping_models.ShippingMethod.objects+ )+class MenuItemTranslate(BaseTranslateMutation):class Arguments:diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.pyindex 6a35974d75..7259fa5a7d 100644--- a/saleor/plugins/avatax/tests/conftest.py+++ b/saleor/plugins/avatax/tests/conftest.py@@ -3,6 +3,7 @@ import pytestfrom ....account.models import Addressfrom ....checkout.fetch import CheckoutInfo, get_delivery_method_infofrom ....shipping.models import ShippingMethodChannelListing+from ....shipping.utils import convert_to_shipping_method_datafrom ...models import PluginConfigurationfrom ..plugin import AvataxPlugin@@ -92,7 +93,7 @@ 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(- shipping_method, shipping_address+ convert_to_shipping_method_data(shipping_method), shipping_address),shipping_method_channel_listings=shipping_channel_listings,valid_shipping_methods=[],diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 39a5956f29..0cc9a19145 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -21,6 +21,7 @@ from ....core.prices import quantize_pricefrom ....core.taxes import TaxError, TaxTypefrom ....product import ProductTypeKindfrom ....product.models import Product, ProductType+from ....shipping.utils import convert_to_shipping_method_datafrom ...manager import get_plugins_managerfrom ...models import PluginConfigurationfrom .. import (@@ -959,7 +960,7 @@ def test_get_checkout_line_tax_rate(checkout_info = CheckoutInfo(checkout=checkout_with_item,delivery_method_info=get_delivery_method_info(- checkout_with_item.shipping_method+ convert_to_shipping_method_data(checkout_with_item.shipping_method)),shipping_address=address,billing_address=None,@@ -1015,7 +1016,7 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(checkout_info = CheckoutInfo(checkout=checkout_with_item,delivery_method_info=get_delivery_method_info(- checkout_with_item.shipping_method+ convert_to_shipping_method_data(checkout_with_item.shipping_method)),shipping_address=address,billing_address=None,@@ -1085,7 +1086,7 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(checkout_info = CheckoutInfo(checkout=checkout_with_item,delivery_method_info=get_delivery_method_info(- checkout_with_item.shipping_method+ convert_to_shipping_method_data(checkout_with_item.shipping_method)),shipping_address=address,billing_address=None,@@ -1313,7 +1314,7 @@ def test_get_checkout_shipping_tax_rate(checkout_info = CheckoutInfo(checkout=checkout_with_item,delivery_method_info=get_delivery_method_info(- checkout_with_item.shipping_method+ convert_to_shipping_method_data(checkout_with_item.shipping_method)),shipping_address=address,billing_address=None,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 1fd8817c2c..c07b44d4c1 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -32,6 +32,7 @@ if TYPE_CHECKING:from ..order.models import Fulfillment, Order, OrderLinefrom ..page.models import Pagefrom ..product.models import Product, ProductType, ProductVariant+ from ..shipping.interface import ShippingMethodDataPluginConfigurationType = List[dict]NoneType = type(None)@@ -312,6 +313,10 @@ class BasePlugin:get_order_shipping_tax_rate: Callable[["Order", Any], Any]get_payment_config: Callable[[Any], Any]+ get_shipping_methods_for_checkout: Callable[+ ["Checkout", Any], List["ShippingMethodData"]+ ]+get_supported_currencies: Callable[[Any], Any]# Return tax code from object meta.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 50f39a2504..a7cc94faf5 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -47,6 +47,7 @@ if TYPE_CHECKING:TokenConfig,)from ..product.models import Product, ProductType, ProductVariant+ from ..shipping.interface import ShippingMethodDatafrom ..translation.models import Translationfrom ..warehouse.models import Stockfrom .base_plugin import BasePlugin@@ -834,6 +835,44 @@ class PluginsManager(PaymentInterface):)return gateways+ def list_shipping_methods_for_checkout(+ self,+ checkout: "Checkout",+ channel_slug: Optional[str] = None,+ active_only: bool = True,+ ) -> List["ShippingMethodData"]:+ channel_slug = checkout.channel.slug if checkout else channel_slug+ plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)+ shipping_plugins = [+ plugin+ for plugin in plugins+ if hasattr(plugin, "get_shipping_methods_for_checkout")+ ]++ shipping_methods = []+ for plugin in shipping_plugins:+ shipping_methods.extend(+ # https://github.com/python/mypy/issues/9975+ getattr(plugin, "get_shipping_methods_for_checkout")(checkout, None)+ )+ return shipping_methods++ def get_shipping_method(+ self,+ shipping_method_id: str,+ checkout: Optional["Checkout"] = None,+ channel_slug: Optional[str] = None,+ ):+ if checkout:+ methods = {+ method.id: method+ for method in self.list_shipping_methods_for_checkout(+ checkout=checkout, channel_slug=channel_slug+ )+ }+ return methods.get(shipping_method_id)+ return None+def list_external_authentications(self, active_only: bool = True) -> List[dict]:auth_basic_method = "external_obtain_access_tokens"plugins = self.get_plugins(active_only=active_only)diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.pyindex a047b6931f..ce3c5cfc03 100644--- a/saleor/plugins/vatlayer/plugin.py+++ b/saleor/plugins/vatlayer/plugin.py@@ -218,12 +218,14 @@ class VatlayerPlugin(BasePlugin):taxes = Noneif address:taxes = self._get_taxes_for_country(address.country)- if (- not checkout_info.delivery_method_info.delivery_method- or not checkout_info.shipping_method_channel_listings- ):+ if not checkout_info.delivery_method_info.delivery_method:return previous_value- shipping_price = checkout_info.shipping_method_channel_listings.price+ shipping_price = getattr(+ checkout_info.delivery_method_info.delivery_method, "price", None+ )+ if shipping_price is None and checkout_info.shipping_method_channel_listings:+ shipping_price = checkout_info.shipping_method_channel_listings.price+return get_taxed_shipping_price(shipping_price, taxes)def calculate_order_shipping(diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex af61c56c54..0863a277c4 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -28,6 +28,7 @@ from .tasks import trigger_webhook_sync, trigger_webhooks_for_eventfrom .utils import (from_payment_app_id,parse_list_payment_gateways_response,+ parse_list_shipping_methods_response,parse_payment_action_response,)@@ -41,6 +42,7 @@ if TYPE_CHECKING:from ...page.models import Pagefrom ...payment.interface import GatewayResponse, PaymentData, PaymentGatewayfrom ...product.models import Product, ProductVariant+ from ...shipping.interface import ShippingMethodDatafrom ...translation.models import Translationfrom ...warehouse.models import Stock@@ -486,3 +488,24 @@ class WebhookPlugin(BasePlugin):previous_value,**kwargs,)++ def get_shipping_methods_for_checkout(+ self, checkout: "Checkout", previous_value: Any+ ) -> List["ShippingMethodData"]:+ methods = []+ apps = App.objects.for_event_type(+ WebhookEventType.SHIPPING_LIST_METHODS_FOR_CHECKOUT+ ).prefetch_related("webhooks")+ payload = generate_checkout_payload(checkout)+ for app in apps:+ response_data = trigger_webhook_sync(+ event_type=WebhookEventType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ data=payload,+ app=app,+ )+ if response_data:+ shipping_methods = parse_list_shipping_methods_response(+ response_data, app+ )+ methods.extend(shipping_methods)+ return methodsdiff --git a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py b/saleor/plugins/webhook/tests/test_payment_webhook_utils.pyindex 9d5e121bf2..d82ecf28bc 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py@@ -2,7 +2,7 @@ import pytestfrom ....payment import TransactionKindfrom ..utils import (- APP_GATEWAY_ID_PREFIX,+ APP_ID_PREFIX,from_payment_app_id,parse_list_payment_gateways_response,parse_payment_action_response,@@ -13,7 +13,7 @@ from ..utils import (def test_to_payment_app_id(app):gateway_id = "example-gateway"payment_app_id = to_payment_app_id(app, gateway_id)- assert payment_app_id == f"{APP_GATEWAY_ID_PREFIX}:{app.pk}:{gateway_id}"+ assert payment_app_id == f"{APP_ID_PREFIX}:{app.pk}:{gateway_id}"def test_from_payment_app_id():@@ -31,9 +31,9 @@ def test_from_payment_app_id():"1","name","1:1:name",- f"{APP_GATEWAY_ID_PREFIX}:1",- f"{APP_GATEWAY_ID_PREFIX}:1:",- f"{APP_GATEWAY_ID_PREFIX}:1a:name",+ f"{APP_ID_PREFIX}:1",+ f"{APP_ID_PREFIX}:1:",+ f"{APP_ID_PREFIX}:1a:name",],)def test_from_payment_app_id_invalid(app_id):diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pynew file mode 100644index 0000000000..9aa4cba560--- /dev/null+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -0,0 +1,107 @@+from unittest import mock++import graphene+import pytest++from ....webhook.event_types import WebhookEventType+from ...manager import get_plugins_manager+from ..tasks import trigger_webhook_sync+from ..utils import parse_list_shipping_methods_response+++def plugin_manager(settings, channel_USD):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ manager = get_plugins_manager()+ return manager+++def webhook_plugin(plugin_manager):+ def factory():+ return plugin_manager.global_plugins[0]++ return factory++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_trigger_webhook_sync(mock_request, shipping_app):+ data = {"key": "value"}+ trigger_webhook_sync(+ WebhookEventType.SHIPPING_LIST_METHODS_FOR_CHECKOUT, data, shipping_app+ )+ webhook = shipping_app.webhooks.first()+ mock_request.assert_called_once_with(+ webhook.target_url,+ webhook.secret_key,+ WebhookEventType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ data,+ )++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_methods_for_checkout(+ mock_send_request, shipping_app, webhook_plugin, checkout+):+ plugin = webhook_plugin()+ mock_json_response = [+ {+ "id": "shipping_method_id",+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response+ methods = plugin.get_shipping_methods_for_checkout(checkout, None)+ expected_methods = parse_list_shipping_methods_response(+ mock_json_response, shipping_app+ )++ assert len(methods) == 1+ assert methods[0] == expected_methods[0]++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_method(mock_send_request, shipping_app, plugin_manager, checkout):+ response_method_id = "abcd"+ shipping_method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ },+ {+ "id": "cdef",+ "name": "Provider - Priority",+ "amount": "15",+ "currency": "USD",+ "maximum_delivery_days": None,+ },+ ]+ mock_send_request.return_value = mock_json_response+ shipping_method = plugin_manager.get_shipping_method(+ shipping_method_id, checkout, None+ )++ assert shipping_method.id == shipping_method_id++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_method_empty_response(+ mock_send_request, shipping_app, plugin_manager, checkout+):+ shipping_method_id = graphene.Node.to_global_id("app", f"{shipping_app.id}:abcd")+ mock_send_request.return_value = []+ shipping_method = plugin_manager.get_shipping_method(+ shipping_method_id, checkout, None+ )++ assert shipping_method is Nonediff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.pyindex c021574a0a..3f639d1df2 100644--- a/saleor/plugins/webhook/utils.py+++ b/saleor/plugins/webhook/utils.py@@ -1,15 +1,19 @@+import base64import decimalfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, List, Optional+from prices import Money+from ...payment.interface import GatewayResponse, PaymentGateway, PaymentMethodInfo+from ...shipping.interface import ShippingMethodDataif TYPE_CHECKING:from ...app.models import Appfrom ...payment.interface import PaymentData-APP_GATEWAY_ID_PREFIX = "app"+APP_ID_PREFIX = "app"@dataclass@@ -18,17 +22,25 @@ class PaymentAppData:name: str+@dataclass+class ShippingAppData:+ app_pk: int+ shipping_method_id: str++def to_payment_app_id(app: "App", gateway_id: str) -> "str":- return f"{APP_GATEWAY_ID_PREFIX}:{app.pk}:{gateway_id}"+ return f"{APP_ID_PREFIX}:{app.pk}:{gateway_id}"+++def to_shipping_app_id(app: "App", shipping_method_id: str) -> "str":+ return base64.b64encode(+ str.encode(f"{APP_ID_PREFIX}:{app.pk}:{shipping_method_id}")+ ).decode("utf-8")def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:splitted_id = app_gateway_id.split(":")- if (- len(splitted_id) == 3- and splitted_id[0] == APP_GATEWAY_ID_PREFIX- and all(splitted_id)- ):+ if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):try:app_pk = int(splitted_id[1])except (TypeError, ValueError):@@ -104,3 +116,25 @@ def parse_payment_action_response("transaction_already_processed", False),)+++def parse_list_shipping_methods_response(+ response_data: Any, app: "App"+) -> List["ShippingMethodData"]:+ shipping_methods = []+ for shipping_method_data in response_data:+ method_id = shipping_method_data.get("id")+ method_name = shipping_method_data.get("name")+ method_amount = shipping_method_data.get("amount")+ method_currency = shipping_method_data.get("currency")+ method_maximum_delivery_days = shipping_method_data.get("maximum_delivery_days")++ shipping_methods.append(+ ShippingMethodData(+ id=to_shipping_app_id(app, method_id),+ name=method_name,+ price=Money(method_amount, method_currency),+ maximum_delivery_days=method_maximum_delivery_days,+ )+ )+ return shipping_methodsdiff --git a/saleor/shipping/interface.py b/saleor/shipping/interface.pynew file mode 100644index 0000000000..830784c865--- /dev/null+++ b/saleor/shipping/interface.py@@ -0,0 +1,44 @@+from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Dict, Optional++import graphql+from measurement.measures import Weight+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+ name: str+ price: Optional[Money]+ 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)++ @property+ def is_external(self) -> bool:+ try:+ type_, _ = from_global_id_or_error(self.id)+ str_type = str(type_)+ except graphql.error.base.GraphQLError:+ pass+ else:+ return str_type == "app"++ return Falsediff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex 8e7f909872..99f4fca494 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -1,5 +1,12 @@+from typing import TYPE_CHECKING, Optional+from django_countries import countries+from .interface import ShippingMethodData++if TYPE_CHECKING:+ from .models import ShippingMethod+def default_shipping_zone_exists(zone_pk=None):from .models import ShippingZone@@ -15,3 +22,26 @@ def get_countries_without_shipping_zone():for zone in ShippingZone.objects.all():covered_countries.update({c.code for c in zone.countries})return (country[0] for country in countries if country[0] not in covered_countries)+++def convert_to_shipping_method_data(+ shipping_method: Optional["ShippingMethod"],+) -> Optional["ShippingMethodData"]:+ if not shipping_method:+ return None++ 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,+ )diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 4d0a2adcec..4460a7d01c 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -4766,6 +4766,29 @@ def payment_app(db, permission_manage_payments):return app+def shipping_app(db, permission_manage_shipping):+ app = App.objects.create(name="Shipping App", is_active=True)+ app.tokens.create(name="Default")+ app.permissions.add(permission_manage_shipping)++ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-app.com/api/",+ )+ webhook.events.bulk_create(+ [+ WebhookEvent(event_type=event_type, webhook=webhook)+ for event_type in [+ WebhookEventType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ WebhookEventType.FULFILLMENT_CREATED,+ ]+ ]+ )+ return app++@pytest.fixturedef external_app(db):app = App.objects.create(diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex fc48147de2..2805a400df 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -6,6 +6,7 @@ from ..core.permissions import (PagePermissions,PaymentPermissions,ProductPermissions,+ ShippingPermissions,SitePermissions,)@@ -65,6 +66,8 @@ class WebhookEventType:PAYMENT_CONFIRM = "payment_confirm"PAYMENT_PROCESS = "payment_process"+ SHIPPING_LIST_METHODS_FOR_CHECKOUT = "shipping_list_methods_for_checkout"+TRANSLATION_CREATED = "translation_created"TRANSLATION_UPDATED = "translation_updated"@@ -110,6 +113,7 @@ class WebhookEventType:PAYMENT_PROCESS: "Process payment",PAYMENT_REFUND: "Refund payment",PAYMENT_VOID: "Void payment",+ SHIPPING_LIST_METHODS_FOR_CHECKOUT: "Shipping list methods for checkout",TRANSLATION_CREATED: "Create translation",TRANSLATION_UPDATED: "Update translation",}@@ -156,6 +160,10 @@ class WebhookEventType:(PAYMENT_PROCESS, DISPLAY_LABELS[PAYMENT_PROCESS]),(PAYMENT_REFUND, DISPLAY_LABELS[PAYMENT_REFUND]),(PAYMENT_VOID, DISPLAY_LABELS[PAYMENT_VOID]),+ (+ SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ DISPLAY_LABELS[SHIPPING_LIST_METHODS_FOR_CHECKOUT],+ ),(TRANSLATION_CREATED, DISPLAY_LABELS[TRANSLATION_CREATED]),(TRANSLATION_UPDATED, DISPLAY_LABELS[TRANSLATION_UPDATED]),]@@ -211,6 +219,7 @@ class WebhookEventType:PAYMENT_PROCESS: PaymentPermissions.HANDLE_PAYMENTS,PAYMENT_REFUND: PaymentPermissions.HANDLE_PAYMENTS,PAYMENT_VOID: PaymentPermissions.HANDLE_PAYMENTS,+ SHIPPING_LIST_METHODS_FOR_CHECKOUT: ShippingPermissions.MANAGE_SHIPPING,TRANSLATION_CREATED: SitePermissions.MANAGE_TRANSLATIONS,TRANSLATION_UPDATED: SitePermissions.MANAGE_TRANSLATIONS,}diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex b538b20b01..1a982bf1b1 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -312,11 +312,19 @@ def generate_checkout_payload(checkout: "Checkout"):"discount_name","private_metadata","metadata",+ "channel",)user_fields = ("email", "first_name", "last_name")shipping_method_fields = ("name", "type", "currency", "price_amount")lines_dict_data = serialize_checkout_lines(checkout)+ # todo use the most appropriate warehouse+ warehouse = None+ if checkout.shipping_address:+ warehouse = Warehouse.objects.for_country(+ checkout.shipping_address.country.code+ ).first()+checkout_data = serializer.serialize([checkout],fields=checkout_fields,@@ -326,6 +334,10 @@ def generate_checkout_payload(checkout: "Checkout"):"billing_address": (lambda c: c.billing_address, ADDRESS_FIELDS),"shipping_address": (lambda c: c.shipping_address, ADDRESS_FIELDS),"shipping_method": (lambda c: c.shipping_method, shipping_method_fields),+ "warehouse_address": (+ lambda c: warehouse.address if warehouse else None,+ ADDRESS_FIELDS,+ ),},extra_dict_data={# Casting to list to make it json-serializablediff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.pyindex d4129ca5ce..fc012dd7b3 100644--- a/saleor/webhook/serializers.py+++ b/saleor/webhook/serializers.py@@ -32,6 +32,7 @@ def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:"full_name": variant.display_product(),"product_name": product.name,"variant_name": variant.name,+ "attributes": serialize_product_or_variant_attributes(variant),})return data