Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add availableShippingMethods to the Shop type (#6551)
Iga Karbowiak6e3b6b6cefd0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 43dfff6019..d3280a0b78 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,7 @@ All notable, unreleased changes to this project will be documented in this file.- Fix password reset request - #6351 by @Manfred-Madelaine-pro, Ambroise and Pierre- Refund products support - #6530 by @korycins- Add possibility to exclude products from shipping method - #6506 by @korycins+- Add availableShippingMethods to the Shop type - #6551 by @IKarbowiak# 2.11.1diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 07eb8993f4..8dc7eeaafb 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -4851,6 +4851,7 @@ input ShippingZoneUpdateInput {type Shop {availablePaymentGateways(currency: String): [PaymentGateway!]!+ availableShippingMethods(channel: String!, address: AddressInput): [ShippingMethod]geolocalization: GeolocalizationauthorizationKeys: [AuthorizationKey]!countries(languageCode: LanguageCodeEnum): [CountryDisplay!]!diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.pynew file mode 100644index 0000000000..8030a2b04a--- /dev/null+++ b/saleor/graphql/shop/resolvers.py@@ -0,0 +1,49 @@+from ...account.models import Address+from ...shipping.models import ShippingMethod, ShippingMethodChannelListing+from ..channel import ChannelContext+++def resolve_available_shipping_methods(info, channel_slug: str, address):+ available = ShippingMethod.objects.filter(+ channel_listings__channel__slug=channel_slug+ )+ if address and address.country:+ available = available.filter(+ shipping_zone__countries__contains=address.country,+ )+ # Address instance needed for apply_taxes_to_shipping method+ address = Address(country=address.country)+ 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)+ 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+ ]+++def get_shipping_method_to_shipping_price_mapping(shipping_methods, channel_slug):+ """Prepare mapping shipping method to price from 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++ return shipping_mappingdiff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex 1b4ee32deb..45fcdb3875 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -7,8 +7,10 @@ from django_countries import countriesfrom ....account.models import Addressfrom ....core.error_codes import ShopErrorCodefrom ....core.permissions import get_permissions_codename+from ....shipping.models import ShippingMethodfrom ....site import AuthenticationBackendsfrom ....site.models import Site+from ...account.enums import CountryCodeEnumfrom ...core.utils import str_to_enumfrom ...tests.utils import assert_no_permission, get_graphql_content@@ -666,6 +668,117 @@ def test_query_available_payment_gateways_specified_currency_EUR(assert data[0]["name"] == "SampleDummy"+AVAILABLE_SHIPPING_METHODS_QUERY = """+ query Shop($channel: String!, $address: AddressInput){+ shop {+ availableShippingMethods(channel: $channel, address: $address) {+ id+ name+ }+ }+ }+"""+++def test_query_available_shipping_methods_no_address(+ staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD+):+ # given+ query = AVAILABLE_SHIPPING_METHODS_QUERY++ # when+ response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug})++ # then+ content = get_graphql_content(response)+ data = content["data"]["shop"]["availableShippingMethods"]+ assert {ship_meth["id"] for ship_meth in data} == {+ graphene.Node.to_global_id("ShippingMethod", ship_meth.pk)+ for ship_meth in ShippingMethod.objects.filter(+ channel_listings__channel__slug=channel_USD.slug+ )+ }+++def test_query_available_shipping_methods_for_given_address(+ staff_api_client,+ channel_USD,+ shipping_method,+ shipping_zone_without_countries,+ address,+):+ # given+ query = AVAILABLE_SHIPPING_METHODS_QUERY+ shipping_method_count = ShippingMethod.objects.count()+ variables = {+ "channel": channel_USD.slug,+ "address": {"country": CountryCodeEnum.US.name},+ }++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ 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.pk+ ) not in {ship_meth["id"] for ship_meth in data}+++def test_query_available_shipping_methods_no_address_vatlayer_set(+ staff_api_client,+ shipping_method,+ shipping_method_channel_PLN,+ channel_USD,+ setup_vatlayer,+):+ # given+ query = AVAILABLE_SHIPPING_METHODS_QUERY++ # when+ response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug})++ # then+ content = get_graphql_content(response)+ data = content["data"]["shop"]["availableShippingMethods"]+ assert {ship_meth["id"] for ship_meth in data} == {+ graphene.Node.to_global_id("ShippingMethod", ship_meth.pk)+ for ship_meth in ShippingMethod.objects.filter(+ channel_listings__channel__slug=channel_USD.slug+ )+ }+++def test_query_available_shipping_methods_for_given_address_vatlayer_set(+ staff_api_client,+ channel_USD,+ shipping_method,+ shipping_zone_without_countries,+ address,+ setup_vatlayer,+):+ # given+ query = AVAILABLE_SHIPPING_METHODS_QUERY+ shipping_method_count = ShippingMethod.objects.count()+ variables = {+ "channel": channel_USD.slug,+ "address": {"country": CountryCodeEnum.US.name},+ }++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ 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.pk+ ) not in {ship_meth["id"] for ship_meth in data}++AUTHORIZATION_KEY_ADD = """mutation AddKey($key: String!, $password: String!, $keyType: AuthorizationKeyType!) {authorizationKeyAdd(input: {key: $key, password: $password}, keyType: $keyType) {diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 53c4693e3b..28c197cb25 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -12,7 +12,7 @@ from ...core.permissions import SitePermissions, get_permissionsfrom ...core.utils import get_client_ip, get_country_by_ipfrom ...plugins.manager import get_plugins_managerfrom ...site import models as site_models-from ..account.types import Address, StaffNotificationRecipient+from ..account.types import Address, AddressInput, StaffNotificationRecipientfrom ..channel import ChannelContextfrom ..checkout.types import PaymentGatewayfrom ..core.connection import CountableDjangoObjectType@@ -22,12 +22,14 @@ from ..core.utils import str_to_enumfrom ..decorators import permission_requiredfrom ..menu.dataloaders import MenuByIdLoaderfrom ..menu.types import Menu+from ..shipping.types import ShippingMethodfrom ..translations.enums import LanguageCodeEnumfrom ..translations.fields import TranslationFieldfrom ..translations.resolvers import resolve_translationfrom ..translations.types import ShopTranslationfrom ..utils import format_permissions_for_displayfrom .enums import AuthorizationKeyType+from .resolvers import resolve_available_shipping_methodsclass Navigation(graphene.ObjectType):@@ -83,6 +85,23 @@ class Shop(graphene.ObjectType):description="List of available payment gateways.",required=True,)+ available_shipping_methods = graphene.List(+ ShippingMethod,+ channel=graphene.Argument(+ graphene.String,+ description="Slug of a channel for which the data should be returned.",+ required=True,+ ),+ address=graphene.Argument(+ AddressInput,+ description=(+ "Address for which available shipping methods should be returned."+ ),+ required=False,+ ),+ required=False,+ description="Shipping methods that are available for the shop.",+ )geolocalization = graphene.Field(Geolocalization, description="Customer's geolocalization data.")@@ -178,6 +197,10 @@ class Shop(graphene.ObjectType):def resolve_available_payment_gateways(_, _info, currency: Optional[str] = None):return get_plugins_manager().list_payment_gateways(currency=currency)+ @staticmethod+ def resolve_available_shipping_methods(_, info, channel, address=None):+ return resolve_available_shipping_methods(info, channel, address)+@staticmethod@permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_authorization_keys(_, _info):diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex 6273a6ac40..9b29411cc8 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -89,7 +89,8 @@ class ShippingMethodQueryset(models.QuerySet):def weight_based(self):return self.filter(type=ShippingMethodType.WEIGHT_BASED)- def applicable_shipping_methods_by_channel(self, shipping_methods, channel_id):+ @staticmethod+ def applicable_shipping_methods_by_channel(shipping_methods, channel_id):query = ShippingMethodChannelListing.objects.filter(shipping_method=OuterRef("pk"), channel_id=channel_id).values_list("price_amount")