Skip to content

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

Return variant quantity available only for available warehouses for given channel

IKarbowiak92ae514d6cd6
diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.py
index d565c382cb..38738e3f44 100644
--- a/saleor/graphql/product/tests/test_variant_availability.py
+++ b/saleor/graphql/product/tests/test_variant_availability.py
@@ -1,6 +1,8 @@
import graphene
from django.test import override_settings
+from django_countries import countries
+from ....shipping.models import ShippingZone
from ...tests.utils import get_graphql_content
COUNTRY_CODE = "US"
@@ -26,6 +28,27 @@ def test_variant_quantity_available_without_country_code(
assert variant_data["quantityAvailable"] == 7
+def test_variant_quantity_available_without_country_code_and_no_channel_shipping_zones(
+ api_client, variant_with_many_stocks, channel_USD
+):
+ query = """
+ query variantAvailability($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
+ quantityAvailable
+ }
+ }
+ """
+ channel_USD.shipping_zones.clear()
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "channel": channel_USD.slug,
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["quantityAvailable"] == 0
+
+
QUERY_VARIANT_AVAILABILITY = """
query variantAvailability(
$id: ID!, $country: CountryCode, $address: AddressInput, $channel: String
@@ -53,6 +76,41 @@ def test_variant_quantity_available_with_country_code(
assert variant_data["byAddress"] == 7
+def test_variant_quantity_available_with_country_code_no_channel_shipping_zones(
+ api_client, variant_with_many_stocks, channel_USD
+):
+ channel_USD.shipping_zones.clear()
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "address": {"country": COUNTRY_CODE},
+ "channel": channel_USD.slug,
+ }
+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["deprecatedByCountry"] == 0
+ assert variant_data["byAddress"] == 0
+
+
+def test_variant_quantity_available_with_country_code_only_one_available_warehouse(
+ api_client, variant_with_many_stocks, channel_USD, warehouses_with_shipping_zone
+):
+ shipping_zone = ShippingZone.objects.create(
+ name="Test", countries=[code for code, name in countries]
+ )
+ warehouses_with_shipping_zone[0].shipping_zones.set([shipping_zone])
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "address": {"country": COUNTRY_CODE},
+ "channel": channel_USD.slug,
+ }
+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["deprecatedByCountry"] == 3
+ assert variant_data["byAddress"] == 3
+
+
def test_variant_quantity_available_with_null_as_country_code(
api_client, variant_with_many_stocks, channel_USD
):
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 3a1caefe35..05ec4dc530 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -70,7 +70,7 @@ from ...utils import (
)
from ...utils.filters import reporting_period_to_date
from ...warehouse.dataloaders import (
- AvailableQuantityByProductVariantIdAndCountryCodeLoader,
+ AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader,
StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader,
)
from ...warehouse.types import Stock
@@ -296,9 +296,9 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
if not root.node.track_inventory:
return settings.MAX_CHECKOUT_LINE_QUANTITY
- return AvailableQuantityByProductVariantIdAndCountryCodeLoader(
+ return AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
info.context
- ).load((root.node.id, country_code))
+ ).load((root.node.id, country_code, root.channel_slug))
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 91279d7043..8f7fa6e901 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -4,13 +4,14 @@ from typing import DefaultDict, Iterable, List, Optional, Tuple
from django.conf import settings
from ...warehouse.models import Stock
+from ..channel.dataloaders import ChannelBySlugLoader
from ..core.dataloaders import DataLoader
CountryCode = Optional[str]
VariantIdAndCountryCode = Tuple[int, CountryCode]
-class AvailableQuantityByProductVariantIdAndCountryCodeLoader(
+class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
DataLoader[VariantIdAndCountryCode, int]
):
"""Calculates available variant quantity based on variant ID and country code.
@@ -23,70 +24,94 @@ class AvailableQuantityByProductVariantIdAndCountryCodeLoader(
context_key = "available_quantity_by_productvariant_and_country"
def batch_load(self, keys):
- # 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)
- for variant_id, country_code in keys:
- variants_by_country[country_code].append(variant_id)
-
- # For each country code execute a single query for all product variants.
- quantity_by_variant_and_country: DefaultDict[
- VariantIdAndCountryCode, int
- ] = defaultdict(int)
- for country_code, variant_ids in variants_by_country.items():
- quantities = self.batch_load_country(country_code, variant_ids)
- for variant_id, quantity in quantities:
- quantity_by_variant_and_country[(variant_id, country_code)] = quantity
-
- return [quantity_by_variant_and_country[key] for key in keys]
-
- def batch_load_country(
- self, country_code: CountryCode, variant_ids: Iterable[int]
- ) -> Iterable[Tuple[int, int]]:
- results = Stock.objects.filter(product_variant_id__in=variant_ids)
- if country_code:
- results = results.filter(
- warehouse__shipping_zones__countries__contains=country_code
+ def with_channels(channels):
+ # 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_and_channel: DefaultDict[
+ CountryCode, List[int]
+ ] = defaultdict(list)
+ for variant_id, country_code, channel_slug in keys:
+ variants_by_country_and_channel[(country_code, channel_slug)].append(
+ variant_id
+ )
+
+ channel_map = {channel.slug: channel for channel in channels}
+
+ # For each country code execute a single query for all product variants.
+ quantity_by_variant_and_country: DefaultDict[
+ VariantIdAndCountryCode, int
+ ] = defaultdict(int)
+ for key, variant_ids in variants_by_country_and_channel.items():
+ country_code, channel_slug = key
+ quantities = batch_load_country(
+ country_code, channel_map[channel_slug], variant_ids
+ )
+ for variant_id, quantity in quantities:
+ quantity_by_variant_and_country[
+ (variant_id, country_code, channel_slug)
+ ] = quantity
+
+ return [quantity_by_variant_and_country[key] for key in keys]
+
+ def batch_load_country(
+ country_code: CountryCode, channel, 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
+ channel_shipping_zones = channel.shipping_zones.values_list("id", flat=True)
+ results = Stock.objects.filter(product_variant_id__in=variant_ids).filter(
+ warehouse__shipping_zones__id__in=channel_shipping_zones
)
- results = results.annotate_available_quantity()
- results = results.values_list(
- "product_variant_id", "warehouse__shipping_zones", "available_quantity"
- )
-
- # A single country code (or a missing country code) can return results from
- # multiple shipping zones. We want to combine all quantities within a single
- # zone and then find out which zone contains the highest total.
- 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:
- quantity_by_shipping_zone_by_product_variant[variant_id][
- shipping_zone_id
- ] += quantity
- quantity_map: DefaultDict[int, int] = defaultdict(int)
- for (
- variant_id,
- quantity_by_shipping_zone,
- ) in quantity_by_shipping_zone_by_product_variant.items():
- quantity_values = quantity_by_shipping_zone.values()
if country_code:
- # When country code is known, return the sum of quantities from all
- # shipping zones supporting given country.
- quantity_map[variant_id] = sum(quantity_values)
- else:
- # When country code is unknown, return the highest known quantity.
- quantity_map[variant_id] = max(quantity_values)
-
- # Return the quantities after capping them at the maximum quantity allowed in
- # checkout. This prevent users from tracking the store's precise stock levels.
- return [
- (
- variant_id,
- min(quantity_map[variant_id], settings.MAX_CHECKOUT_LINE_QUANTITY),
+ results = results.filter(
+ warehouse__shipping_zones__countries__contains=country_code
+ )
+ results = results.annotate_available_quantity()
+ results = results.values_list(
+ "product_variant_id", "warehouse__shipping_zones", "available_quantity"
)
- for variant_id in variant_ids
- ]
+
+ # A single country code (or a missing country code) can return results from
+ # multiple shipping zones. We want to combine all quantities within a single
+ # zone and then find out which zone contains the highest total.
+ 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:
+ quantity_by_shipping_zone_by_product_variant[variant_id][
+ shipping_zone_id
+ ] += quantity
+ quantity_map: DefaultDict[int, int] = defaultdict(int)
+ for (
+ variant_id,
+ quantity_by_shipping_zone,
+ ) in quantity_by_shipping_zone_by_product_variant.items():
+ quantity_values = quantity_by_shipping_zone.values()
+ if country_code:
+ # When country code is known, return the sum of quantities from all
+ # shipping zones supporting given country.
+ quantity_map[variant_id] = sum(quantity_values)
+ else:
+ # When country code is unknown, return the highest known quantity.
+ quantity_map[variant_id] = max(quantity_values)
+
+ # Return the quantities after capping them at the maximum quantity allowed
+ # in checkout. This prevent users from tracking the store's precise
+ # stock levels.
+ return [
+ (
+ variant_id,
+ min(quantity_map[variant_id], settings.MAX_CHECKOUT_LINE_QUANTITY),
+ )
+ for variant_id in variant_ids
+ ]
+
+ return (
+ ChannelBySlugLoader(self.context)
+ .load_many({slug for _, _, slug in keys})
+ .then(with_channels)
+ )
class StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader(
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index b15530fce0..f21ccde6be 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -615,6 +615,7 @@ def shipping_zone(db, channel_USD): # pylint: disable=W0613
shipping_zone = ShippingZone.objects.create(
name="Europe", countries=[code for code, name in countries]
)
+ shipping_zone.channels.add(channel_USD)
method = shipping_zone.shipping_methods.create(
name="DHL",
type=ShippingMethodType.PRICE_BASED,
@@ -638,6 +639,10 @@ def shipping_zones(db, channel_USD, channel_PLN):
ShippingZone(name="USA", countries=["US"]),
]
)
+
+ shipping_zone_poland.channels.add(channel_PLN, channel_USD)
+ shipping_zone_usa.channels.add(channel_PLN, channel_USD)
+
method = shipping_zone_poland.shipping_methods.create(
name="DHL",
type=ShippingMethodType.PRICE_BASED,