Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop fallback for company address (#7736)
Marcin Gębalab60266933f7a
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 611c8a8899..9870dc2658 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -37,6 +37,7 @@ from ...product import models as product_modelsfrom ...product.models import ProductChannelListingfrom ...shipping import models as shipping_modelsfrom ...warehouse.availability import check_stock_quantity_bulk+from ...warehouse.models import Warehousefrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..channel.utils import clean_channel@@ -51,7 +52,6 @@ from ..core.validators import (from ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod-from ..utils import get_user_country_contextfrom .types import Checkout, CheckoutLinefrom .utils import prepare_insufficient_stock_checkout_validation_error@@ -325,10 +325,16 @@ class CheckoutCreate(ModelMutation, I18nMixin):shipping_address = cls.retrieve_shipping_address(user, data)billing_address = cls.retrieve_billing_address(user, data)- country = get_user_country_context(- destination_address=shipping_address,- company_address=info.context.site.settings.company_address,- )++ if shipping_address:+ country = shipping_address.country.code+ else:+ warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel.pk)+ if warehouse:+ country = warehouse.address.country.code+ else:+ # fallback when channel has no warehouses+ country = settings.DEFAULT_COUNTRY# Resolve and process the lines, retrieving the variants and quantitieslines = data.pop("lines", None)@@ -790,10 +796,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):manager = info.context.pluginscheckout_info = fetch_checkout_info(checkout, lines, discounts, manager)- country = get_user_country_context(- destination_address=shipping_address,- company_address=info.context.site.settings.company_address,- )+ country = shipping_address.country.codecheckout.set_country(country, commit=True)# Resolve and process the lines, validating variants quantitiesdiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 264e7e35fc..68e5e5bc45 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -31,7 +31,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 ....warehouse.models import Stock+from ....warehouse.models import Stock, Warehousefrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (clean_shipping_method,@@ -1020,6 +1020,28 @@ def test_checkout_create_sets_country_from_shipping_address_country(assert checkout.country == "US"+def test_checkout_create_sets_country_when_no_shipping_address_is_given(+ api_client, variant_with_many_stocks_different_shipping_zones, channel_USD+):+ variant = variant_with_many_stocks_different_shipping_zones+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id}],+ "email": test_email,+ }+ }+ assert not Checkout.objects.exists()++ # should set address of a first warehouse in the channel+ api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ checkout = Checkout.objects.first()+ first_warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel_USD.pk)+ assert checkout.country == first_warehouse.address.country++@override_settings(DEFAULT_COUNTRY="DE")def test_checkout_create_check_lines_quantity_for_zone_insufficient_stocks(user_api_client,diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 7613c8628a..0f3750e447 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -2,6 +2,7 @@ import jsonimport osfrom datetime import datetime, timedeltafrom decimal import Decimal+from unittest import mockfrom unittest.mock import ANY, Mock, patchimport graphene@@ -163,6 +164,7 @@ QUERY_PRODUCT = """}availableForPurchaseisAvailableForPurchase+ isAvailable}}"""@@ -1010,6 +1012,7 @@ def test_product_query_is_available_for_purchase_false("%Y-%m-%d")assert product_data["isAvailableForPurchase"] is False+ assert product_data["isAvailable"] is Falsedef test_product_query_is_available_for_purchase_false_no_available_for_purchase_date(@@ -1032,6 +1035,7 @@ def test_product_query_is_available_for_purchase_false_no_available_for_purchaseassert not product_data["availableForPurchase"]assert product_data["isAvailableForPurchase"] is False+ assert product_data["isAvailable"] is Falsedef test_product_query_unpublished_products_by_slug(@@ -1675,6 +1679,87 @@ def test_query_products_no_channel_shipping_zones(assert product_data["isAvailable"] is False+QUERY_PRODUCT_IS_AVAILABLE = """+ query Product($id: ID, $channel: String, $address: AddressInput) {+ product(id: $id, channel: $channel) {+ isAvailableNoAddress: isAvailable+ isAvailableAddress: isAvailable(address: $address)+ }+ }+"""+++def test_query_product_is_available(+ api_client, channel_USD, variant_with_many_stocks_different_shipping_zones+):+ # given+ variant = variant_with_many_stocks_different_shipping_zones+ product = variant.product+ variables = {+ "id": graphene.Node.to_global_id("Product", product.id),+ "channel": channel_USD.slug,+ "address": {"country": "PL"},+ }++ # when+ response = api_client.post_graphql(QUERY_PRODUCT_IS_AVAILABLE, variables)+ content = get_graphql_content(response)++ # then+ product_data = content["data"]["product"]+ assert product_data["isAvailableNoAddress"] is True+ assert product_data["isAvailableAddress"] is True+++def test_query_product_is_available_with_one_variant(+ api_client, channel_USD, product_with_two_variants+):+ # given+ product = product_with_two_variants++ # remove stock for 2nd variant+ variant_2 = product.variants.all()[1]+ Stock.objects.filter(product_variant=variant_2).delete()++ variables = {+ "id": graphene.Node.to_global_id("Product", product.id),+ "channel": channel_USD.slug,+ "address": {"country": "PL"},+ }++ # when+ response = api_client.post_graphql(QUERY_PRODUCT_IS_AVAILABLE, variables)+ content = get_graphql_content(response)++ # then+ product_data = content["data"]["product"]+ assert product_data["isAvailableNoAddress"] is True+ assert product_data["isAvailableAddress"] is True+++def test_query_product_is_available_no_shipping_zones(+ api_client, channel_USD, variant_with_many_stocks_different_shipping_zones+):+ # given+ channel_USD.shipping_zones.clear()+ variant = variant_with_many_stocks_different_shipping_zones+ product = variant.product+ variables = {+ "id": graphene.Node.to_global_id("Product", product.id),+ "channel": channel_USD.slug,+ "address": {"country": "PL"},+ }++ # when+ response = api_client.post_graphql(QUERY_PRODUCT_IS_AVAILABLE, variables)+ content = get_graphql_content(response)++ # then+ product_data = content["data"]["product"]+ assert product_data["isAvailableNoAddress"] is False+ assert product_data["isAvailableAddress"] is False++def test_products_query_with_filter_attributes(query_products_with_filter,staff_api_client,@@ -8885,11 +8970,38 @@ def test_product_variants_no_ids_list(user_api_client, variant, channel_USD):assert len(data["edges"]) == ProductVariant.objects.count()+QUERY_GET_PRODUCT_VARIANTS_PRICING = """+ query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {+ product(id: $id, channel: $channel) {+ variants {+ id+ pricingNoAddress: pricing {+ priceUndiscounted {+ gross {+ amount+ }+ }+ }+ pricing(address: $address) {+ priceUndiscounted {+ gross {+ amount+ }+ }+ }+ }+ }+ }+"""++[email protected]("saleor.graphql.product.types.products.WarehouseCountryCodeByChannelLoader")@pytest.mark.parametrize("variant_price_amount, api_variant_price",[(200, 200), (0, 0)],)def test_product_variant_price(+ warehouse_country_code_loader,variant_price_amount,api_variant_price,user_api_client,@@ -8902,32 +9014,20 @@ def test_product_variant_price(channel=channel_USD, variant__product_id=product.pk).update(price_amount=variant_price_amount)- query = """- query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {- product(id: $id, channel: $channel) {- variants {- pricing(address: $address) {- priceUndiscounted {- gross {- amount- }- }- }- }- }- }- """product_id = graphene.Node.to_global_id("Product", variant.product.id)variables = {"id": product_id,"channel": channel_USD.slug,"address": {"country": "US"},}- response = user_api_client.post_graphql(query, variables)+ response = user_api_client.post_graphql(+ QUERY_GET_PRODUCT_VARIANTS_PRICING, variables+ )content = get_graphql_content(response)data = content["data"]["product"]variant_price = data["variants"][0]["pricing"]["priceUndiscounted"]["gross"]assert variant_price["amount"] == api_variant_price+ assert warehouse_country_code_loader.calleddef test_product_variant_without_price_as_user(@@ -8937,23 +9037,6 @@ def test_product_variant_without_price_as_user(channel_USD,):variant.channel_listings.filter(channel=channel_USD).update(price_amount=None)-- query = """- query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {- product(id: $id, channel: $channel) {- variants {- id- pricing(address: $address) {- priceUndiscounted {- gross {- amount- }- }- }- }- }- }- """product_id = graphene.Node.to_global_id("Product", variant.product.id)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)variables = {@@ -8962,7 +9045,9 @@ def test_product_variant_without_price_as_user("address": {"country": "US"},}- response = user_api_client.post_graphql(query, variables)+ response = user_api_client.post_graphql(+ QUERY_GET_PRODUCT_VARIANTS_PRICING, variables+ )content = get_graphql_content(response)variants_data = content["data"]["product"]["variants"]@@ -8981,22 +9066,6 @@ def test_product_variant_without_price_as_staff(variant_channel_listing.price_amount = Nonevariant_channel_listing.save()- query = """- query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {- product(id: $id, channel: $channel) {- variants {- id- pricing(address: $address) {- priceUndiscounted {- gross {- amount- }- }- }- }- }- }- """product_id = graphene.Node.to_global_id("Product", variant.product.id)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)variables = {@@ -9004,7 +9073,9 @@ def test_product_variant_without_price_as_staff("channel": channel_USD.slug,"address": {"country": "US"},}- response = staff_api_client.post_graphql(query, variables)+ response = staff_api_client.post_graphql(+ QUERY_GET_PRODUCT_VARIANTS_PRICING, variables+ )content = get_graphql_content(response)variants_data = content["data"]["product"]["variants"]diff --git a/saleor/graphql/product/tests/test_product_channel_listings_queries.py b/saleor/graphql/product/tests/test_product_channel_listings_queries.pyindex ad5b65a583..27c3717b1e 100644--- a/saleor/graphql/product/tests/test_product_channel_listings_queries.py+++ b/saleor/graphql/product/tests/test_product_channel_listings_queries.py@@ -1,46 +1,49 @@+from unittest import mock+import graphene+from ....warehouse.models import Warehousefrom ...tests.utils import get_graphql_contentQUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING = """+fragment Pricing on ProductPricingInfo {+ priceRangeUndiscounted {+ start {+ net {+ amount+ currency+ }+ gross {+ amount+ currency+ }+ }+ stop {+ gross {+ amount+ currency+ }+ }+ }+}query FetchProduct($id: ID, $channel: String, $address: AddressInput) {product(id: $id, channel: $channel) {idpricing(address: $address) {- priceRangeUndiscounted {- start {- gross {- amount- currency- }- }- stop {- gross {- amount- currency- }- }- }+ ...Pricing+ }+ pricingNoAddress: pricing {+ ...Pricing}channelListings {channel {slug}pricing(address: $address) {- priceRangeUndiscounted {- start {- gross {- amount- currency- }- }- stop {- gross {- amount- currency- }- }- }+ ...Pricing+ }+ pricingNoAddress: pricing {+ ...Pricing}}}@@ -48,14 +51,27 @@ query FetchProduct($id: ID, $channel: String, $address: AddressInput) {"""[email protected]("saleor.graphql.product.types.channels.WarehouseCountryCodeByChannelLoader")def test_product_channel_listing_pricing_field(- staff_api_client, permission_manage_products, channel_USD, product+ warehouse_country_code_loader,+ address_usa,+ staff_api_client,+ permission_manage_products,+ channel_USD,+ product,):# given++ # Changing the address of a warehouse used by the product to address_usa, so that+ # we can query pricing in two countries: US and PL.+ warehouse = Warehouse.objects.first()+ warehouse.address = address_usa+ warehouse.save()+variables = {"id": graphene.Node.to_global_id("Product", product.pk),"channel": channel_USD.slug,- "address": {"country": "US"},+ "address": {"country": "PL"},}product.channel_listings.exclude(channel__slug=channel_USD.slug).delete()@@ -72,3 +88,4 @@ def test_product_channel_listing_pricing_field(product_data = content["data"]["product"]product_channel_listing_data = product_data["channelListings"][0]assert product_data["pricing"] == product_channel_listing_data["pricing"]+ assert warehouse_country_code_loader.calleddiff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 965eb5b914..08300014b6 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -267,28 +267,45 @@ def test_get_product_variant_channel_listing_as_anonymous(QUERY_PRODUCT_VARIANT_STOCKS = """- query ProductVariantDetails($id: ID!, $channel: String) {- productVariant(id: $id, channel: $channel) {- id- stocks{- id- quantity- warehouse{- slug- }- }- }+ fragment Stock on Stock {+ id+ quantity+ warehouse {+ slug+ }+ }+ query ProductVariantDetails(+ $id: ID!+ $channel: String+ $address: AddressInput+ ) {+ productVariant(id: $id, channel: $channel) {+ id+ stocksNoAddress: stocks {+ ...Stock+ }+ stocksWithAddress: stocks(address: $address) {+ ...Stock+ }}+ }"""def test_get_product_variant_stocks(- staff_api_client, variant_with_many_stocks, channel_USD, permission_manage_products+ staff_api_client,+ variant_with_many_stocks_different_shipping_zones,+ channel_USD,+ permission_manage_products,):# given- variant = variant_with_many_stocks+ variant = variant_with_many_stocks_different_shipping_zonesvariant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- variables = {"id": variant_id, "channel": channel_USD.slug}+ variables = {+ "id": variant_id,+ "channel": channel_USD.slug,+ "address": {"country": "PL"},+ }# whenresponse = staff_api_client.post_graphql(@@ -299,19 +316,50 @@ def test_get_product_variant_stocks(content = get_graphql_content(response)# then- stocks_count = variant.stocks.count()+ all_stocks = variant.stocks.all()+ pl_stocks = variant.stocks.filter(+ warehouse__shipping_zones__countries__contains="PL"+ )data = content["data"]["productVariant"]- assert len(data["stocks"]) == stocks_count++ # When no address is provided, it should return all stocks of the variant available+ # in given channel.+ assert len(data["stocksNoAddress"]) == all_stocks.count()+ no_address_stocks_ids = [stock["id"] for stock in data["stocksNoAddress"]]+ assert all(+ [+ graphene.Node.to_global_id("Stock", stock.pk) in no_address_stocks_ids+ for stock in all_stocks+ ]+ )++ # When address is given, return only stocks from warehouse that ship to that+ # address.+ assert len(data["stocksWithAddress"]) == pl_stocks.count()+ with_address_stocks_ids = [stock["id"] for stock in data["stocksWithAddress"]]+ assert all(+ [+ graphene.Node.to_global_id("Stock", stock.pk) in with_address_stocks_ids+ for stock in pl_stocks+ ]+ )def test_get_product_variant_stocks_no_channel_shipping_zones(- staff_api_client, variant_with_many_stocks, channel_USD, permission_manage_products+ staff_api_client,+ variant_with_many_stocks_different_shipping_zones,+ channel_USD,+ permission_manage_products,):# givenchannel_USD.shipping_zones.clear()- variant = variant_with_many_stocks+ variant = variant_with_many_stocks_different_shipping_zonesvariant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- variables = {"id": variant_id, "channel": channel_USD.slug}+ variables = {+ "id": variant_id,+ "channel": channel_USD.slug,+ "address": {"country": "PL"},+ }# whenresponse = staff_api_client.post_graphql(@@ -324,7 +372,8 @@ def test_get_product_variant_stocks_no_channel_shipping_zones(# thenstocks_count = variant.stocks.count()data = content["data"]["productVariant"]- assert data["stocks"] == []+ assert data["stocksNoAddress"] == []+ assert data["stocksWithAddress"] == []assert stocks_count > 0diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.pyindex 6d740aa966..0c44c5e5b6 100644--- a/saleor/graphql/product/tests/test_variant_pricing.py+++ b/saleor/graphql/product/tests/test_variant_pricing.py@@ -1,3 +1,4 @@+from unittest import mockfrom unittest.mock import Mockfrom django_countries.fields import Country@@ -9,31 +10,37 @@ from ....product.utils.availability import get_variant_availabilityfrom ...tests.utils import get_graphql_contentQUERY_GET_VARIANT_PRICING = """+fragment VariantPricingInfo on VariantPricingInfo {+ onSale+ discount {+ currency+ net {+ amount+ }+ }+ priceUndiscounted {+ currency+ net {+ amount+ }+ }+ price {+ currency+ net {+ amount+ }+ }+}query ($channel: String, $address: AddressInput) {products(first: 1, channel: $channel) {edges {node {variants {pricing(address: $address) {- onSale- discount {- currency- net {- amount- }- }- priceUndiscounted {- currency- net {- amount- }- }- price {- currency- net {- amount- }- }+ ...VariantPricingInfo+ }+ pricingNoAddress: pricing {+ ...VariantPricingInfo}}}@@ -73,7 +80,10 @@ def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):assert pricing["price"]["net"]["amount"] == discounted_price-def test_get_variant_pricing_not_on_sale(api_client, product, channel_USD):[email protected]("saleor.graphql.product.types.products.WarehouseCountryCodeByChannelLoader")+def test_get_variant_pricing_not_on_sale(+ warehouse_country_code_loader, api_client, product, channel_USD+):price = product.variants.first().channel_listings.get().pricevariables = {"channel": channel_USD.slug, "address": {"country": "US"}}@@ -99,6 +109,9 @@ def test_get_variant_pricing_not_on_sale(api_client, product, channel_USD):assert pricing["price"]["currency"] == price.currencyassert pricing["price"]["net"]["amount"] == price.amount+ # check that country_code loader was called for pricing without address+ assert warehouse_country_code_loader.called+def test_variant_pricing(variant: ProductVariant, monkeypatch, settings, stock, channel_USD@@ -122,6 +135,7 @@ def test_variant_pricing(discounts=[],channel=channel_USD,plugins=manager,+ country=Country("US"),)assert pricing.price == taxed_priceassert pricing.price_local_currency is None@@ -131,7 +145,6 @@ def test_variant_pricing(lambda c: {"PLN": Mock(rate=2)},)- settings.DEFAULT_COUNTRY = "PL"settings.OPENEXCHANGERATES_API_KEY = "fake-key"pricing = get_variant_availability(@@ -157,6 +170,7 @@ def test_variant_pricing(discounts=[],channel=channel_USD,plugins=manager,+ country=Country("PL"),)assert pricing.price.tax.amountassert pricing.price_undiscounted.tax.amountdiff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex 34335b7d79..ddf4169ded 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -18,7 +18,7 @@ from ...channel.dataloaders import ChannelByIdLoaderfrom ...core.connection import CountableDjangoObjectTypefrom ...decorators import permission_requiredfrom ...discount.dataloaders import DiscountsByDateTimeLoader-from ...utils import get_user_country_context+from ...warehouse.dataloaders import WarehouseCountryCodeByChannelLoaderfrom ..dataloaders import (CollectionsByProductIdLoader,ProductByIdLoader,@@ -160,9 +160,8 @@ class ProductChannelListing(CountableDjangoObjectType):@traced_resolverdef resolve_pricing(root: models.ProductChannelListing, info, address=None):context = info.context- country_code = get_user_country_context(- address, info.context.site.settings.company_address- )++ country_code = address.country if address is not None else Nonedef calculate_pricing_info(discounts):def calculate_pricing_with_channel(channel):@@ -172,25 +171,41 @@ class ProductChannelListing(CountableDjangoObjectType):variants_channel_listing,):def calculate_pricing_with_collections(collections):- if not variants_channel_listing:- return None- availability = get_product_availability(- product=product,- product_channel_listing=root,- variants=variants,- variants_channel_listing=variants_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,- manager=context.plugins,- country=Country(country_code),- local_currency=get_currency_for_country(- country_code- ),- )- from .products import ProductPricingInfo-- return ProductPricingInfo(**asdict(availability))+ def calculate_pricing_with_country_code(country_code):+ if not variants_channel_listing:+ return None++ vc_listing = variants_channel_listing+ local_currency = None+ if country_code:+ local_currency = get_currency_for_country(+ country_code+ )++ availability = get_product_availability(+ product=product,+ product_channel_listing=root,+ variants=variants,+ variants_channel_listing=vc_listing,+ collections=collections,+ discounts=discounts,+ channel=channel,+ manager=context.plugins,+ country=Country(country_code),+ local_currency=local_currency,+ )+ from .products import ProductPricingInfo++ return ProductPricingInfo(**asdict(availability))++ if not country_code:+ return (+ WarehouseCountryCodeByChannelLoader(context)+ .load(channel.slug)+ .then(calculate_pricing_with_country_code)+ )++ return calculate_pricing_with_country_code(country_code)return (CollectionsByProductIdLoader(context)diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex e1f6111391..336bc37e0f 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -21,7 +21,6 @@ from ....product.utils.availability import (get_variant_availability,)from ....product.utils.variants import get_variant_selection_attributes-from ....warehouse.availability import is_product_in_stockfrom ...account import types as account_typesfrom ...account.enums import CountryCodeEnumfrom ...attribute.filters import AttributeFilterInput@@ -62,11 +61,12 @@ from ...translations.types import (ProductTranslation,ProductVariantTranslation,)-from ...utils import get_user_country_context, get_user_or_app_from_context+from ...utils import get_user_or_app_from_contextfrom ...utils.filters import reporting_period_to_datefrom ...warehouse.dataloaders import (AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader,- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader,+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,+ WarehouseCountryCodeByChannelLoader,)from ...warehouse.types import Stockfrom ..dataloaders import (@@ -268,11 +268,8 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):country_code=None,):if address is not None:- country_code = get_user_country_context(- address, info.context.site.settings.company_address- )-- return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader(+ country_code = address.country+ return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(info.context).load((root.node.id, country_code, root.channel_slug))@@ -284,9 +281,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):country_code=None,):if address is not None:- country_code = get_user_country_context(- address, info.context.site.settings.company_address- )+ country_code = address.countryif not root.node.track_inventory:return settings.MAX_CHECKOUT_LINE_QUANTITY@@ -348,10 +343,6 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):if not root.channel_slug:return None- country_code = get_user_country_context(- address, info.context.site.settings.company_address- )-channel_slug = str(root.channel_slug)context = info.context@@ -365,56 +356,74 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):collections = CollectionsByProductIdLoader(context).load(root.node.product_id)channel = ChannelBySlugLoader(context).load(channel_slug)- def calculate_pricing_info(discounts):- def calculate_pricing_with_channel(channel):- def calculate_pricing_with_product_variant_channel_listings(- variant_channel_listing,- ):- def calculate_pricing_with_product(product):- def calculate_pricing_with_product_channel_listings(- product_channel_listing,- ):- def calculate_pricing_with_collections(collections):- if (- not variant_channel_listing- or not product_channel_listing- ):- return None- availability = get_variant_availability(- variant=root.node,- variant_channel_listing=variant_channel_listing,- product=product,- product_channel_listing=product_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,- country=Country(country_code),- local_currency=get_currency_for_country(- country_code- ),- plugins=context.plugins,+ country_code = address.country if address is not None else None++ def calculate_discounts(country_code):+ def calculate_pricing_info(discounts):+ def calculate_pricing_with_channel(channel):+ def calculate_pricing_with_product_variant_channel_listings(+ variant_channel_listing,+ ):+ def calculate_pricing_with_product(product):+ def calculate_pricing_with_product_channel_listings(+ product_channel_listing,+ ):+ def calculate_pricing_with_collections(collections):+ if (+ not variant_channel_listing+ or not product_channel_listing+ ):+ return None++ local_currency = None+ if country_code:+ local_currency = get_currency_for_country(+ country_code+ )++ availability = get_variant_availability(+ variant=root.node,+ variant_channel_listing=variant_channel_listing,+ product=product,+ product_channel_listing=product_channel_listing,+ collections=collections,+ discounts=discounts,+ channel=channel,+ country=Country(country_code),+ local_currency=local_currency,+ plugins=context.plugins,+ )+ return VariantPricingInfo(**asdict(availability))++ return collections.then(+ calculate_pricing_with_collections)- return VariantPricingInfo(**asdict(availability))- return collections.then(calculate_pricing_with_collections)+ return product_channel_listing.then(+ calculate_pricing_with_product_channel_listings+ )- return product_channel_listing.then(- calculate_pricing_with_product_channel_listings- )+ return product.then(calculate_pricing_with_product)- return product.then(calculate_pricing_with_product)+ return variant_channel_listing.then(+ calculate_pricing_with_product_variant_channel_listings+ )- return variant_channel_listing.then(- calculate_pricing_with_product_variant_channel_listings- )+ return channel.then(calculate_pricing_with_channel)- return channel.then(calculate_pricing_with_channel)+ return (+ DiscountsByDateTimeLoader(context)+ .load(info.context.request_time)+ .then(calculate_pricing_info)+ )- return (- DiscountsByDateTimeLoader(context)- .load(info.context.request_time)- .then(calculate_pricing_info)- )+ if not country_code:+ return (+ WarehouseCountryCodeByChannelLoader(context)+ .load(channel_slug)+ .then(calculate_discounts)+ )+ return calculate_discounts(country_code)@staticmethoddef resolve_product(root: ChannelContext[models.ProductVariant], info):@@ -657,11 +666,9 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):if not root.channel_slug:return None- country_code = get_user_country_context(- address, info.context.site.settings.company_address- )- context = info.contextchannel_slug = str(root.channel_slug)+ context = info.context+product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(context).load((root.node.id, channel_slug))@@ -674,53 +681,72 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):collections = CollectionsByProductIdLoader(context).load(root.node.id)channel = ChannelBySlugLoader(context).load(channel_slug)- def calculate_pricing_info(discounts):- def calculate_pricing_with_channel(channel):- def calculate_pricing_with_product_channel_listings(- product_channel_listing,- ):- def calculate_pricing_with_variants(variants):- def calculate_pricing_with_variants_channel_listings(- variants_channel_listing,- ):- def calculate_pricing_with_collections(collections):- if not variants_channel_listing:- return None- availability = get_product_availability(- product=root.node,- product_channel_listing=product_channel_listing,- variants=variants,- variants_channel_listing=variants_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,- manager=context.plugins,- country=Country(country_code),- local_currency=get_currency_for_country(- country_code- ),+ country_code = address.country if address is not None else None++ def calculate_discounts(country_code):+ def calculate_pricing_info(discounts):+ def calculate_pricing_with_channel(channel):+ def calculate_pricing_with_product_channel_listings(+ product_channel_listing,+ ):+ def calculate_pricing_with_variants(variants):+ def calculate_pricing_with_variants_channel_listings(+ variants_channel_listing,+ ):+ def calculate_pricing_with_collections(collections):+ if not variants_channel_listing:+ return None++ vc_listing = variants_channel_listing+ local_currency = None+ if country_code:+ local_currency = get_currency_for_country(+ country_code+ )++ availability = get_product_availability(+ product=root.node,+ product_channel_listing=product_channel_listing,+ variants=variants,+ variants_channel_listing=vc_listing,+ collections=collections,+ discounts=discounts,+ channel=channel,+ manager=context.plugins,+ country=Country(country_code),+ local_currency=local_currency,+ )+ return ProductPricingInfo(**asdict(availability))++ return collections.then(+ calculate_pricing_with_collections)- return ProductPricingInfo(**asdict(availability))- return collections.then(calculate_pricing_with_collections)+ return variants_channel_listing.then(+ calculate_pricing_with_variants_channel_listings+ )- return variants_channel_listing.then(- calculate_pricing_with_variants_channel_listings- )+ return variants.then(calculate_pricing_with_variants)- return variants.then(calculate_pricing_with_variants)+ return product_channel_listing.then(+ calculate_pricing_with_product_channel_listings+ )- return product_channel_listing.then(- calculate_pricing_with_product_channel_listings- )+ return channel.then(calculate_pricing_with_channel)- return channel.then(calculate_pricing_with_channel)+ return (+ DiscountsByDateTimeLoader(context)+ .load(info.context.request_time)+ .then(calculate_pricing_info)+ )- return (- DiscountsByDateTimeLoader(context)- .load(info.context.request_time)- .then(calculate_pricing_info)- )+ if not country_code:+ return (+ WarehouseCountryCodeByChannelLoader(context)+ .load(channel_slug)+ .then(calculate_discounts)+ )+ return calculate_discounts(country_code)@staticmethod@traced_resolver@@ -729,21 +755,51 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return Nonechannel_slug = str(root.channel_slug)- country_code = get_user_country_context(- address, info.context.site.settings.company_address- )+ country_code = address.country if address is not None else None++ requestor = get_user_or_app_from_context(info.context)+ is_staff = requestor_is_staff_member_or_app(requestor)+ channel_slug = str(root.channel_slug)++ def calculate_is_available(quantities):+ for qty in quantities:+ if qty > 0:+ return True+ return False++ def load_variants_availability(variants):+ keys = [(variant.id, country_code, channel_slug) for variant in variants]+ return AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(+ info.context+ ).load_many(keys)++ def check_variant_availability():+ if is_staff and not channel_slug:+ variants = ProductVariantsByProductIdLoader(info.context).load(+ root.node.id+ )+ elif is_staff and channel_slug:+ variants = ProductVariantsByProductIdAndChannel(info.context).load(+ (root.node.id, channel_slug)+ )+ else:+ variants = AvailableProductVariantsByProductIdAndChannel(+ info.context+ ).load((root.node.id, channel_slug))+ return variants.then(load_variants_availability).then(+ calculate_is_available+ )- def calculate_is_available(product_channel_listing):- in_stock = is_product_in_stock(root.node, country_code, channel_slug)- is_visible = False+ def check_is_available_for_purchase(product_channel_listing):if product_channel_listing:- is_visible = product_channel_listing.is_available_for_purchase()- return is_visible and in_stock+ if product_channel_listing.is_available_for_purchase():+ return check_variant_availability()+ return Falsereturn (ProductChannelListingByProductIdAndChannelSlugLoader(info.context).load((root.node.id, channel_slug))- .then(calculate_is_available)+ .then(check_is_available_for_purchase))@staticmethoddiff --git a/saleor/graphql/tests/test_utils.py b/saleor/graphql/tests/test_utils.pyindex 009c5cf590..50bdc9f24e 100644--- a/saleor/graphql/tests/test_utils.py+++ b/saleor/graphql/tests/test_utils.py@@ -1,54 +1,10 @@import re-import graphene-from django.conf import settingsfrom graphql.utils import schema_printer-from ..account.types import AddressInput-from ..utils import get_user_country_contextfrom .utils import get_graphql_content-def test_get_user_country_context_from_address_instance(address, address_other_country):- destination_address = address- company_address = address_other_country-- country = get_user_country_context(destination_address=destination_address)- assert country == destination_address.country.code-- country = get_user_country_context(company_address=company_address)- assert country == company_address.country.code-- country = get_user_country_context(- destination_address=destination_address, company_address=company_address- )- assert country == destination_address.country.code-- country = get_user_country_context()- assert country == settings.DEFAULT_COUNTRY---def test_get_user_country_from_address_input():- class Query(graphene.ObjectType):- field = graphene.Field(graphene.String, address=graphene.Argument(AddressInput))-- @staticmethod- def resolve_field(_root, _info, address):- return get_user_country_context(destination_address=address)-- schema = graphene.Schema(query=Query)- result = schema.execute(- """- query {- field(address: {country: US})- }- """- )-- assert not result.errors- assert result.data == {"field": "US"}--def test_multiple_interface_separator_in_schema(api_client):query = """query __ApolloGetServiceDefinition__ {diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 78e94dfd08..a795207a78 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -1,21 +1,15 @@-from typing import TYPE_CHECKING, Optional, Union+from typing import Unionimport graphene-from django.conf import settingsfrom django.db.models import Valuefrom django.db.models.functions import Concatfrom graphene_django.registry import get_global_registryfrom graphql.error import GraphQLErrorfrom graphql_relay import from_global_id-from ...account import models as account_modelsfrom ..core.enums import PermissionEnumfrom ..core.types import Permission-if TYPE_CHECKING:- from ..account import types as account_types--ERROR_COULD_NO_RESOLVE_GLOBAL_ID = ("Could not resolve to a node with the global id list of '%s'.")@@ -136,26 +130,3 @@ def get_user_or_app_from_context(context):def requestor_is_superuser(requestor):"""Return True if requestor is superuser."""return getattr(requestor, "is_superuser", False)---def get_user_country_context(- destination_address: Optional[- Union["account_types.AddressInput", "account_models.Address"]- ] = None,- company_address: Optional["account_models.Address"] = None,-) -> str:- """Get country of the current user to use for tax and stock related calculations.-- User's country context is determined from the provided `destination_address` (which- may represent user's current location determined by the client or a shipping- address provided in the checkout). If `destination_address` is not given, the- default company address from the shop settings is assumed. If this address is not- set, fallback to the `DEFAULT_COUNTRY` setting.- """- if destination_address and destination_address.country:- if isinstance(destination_address, account_models.Address):- return destination_address.country.code- return destination_address.country- elif company_address and company_address.country:- return company_address.country.code- return settings.DEFAULT_COUNTRYdiff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 5448f773ef..4f5e4f1ab6 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -5,14 +5,16 @@ from uuid import UUIDfrom django.conf import settingsfrom ...warehouse.models import Stock, Warehouse+from ..account.dataloaders import AddressByIdLoader+from ..channel.dataloaders import ChannelBySlugLoaderfrom ..core.dataloaders import DataLoaderCountryCode = Optional[str]-VariantIdAndCountryCode = Tuple[int, CountryCode]+VariantIdCountryCodeChannelSlug = Tuple[int, CountryCode, str]class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(- DataLoader[VariantIdAndCountryCode, int]+ DataLoader[VariantIdCountryCodeChannelSlug, int]):"""Calculates available variant quantity based on variant ID and country code.@@ -37,11 +39,11 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(# For each country code execute a single query for all product variants.quantity_by_variant_and_country: DefaultDict[- VariantIdAndCountryCode, int+ VariantIdCountryCodeChannelSlug, int] = defaultdict(int)for key, variant_ids in variants_by_country_and_channel.items():country_code, channel_slug = key- quantities = self.batch_load_country(+ quantities = self.batch_load_quantities_by_country(country_code, channel_slug, variant_ids)for variant_id, quantity in quantities:@@ -51,25 +53,25 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(return [quantity_by_variant_and_country[key] for key in keys]- def batch_load_country(+ def batch_load_quantities_by_country(self,- country_code: CountryCode,+ country_code: Optional[CountryCode],channel_slug: Optional[str],variant_ids: Iterable[int],) -> Iterable[Tuple[int, int]]:# get stocks only for warehouses assigned to the shipping zones# that are available in the given channel- results = Stock.objects.filter(product_variant_id__in=variant_ids)+ stocks = Stock.objects.filter(product_variant_id__in=variant_ids)if country_code:- results = results.filter(+ stocks = stocks.filter(warehouse__shipping_zones__countries__contains=country_code)if channel_slug:- results = results.filter(+ stocks = stocks.filter(warehouse__shipping_zones__channels__slug=channel_slug)- results = results.annotate_available_quantity()- results = results.values_list(+ stocks = stocks.annotate_available_quantity()+ stocks = stocks.values_list("product_variant_id", "warehouse__shipping_zones", "available_quantity")@@ -79,7 +81,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(quantity_by_shipping_zone_by_product_variant: DefaultDict[int, DefaultDict[int, int]] = defaultdict(lambda: defaultdict(int))- for variant_id, shipping_zone_id, quantity in results:+ for variant_id, shipping_zone_id, quantity in stocks:quantity_by_shipping_zone_by_product_variant[variant_id][shipping_zone_id] += quantity@@ -108,8 +110,8 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(]-class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader(- DataLoader[VariantIdAndCountryCode, Iterable[Stock]]+class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(+ DataLoader[VariantIdCountryCodeChannelSlug, Iterable[Stock]]):"""Return stocks with available quantity based on variant ID, country code, channel.@@ -123,17 +125,21 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader(# Split the list of keys by country first. A typical query will only touch# a handful of unique countries but may access thousands of product variants# so it's cheaper to execute one query per country.- variants_by_country: DefaultDict[CountryCode, List[int]] = defaultdict(list)+ variants_by_country_and_channel: DefaultDict[+ CountryCode, List[int]+ ] = defaultdict(list)for variant_id, country_code, channel_slug in keys:- variants_by_country[(country_code, channel_slug)].append(variant_id)+ variants_by_country_and_channel[(country_code, channel_slug)].append(+ variant_id+ )# For each country code execute a single query for all product variants.stocks_by_variant_and_country: DefaultDict[- VariantIdAndCountryCode, Iterable[Stock]+ VariantIdCountryCodeChannelSlug, Iterable[Stock]] = defaultdict(list)- for key, variant_ids in variants_by_country.items():+ for key, variant_ids in variants_by_country_and_channel.items():country_code, channel_slug = key- variant_ids_stocks = self.batch_load_country(+ variant_ids_stocks = self.batch_load_stocks_by_country(country_code, channel_slug, variant_ids)for variant_id, stocks in variant_ids_stocks:@@ -143,9 +149,9 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader(return [stocks_by_variant_and_country[key] for key in keys]- def batch_load_country(+ def batch_load_stocks_by_country(self,- country_code: CountryCode,+ country_code: Optional[CountryCode],channel_slug: Optional[str],variant_ids: Iterable[int],) -> Iterable[Tuple[int, List[Stock]]]:@@ -179,3 +185,47 @@ class WarehouseByIdLoader(DataLoader):def batch_load(self, keys):warehouses = Warehouse.objects.in_bulk(keys)return [warehouses.get(UUID(warehouse_uuid)) for warehouse_uuid in keys]+++class WarehouseCountryCodeByChannelLoader(DataLoader):+ """Loads country code of a first available warehouse that is found for a channel."""++ context_key = "warehouse_country_code_by_channel"++ def batch_load(self, keys):+ def with_channels(channels):+ address_id_by_channel_slug = dict()+ for channel in channels:+ first_warehouse = Warehouse.objects.get_first_warehouse_for_channel(+ channel.id+ )+ if first_warehouse:+ address_id_by_channel_slug[+ channel.slug+ ] = first_warehouse.address_id++ def with_addresses(addresses):+ address_by_id = {address.pk: address for address in addresses}+ country_codes = []+ for key in keys:+ address_id = address_id_by_channel_slug.get(key)+ address = address_by_id.get(address_id) if address_id else None+ if address and address.country:+ country_code = address.country.code+ else:+ # Fallback when warehouse address has no country set. API has+ # validation to prevent from adding such addresses, so this is+ # added only to handle an edge-case if a warehouse would be+ # added with bypassing the API (for instance with a migration).+ country_code = settings.DEFAULT_COUNTRY+ country_codes.append(country_code)+ return country_codes++ address_ids = address_id_by_channel_slug.values()+ return (+ AddressByIdLoader(self.context)+ .load_many(address_ids)+ .then(with_addresses)+ )++ return ChannelBySlugLoader(self.context).load_many(keys).then(with_channels)diff --git a/saleor/graphql/warehouse/tests/test_dataloaders.py b/saleor/graphql/warehouse/tests/test_dataloaders.pynew file mode 100644index 0000000000..1015694821--- /dev/null+++ b/saleor/graphql/warehouse/tests/test_dataloaders.py@@ -0,0 +1,31 @@+from unittest.mock import Mock++from ..dataloaders import WarehouseCountryCodeByChannelLoader+++def test_warehouse_country_code_loader(channel_USD, shipping_zone):+ warehouse = channel_USD.shipping_zones.first().warehouses.first()+ request = Mock(dataloaders={})++ def with_country_code(country_code):+ assert country_code == warehouse.address.country.code++ WarehouseCountryCodeByChannelLoader(request).load(channel_USD.slug).then(+ with_country_code+ )+++def test_warehouse_country_code_loader_fallback_to_settings_country_no_warehouse(+ channel_USD, settings+):+ # Change the DEFAULT_COUNTRY for test purpose to a country that is different than+ # fixtures' addresses.+ settings.DEFAULT_COUNTRY = "TH"+ request = Mock(dataloaders={})++ def with_country_code(country_code):+ assert country_code == "TH"++ WarehouseCountryCodeByChannelLoader(request).load(channel_USD.slug).then(+ with_country_code+ )diff --git a/saleor/graphql/warehouse/tests/test_stock.py b/saleor/graphql/warehouse/tests/test_stock.pyindex e4fd25beb3..873fdb60a6 100644--- a/saleor/graphql/warehouse/tests/test_stock.py+++ b/saleor/graphql/warehouse/tests/test_stock.py@@ -204,6 +204,7 @@ def test_stock_quantities_in_different_warehouses(productVariant(id: $id, channel: $channel) {quantityPL: quantityAvailable(address: { country: $country1 })quantityUS: quantityAvailable(address: { country: $country2 })+ quantityNoAddress: quantityAvailable}}"""@@ -229,6 +230,12 @@ def test_stock_quantities_in_different_warehouses(assert content["data"]["productVariant"]["quantityPL"] == stock_map["PL"]assert content["data"]["productVariant"]["quantityUS"] == stock_map["US"]+ # when country is not provided, should return max value of all available stock+ # quantities+ assert content["data"]["productVariant"]["quantityNoAddress"] == max(+ stock_map.values()+ )+def test_stock_quantity_is_max_from_all_warehouses_without_provided_country(api_client, channel_USD, variant_with_many_stocks_different_shipping_zonesdiff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex fddc64b30d..26f69aef51 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -147,10 +147,9 @@ def get_product_availability(discounts: Iterable[DiscountInfo],channel: Channel,manager: "PluginsManager",- country: Optional[Country] = None,+ country: Country,local_currency: Optional[str] = None,) -> ProductAvailability:- country = country or Country(settings.DEFAULT_COUNTRY)with opentracing.global_tracer().start_active_span("get_product_availability"):channel_slug = channel.slug@@ -237,10 +236,9 @@ def get_variant_availability(discounts: Iterable[DiscountInfo],channel: Channel,plugins: "PluginsManager",- country: Optional[Country] = None,+ country: Country,local_currency: Optional[str] = None,) -> VariantAvailability:- country = country or Country(settings.DEFAULT_COUNTRY)with opentracing.global_tracer().start_active_span("get_variant_availability"):channel_slug = channel.slugdiscounted = plugins.apply_taxes_to_product(diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 1a7e02b41a..860a12aef5 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -4012,18 +4012,18 @@ def warehouse(address, shipping_zone):@pytest.fixture-def warehouses(address):+def warehouses(address, address_usa):return Warehouse.objects.bulk_create([Warehouse(address=address.get_copy(),- name="Warehouse1",+ name="Warehouse PL",slug="warehouse1",email="[email protected]",),Warehouse(- address=address.get_copy(),- name="Warehouse2",+ address=address_usa.get_copy(),+ name="Warehouse USA",slug="warehouse2",email="[email protected]",),diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex caa24f9f82..d11011f7d2 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -8,7 +8,7 @@ from ..core.exceptions import InsufficientStock, InsufficientStockDatafrom .models import Stock, StockQuerySetif TYPE_CHECKING:- from ..product.models import Product, ProductVariant+ from ..product.models import ProductVariantdef _get_available_quantity(stocks: StockQuerySet) -> int:@@ -84,13 +84,3 @@ def check_stock_quantity_bulk(if insufficient_stocks:raise InsufficientStock(insufficient_stocks)---def is_product_in_stock(- product: "Product", country_code: str, channel_slug: str-) -> bool:- """Check if there is any variant of given product available in given country."""- stocks = Stock.objects.get_product_stocks_for_country_and_channel(- country_code, channel_slug, product- ).annotate_available_quantity()- return any(stocks.values_list("available_quantity", flat=True))diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex e725aad47a..f41390839c 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -25,6 +25,9 @@ class WarehouseQueryset(models.QuerySet):.order_by("pk"))+ def get_first_warehouse_for_channel(self, channel_pk: int):+ return self.filter(shipping_zones__channels=channel_pk).first()+class Warehouse(ModelWithMetadata):id = models.UUIDField(default=uuid.uuid4, primary_key=True)diff --git a/saleor/warehouse/tests/test_warehouse.py b/saleor/warehouse/tests/test_warehouse.pynew file mode 100644index 0000000000..d06c25508b--- /dev/null+++ b/saleor/warehouse/tests/test_warehouse.py@@ -0,0 +1,23 @@+from ...shipping.models import ShippingZone+from ..models import Warehouse+++def test_get_first_warehouse_for_channel_no_shipping_zone(+ warehouses_with_different_shipping_zone, channel_USD+):+ for shipping_zone in ShippingZone.objects.all():+ shipping_zone.channels.all().delete()+ # At this point warehouse has no shipping zones; getting the first warehouse for+ # channel should return None.+ warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel_USD.pk)+ assert warehouse is None+++def test_get_first_warehouse_for_channel(warehouses, channel_USD):+ warehouse_usa = warehouses[1]+ shipping_zone = ShippingZone.objects.create(name="USA", countries=["US"])+ shipping_zone.channels.add(channel_USD)+ warehouse_usa.shipping_zones.add(shipping_zone)++ first_warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel_USD.pk)+ assert first_warehouse == warehouse_usa