Skip to content

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

Return variant stocks available in given channel, if channel is given

IKarbowiakd3f492b644db
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 3a307d0ac8..a769fd7009 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -258,6 +258,68 @@ def test_get_product_variant_channel_listing_as_anonymous(
assert_no_permission(response)
+QUERY_PRODUCT_VARIANT_STOCKS = """
+ query ProductVariantDetails($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
+ id
+ stocks{
+ id
+ quantity
+ warehouse{
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_get_product_variant_stocks(
+ staff_api_client, variant_with_many_stocks, channel_USD, permission_manage_products
+):
+ # given
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_STOCKS,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ stocks_count = variant.stocks.count()
+ data = content["data"]["productVariant"]
+ assert len(data["stocks"]) == stocks_count
+
+
+def test_get_product_variant_stocks_no_channel_shipping_zones(
+ staff_api_client, variant_with_many_stocks, channel_USD, permission_manage_products
+):
+ # given
+ channel_USD.shipping_zones.clear()
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_STOCKS,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ stocks_count = variant.stocks.count()
+ data = content["data"]["productVariant"]
+ assert data["stocks"] == []
+ assert stocks_count > 0
+
+
CREATE_VARIANT_MUTATION = """
mutation createVariant (
$productId: ID!,
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 974b2fe21e..d5a33efb0e 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -71,7 +71,7 @@ from ...utils import (
from ...utils.filters import reporting_period_to_date
from ...warehouse.dataloaders import (
AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader,
- StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader,
+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader,
)
from ...warehouse.types import Stock
from ..dataloaders import (
@@ -277,9 +277,9 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
address, info.context.site.settings.company_address
)
- return StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader(
+ return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader(
info.context
- ).load((root.node.id, country_code))
+ ).load((root.node.id, country_code, root.channel_slug))
@staticmethod
def resolve_quantity_available(
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 8f7fa6e901..9138fcbbc5 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -114,44 +114,56 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
)
-class StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader(
+class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChanneLoader(
DataLoader[VariantIdAndCountryCode, Iterable[Stock]]
):
- """Return stocks with available quantity based on variant ID and country code.
+ """Return stocks with available quantity based on variant ID, country code, channel.
- For each country code, for each shipping zone supporting that country,
+ For each country code, for each shipping zone supporting that country and channel,
return stocks with maximum available quantity.
"""
- context_key = "stocks_with_available_quantity_by_productvariant_and_country"
+ context_key = "stocks_with_available_quantity_by_productvariant_country_and_channel"
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 variant_id, country_code, channel_slug in keys:
+ variants_by_country[(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]
] = defaultdict(list)
- for country_code, variant_ids in variants_by_country.items():
- variant_ids_stocks = self.batch_load_country(country_code, variant_ids)
+ for key, variant_ids in variants_by_country.items():
+ country_code, channel_slug = key
+ variant_ids_stocks = self.batch_load_country(
+ country_code, channel_slug, variant_ids
+ )
for variant_id, stocks in variant_ids_stocks:
- stocks_by_variant_and_country[(variant_id, country_code)].extend(stocks)
+ stocks_by_variant_and_country[
+ (variant_id, country_code, channel_slug)
+ ].extend(stocks)
return [stocks_by_variant_and_country[key] for key in keys]
def batch_load_country(
- self, country_code: CountryCode, variant_ids: Iterable[int]
+ self,
+ country_code: CountryCode,
+ channel_slug: Optional[str],
+ variant_ids: Iterable[int],
) -> Iterable[Tuple[int, List[Stock]]]:
stocks = Stock.objects.filter(product_variant_id__in=variant_ids)
if country_code:
stocks = stocks.filter(
warehouse__shipping_zones__countries__contains=country_code
)
+ if channel_slug:
+ stocks = stocks.filter(
+ warehouse__shipping_zones__channels__slug=channel_slug
+ )
stocks = stocks.annotate_available_quantity()
stocks_by_variant_id_map: DefaultDict[int, List[Stock]] = defaultdict(list)
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index 686d2a5380..00294f4412 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -62,6 +62,16 @@ class StockQuerySet(models.QuerySet):
- Coalesce(Sum("allocations__quantity_allocated"), 0)
)
+ def for_channel(self, channel_slug: str):
+ query_warehouse = models.Subquery(
+ Warehouse.objects.filter(
+ shipping_zones__channels__slug=channel_slug
+ ).values("pk")
+ )
+ return self.select_related("product_variant", "warehouse").filter(
+ warehouse__in=query_warehouse
+ )
+
def for_country(self, country_code: str, channel_slug=None):
filter_lookup = {"shipping_zones__countries__contains": country_code}
if channel_slug is not None: