Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add in_shipping_zones filter to shop countries query (#8897) (#8994)
Jakub7309f80b39cf
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex b37333da80..561442b7e6 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1734,6 +1734,10 @@ type CountryDisplay {vat: VAT}+input CountryFilterInput {+ attachedToShippingZones: Boolean+}+type CreateToken {token: StringrefreshToken: String@@ -6520,7 +6524,7 @@ type Shop {availableExternalAuthentications: [ExternalAuthentication!]!availableShippingMethods(channel: String!, address: AddressInput): [ShippingMethod]channelCurrencies: [String!]!- countries(languageCode: LanguageCodeEnum): [CountryDisplay!]!+ countries(languageCode: LanguageCodeEnum, filter: CountryFilterInput): [CountryDisplay!]!defaultCountry: CountryDisplaydefaultMailSenderName: StringdefaultMailSenderAddress: Stringdiff --git a/saleor/graphql/shop/filters.py b/saleor/graphql/shop/filters.pynew file mode 100644index 0000000000..65a2fd79dd--- /dev/null+++ b/saleor/graphql/shop/filters.py@@ -0,0 +1,10 @@+import graphene+++class CountryFilterInput(graphene.InputObjectType):+ attached_to_shipping_zones = graphene.Boolean(+ description="Boolean for filtering countries by having shipping zone assigned."+ "If 'true', return countries with shipping zone assigned."+ "If 'false', return countries without any shipping zone assigned."+ "If the argument is not provided (null), return all countries."+ )diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.pyindex addb761ce7..fe6804c72b 100644--- a/saleor/graphql/shop/resolvers.py+++ b/saleor/graphql/shop/resolvers.py@@ -1,8 +1,14 @@+from django.utils import translation+from django_countries import countries+from django_prices_vatlayer.models import VAT+from ...account.models import Addressfrom ...core.tracing import traced_resolverfrom ...shipping.models import ShippingMethod, ShippingMethodChannelListingfrom ...shipping.postal_codes import filter_shipping_methods_by_postal_code_rulesfrom ...shipping.utils import convert_to_shipping_method_data+from ..core.types import CountryDisplay+from .utils import get_countries_codes_list@traced_resolver@@ -27,6 +33,22 @@ def resolve_available_shipping_methods(info, channel_slug: str, address):return instances+def resolve_countries(**kwargs):+ countries_filter = kwargs.get("filter", {})+ attached_to_shipping_zones = countries_filter.get("attached_to_shipping_zones")+ language_code = kwargs.get("language_code")+ taxes = {vat.country_code: vat for vat in VAT.objects.all()}+ # DEPRECATED: translation.override will be dropped in Saleor 4.0+ with translation.override(language_code):+ return [+ CountryDisplay(+ code=country[0], country=country[1], vat=taxes.get(country[0])+ )+ for country in countries+ if country[0] in get_countries_codes_list(attached_to_shipping_zones)+ ]++def get_shipping_method_to_listing_mapping(shipping_methods, channel_slug):"""Prepare mapping shipping method to its channel listings."""shipping_mapping = {}diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex 4fd0a1c1bf..f6cad1f5c7 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -1670,3 +1670,71 @@ def test_fetch_channel_currencies_by_customer(api_client, channel_PLN, channel_Uquery = CHANNEL_CURRENCIES_QUERYresponse = api_client.post_graphql(query)assert_no_permission(response)+++COUNTRY_FILTER_QUERY = """+ query($filter: CountryFilterInput!) {+ shop {+ countries(filter: $filter){+ code+ }+ }+ }++"""+++def test_query_countries_filter_shiping_zones_attached_true(+ user_api_client, shipping_zones+):+ # given+ variables = {"filter": {"attachedToShippingZones": True}}+ fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}++ # when+ response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)+ content = get_graphql_content(response)++ data = content["data"]["shop"]["countries"]+ countries_codes_results = {country["code"] for country in data}++ # then+ assert countries_codes_results == fixture_countries_code_set+ assert len(data) == len(shipping_zones)+++def test_query_countries_filter_shiping_zones_attached_false(+ user_api_client, shipping_zones+):+ # given+ variables = {"filter": {"attachedToShippingZones": False}}+ fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}++ # when+ response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)+ content = get_graphql_content(response)++ data = content["data"]["shop"]["countries"]+ countries_codes_results = {country["code"] for country in data}++ # then+ assert not any(+ code in countries_codes_results for code in fixture_countries_code_set+ )+ assert len(data) == (len(countries) - len(shipping_zones))+++def test_query_countries_filter_shiping_zones_attached_none(+ user_api_client, shipping_zones+):+ # given+ variables = {"filter": {"attachedToShippingZones": None}}++ # when+ response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)+ content = get_graphql_content(response)++ data = content["data"]["shop"]["countries"]++ # then+ assert len(data) == len(countries)diff --git a/saleor/graphql/shop/tests/test_shop_utils.py b/saleor/graphql/shop/tests/test_shop_utils.pynew file mode 100644index 0000000000..4070107cdf--- /dev/null+++ b/saleor/graphql/shop/tests/test_shop_utils.py@@ -0,0 +1,38 @@+from django_countries import countries++from ..utils import get_countries_codes_list+++def test_get_countries_codes_list(shipping_zones):+ # given+ all_countries = {country[0] for country in countries}++ # when+ countries_list_all = get_countries_codes_list()++ # then+ assert countries_list_all == all_countries+++def test_get_countries_codes_list_true(shipping_zones):+ # given+ fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}++ # when+ countries_list_true = get_countries_codes_list(attached_to_shipping_zones=True)++ # then+ assert countries_list_true == fixture_countries_code_set+++def test_get_countries_codes_list_false(shipping_zones):+ # given+ fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}++ # when+ countries_list_false = get_countries_codes_list(False)++ # then+ assert not any(+ country in countries_list_false for country in fixture_countries_code_set+ )diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 942e7c9013..94ec1b1a93 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -2,7 +2,6 @@ from typing import Optionalimport graphenefrom django.conf import settings-from django.utils import translationfrom django_countries import countriesfrom django_prices_vatlayer.models import VATfrom phonenumbers import COUNTRY_CODE_TO_REGION_CODE@@ -31,7 +30,8 @@ from ..translations.resolvers import resolve_translationfrom ..translations.types import ShopTranslationfrom ..utils import format_permissions_for_displayfrom .enums import GiftCardSettingsExpiryTypeEnum-from .resolvers import resolve_available_shipping_methods+from .filters import CountryFilterInput+from .resolvers import resolve_available_shipping_methods, resolve_countriesclass Domain(graphene.ObjectType):@@ -164,6 +164,10 @@ class Shop(graphene.ObjectType):f"{DEPRECATED_IN_3X_INPUT}"),),+ filter=CountryFilterInput(+ description="Filtering options for countries",+ required=False,+ ),description="List of countries available in the shop.",required=True,)@@ -293,17 +297,8 @@ class Shop(graphene.ObjectType):)@staticmethod- def resolve_countries(_, _info, language_code=None):- taxes = {vat.country_code: vat for vat in VAT.objects.all()}-- # DEPRECATED: translation.override will be dropped in Saleor 4.0- with translation.override(language_code):- return [- CountryDisplay(- code=country[0], country=country[1], vat=taxes.get(country[0])- )- for country in countries- ]+ def resolve_countries(_, _info, **kwargs):+ return resolve_countries(**kwargs)@staticmethoddef resolve_domain(_, info):diff --git a/saleor/graphql/shop/utils.py b/saleor/graphql/shop/utils.pynew file mode 100644index 0000000000..6af450912b--- /dev/null+++ b/saleor/graphql/shop/utils.py@@ -0,0 +1,28 @@+from typing import Optional++from django_countries import countries++from ...shipping.models import ShippingZone+++def get_countries_codes_list(attached_to_shipping_zones: Optional[bool] = None):+ """Return set of countries codes.++ If 'True', return countries with shipping zone assigned.+ If 'False', return countries without any shipping zone assigned."+ If the argument is not provided (None), return all countries.+ """++ all_countries_codes = {country[0] for country in countries}+ if attached_to_shipping_zones is not None:+ covered_countries_codes = set()+ for zone in ShippingZone.objects.iterator():+ covered_countries_codes.update({country.code for country in zone.countries})++ if attached_to_shipping_zones:+ return covered_countries_codes++ if not attached_to_shipping_zones:+ return all_countries_codes - covered_countries_codes++ return all_countries_codes