Skip to content

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

Add availableShippingMethods to the Shop type (#6551)

Iga Karbowiak6e3b6b6cefd0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 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.1
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 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: Geolocalization
authorizationKeys: [AuthorizationKey]!
countries(languageCode: LanguageCodeEnum): [CountryDisplay!]!
diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.py
new file mode 100644
index 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_mapping
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index 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 countries
from ....account.models import Address
from ....core.error_codes import ShopErrorCode
from ....core.permissions import get_permissions_codename
+from ....shipping.models import ShippingMethod
from ....site import AuthenticationBackends
from ....site.models import Site
+from ...account.enums import CountryCodeEnum
from ...core.utils import str_to_enum
from ...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.py
index 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_permissions
from ...core.utils import get_client_ip, get_country_by_ip
from ...plugins.manager import get_plugins_manager
from ...site import models as site_models
-from ..account.types import Address, StaffNotificationRecipient
+from ..account.types import Address, AddressInput, StaffNotificationRecipient
from ..channel import ChannelContext
from ..checkout.types import PaymentGateway
from ..core.connection import CountableDjangoObjectType
@@ -22,12 +22,14 @@ from ..core.utils import str_to_enum
from ..decorators import permission_required
from ..menu.dataloaders import MenuByIdLoader
from ..menu.types import Menu
+from ..shipping.types import ShippingMethod
from ..translations.enums import LanguageCodeEnum
from ..translations.fields import TranslationField
from ..translations.resolvers import resolve_translation
from ..translations.types import ShopTranslation
from ..utils import format_permissions_for_display
from .enums import AuthorizationKeyType
+from .resolvers import resolve_available_shipping_methods
class 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.py
index 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")