Skip to content

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

Add stock filtering to productVariants where input (#19339)

ayesha waris83c17996ce7c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa9fe4de68..ff1ed82b12 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,8 @@ All notable, unreleased changes to this project will be documented in this file.
### GraphQL API
+- Added `stockAvailability` and `stocks` filters to the `productVariants` query `where` input, allowing variants to be filtered by their stock status and stock quantity for a given channel - #17689 by @ayesha-waris
+
### Webhooks
### Other changes
diff --git a/saleor/graphql/product/filters/product.py b/saleor/graphql/product/filters/product.py
index 915f89c983..dc549b05fd 100644
--- a/saleor/graphql/product/filters/product.py
+++ b/saleor/graphql/product/filters/product.py
@@ -36,10 +36,7 @@ from ...core.filters.where_input import (
)
from ...core.scalars import DateTime
from ...core.types import (
- BaseInputObjectType,
DateTimeRangeInput,
- IntRangeInput,
- NonNullList,
PriceRangeInput,
)
from ...utils.filters import (
@@ -78,17 +75,11 @@ from .product_helpers import (
where_filter_stocks,
where_filter_updated_at_range,
)
-from .shared import filter_updated_at_range
+from .shared import ProductStockFilterInput, filter_updated_at_range
T_PRODUCT_FILTER_QUERIES = dict[int, list[int]]
-
-class ProductStockFilterInput(BaseInputObjectType):
- warehouse_ids = NonNullList(graphene.ID, required=False)
- quantity = graphene.Field(IntRangeInput, required=False)
-
- class Meta:
- doc_category = DOC_CATEGORY_PRODUCTS
+__all__ = ["ProductStockFilterInput"]
class ProductFilter(MetadataFilterBase):
diff --git a/saleor/graphql/product/filters/product_helpers.py b/saleor/graphql/product/filters/product_helpers.py
index 39536ccaeb..ef13a32e85 100644
--- a/saleor/graphql/product/filters/product_helpers.py
+++ b/saleor/graphql/product/filters/product_helpers.py
@@ -97,7 +97,14 @@ def filter_products_by_collections(qs, collection_pks):
return qs.filter(Exists(collection_products.filter(product_id=OuterRef("pk"))))
-def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
+def _get_in_stock_variant_stocks(qs, channel_slug):
+ """Return a Stock queryset of variants in stock for the channel's warehouses.
+
+ A variant is considered in stock when it has a stock with available quantity
+ (i.e. quantity greater than the sum of allocated and actively reserved quantity)
+ in a warehouse available for the given channel. The returned queryset is keyed by
+ ``product_variant_id``.
+ """
allocations = (
Allocation.objects.using(qs.db)
.values("stock_id")
@@ -119,7 +126,7 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
reservation_subquery = Subquery(queryset=reservations, output_field=IntegerField())
warehouse_pks = get_available_warehouse_pks_for_product(qs, channel_slug)
- stocks = (
+ return (
Stock.objects.using(qs.db)
.filter(
warehouse_id__in=warehouse_pks,
@@ -129,6 +136,9 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
.values("product_variant_id")
)
+
+def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
+ stocks = _get_in_stock_variant_stocks(qs, channel_slug)
variants = (
ProductVariant.objects.using(qs.db)
.filter(Exists(stocks.filter(product_variant_id=OuterRef("pk"))))
@@ -141,6 +151,17 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
return qs
+def filter_variants_by_stock_availability(qs, stock_availability, channel_slug):
+ """Filter a ProductVariant queryset by stock availability for the given channel."""
+ stocks = _get_in_stock_variant_stocks(qs, channel_slug)
+ in_stock = Exists(stocks.filter(product_variant_id=OuterRef("pk")))
+ if stock_availability == StockAvailability.IN_STOCK.value: # type: ignore[attr-defined]
+ qs = qs.filter(in_stock)
+ if stock_availability == StockAvailability.OUT_OF_STOCK.value: # type: ignore[attr-defined]
+ qs = qs.filter(~in_stock)
+ return qs
+
+
def get_available_warehouse_pks_for_product(qs, channel_slug):
# refetch the site to make sure that we have the latest settings
Site.objects.clear_cache()
@@ -523,6 +544,65 @@ def where_filter_stock_availability(qs, _, value, channel_slug):
return qs.none()
+def where_filter_variant_stock_availability(qs, _, value, channel_slug):
+ if value:
+ return filter_variants_by_stock_availability(qs, value, channel_slug)
+ return qs.none()
+
+
+def where_filter_variant_warehouses(qs, value):
+ if not value:
+ return qs.none()
+ _, warehouse_pks = resolve_global_ids_to_primary_keys(
+ value, warehouse_types.Warehouse
+ )
+ warehouses = (
+ Warehouse.objects.using(qs.db).filter(pk__in=warehouse_pks).values("pk")
+ )
+ stocks = (
+ Stock.objects.using(qs.db)
+ .filter(Exists(warehouses.filter(pk=OuterRef("warehouse"))))
+ .values("product_variant_id")
+ )
+ return qs.filter(Exists(stocks.filter(product_variant_id=OuterRef("pk"))))
+
+
+def where_filter_variant_quantity(qs, quantity_value, warehouse_ids=None):
+ """Filter variants queryset by their aggregated stock quantity.
+
+ Returns variants whose total stock quantity falls between the given range. If
+ warehouses are given, only stocks from those warehouses are aggregated.
+ """
+ stocks = Stock.objects.using(qs.db).all()
+ if warehouse_ids:
+ _, warehouse_pks = resolve_global_ids_to_primary_keys(
+ warehouse_ids, warehouse_types.Warehouse
+ )
+ stocks = stocks.filter(warehouse_id__in=warehouse_pks)
+ stocks = stocks.values("product_variant_id").filter(
+ product_variant_id=OuterRef("pk")
+ )
+ total_quantity = Subquery(stocks.values_list(Sum("quantity")))
+ qs = qs.annotate(
+ total_quantity=ExpressionWrapper(total_quantity, output_field=IntegerField())
+ )
+ return _filter_range(qs, "total_quantity", quantity_value)
+
+
+def where_filter_variant_stocks(qs, _, value):
+ if not value:
+ return qs.none()
+ warehouse_ids = value.get("warehouse_ids")
+ quantity = value.get("quantity")
+ if warehouse_ids and not quantity:
+ return where_filter_variant_warehouses(qs, warehouse_ids)
+ if quantity and not warehouse_ids:
+ return where_filter_variant_quantity(qs, quantity)
+ if quantity and warehouse_ids:
+ return where_filter_variant_quantity(qs, quantity, warehouse_ids)
+ return qs.none()
+
+
def where_filter_gift_card(qs, _, value):
if value is None:
return qs.none()
diff --git a/saleor/graphql/product/filters/product_variant.py b/saleor/graphql/product/filters/product_variant.py
index 99c4273a48..3bed655c2c 100644
--- a/saleor/graphql/product/filters/product_variant.py
+++ b/saleor/graphql/product/filters/product_variant.py
@@ -34,9 +34,11 @@ from ...attribute.shared_filters import (
get_attribute_values_by_slug_or_name_value,
validate_attribute_value_input,
)
-from ...core.descriptions import ADDED_IN_322
+from ...channel.filters import get_channel_slug_from_filter_data
+from ...core.descriptions import ADDED_IN_322, ADDED_IN_324
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.filters import (
+ EnumWhereFilter,
FilterInputObjectType,
GlobalIDMultipleChoiceWhereFilter,
ListObjectTypeFilter,
@@ -54,7 +56,12 @@ from ...utils.filters import (
filter_where_by_range_field,
filter_where_by_value_field,
)
-from .shared import filter_updated_at_range
+from ..enums import StockAvailability
+from .product_helpers import (
+ where_filter_variant_stock_availability,
+ where_filter_variant_stocks,
+)
+from .shared import ProductStockFilterInput, filter_updated_at_range
def filter_sku_list(qs, _, value):
@@ -734,6 +741,19 @@ class ProductVariantWhere(MetadataWhereFilterBase):
method="filter_attributes",
help_text="Filter by attributes associated with the variant." + ADDED_IN_322,
)
+ stock_availability = EnumWhereFilter(
+ input_class=StockAvailability,
+ method="filter_stock_availability",
+ help_text=(
+ "Filter by variants having a specific stock status in the given channel."
+ + ADDED_IN_324
+ ),
+ )
+ stocks = ObjectTypeWhereFilter(
+ input_class=ProductStockFilterInput,
+ method="filter_stocks",
+ help_text="Filter by stock of the variant." + ADDED_IN_324,
+ )
class Meta:
model = ProductVariant
@@ -753,6 +773,14 @@ class ProductVariantWhere(MetadataWhereFilterBase):
return qs
return filter_variants_by_attributes(qs, value)
+ def filter_stock_availability(self, qs, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return where_filter_variant_stock_availability(qs, name, value, channel_slug)
+
+ @staticmethod
+ def filter_stocks(qs, name, value):
+ return where_filter_variant_stocks(qs, name, value)
+
def is_valid(self):
if attributes := self.data.get("attributes"):
validate_attribute_value_input(attributes, self.queryset.db)
diff --git a/saleor/graphql/product/filters/shared.py b/saleor/graphql/product/filters/shared.py
index fe67888bf8..3897300948 100644
--- a/saleor/graphql/product/filters/shared.py
+++ b/saleor/graphql/product/filters/shared.py
@@ -1,5 +1,17 @@
+import graphene
+
+from ...core.doc_category import DOC_CATEGORY_PRODUCTS
+from ...core.types import BaseInputObjectType, IntRangeInput, NonNullList
from ...utils.filters import filter_range_field
def filter_updated_at_range(qs, _, value):
return filter_range_field(qs, "updated_at", value)
+
+
+class ProductStockFilterInput(BaseInputObjectType):
+ warehouse_ids = NonNullList(graphene.ID, required=False)
+ quantity = graphene.Field(IntRangeInput, required=False)
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
diff --git a/saleor/graphql/product/tests/queries/variants_where/test_over_stock.py b/saleor/graphql/product/tests/queries/variants_where/test_over_stock.py
new file mode 100644
index 0000000000..8bbc893db6
--- /dev/null
+++ b/saleor/graphql/product/tests/queries/variants_where/test_over_stock.py
@@ -0,0 +1,216 @@
+import datetime
+
+import graphene
+import pytest
+from django.utils import timezone
+
+from ......warehouse.models import Allocation, Reservation, Stock, Warehouse
+from .....tests.utils import get_graphql_content
+from .shared import PRODUCT_VARIANTS_WHERE_QUERY
+
+
+ ("where", "indexes"),
+ [
+ ({"stockAvailability": "OUT_OF_STOCK"}, [0, 1]),
+ ({"stockAvailability": "IN_STOCK"}, [2]),
+ ({"stockAvailability": None}, []),
+ ],
+)
+def test_variants_filter_by_stock_availability(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ # ``product_list`` yields 3 products with a single, in-stock variant each.
+ variants = [prod.variants.first() for prod in product_list]
+ # make the first two variants out of stock by zeroing their stock quantity
+ Stock.objects.filter(product_variant__in=variants[:2]).update(quantity=0)
+
+ variables = {"channel": channel_USD.slug, "where": where}
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ nodes = content["data"]["productVariants"]["edges"]
+ returned_ids = {node["node"]["id"] for node in nodes}
+ expected_ids = {
+ graphene.Node.to_global_id("ProductVariant", variants[index].id)
+ for index in indexes
+ }
+ assert returned_ids == expected_ids
+
+
+def test_variants_filter_by_stock_availability_respects_allocations(
+ api_client, product_list, order_line, channel_USD
+):
+ # given
+ variants = [prod.variants.first() for prod in product_list]
+ # fully allocate the stock of the first variant -> out of stock
+ allocated_variant = variants[0]
+ stock = allocated_variant.stocks.first()
+ Allocation.objects.create(
+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"stockAvailability": "IN_STOCK"},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ returned_ids = {
+ node["node"]["id"] for node in content["data"]["productVariants"]["edges"]
+ }
+ allocated_id = graphene.Node.to_global_id("ProductVariant", allocated_variant.id)
+ in_stock_id = graphene.Node.to_global_id("ProductVariant", variants[1].id)
+ assert allocated_id not in returned_ids
+ assert in_stock_id in returned_ids
+
+
+ ("reserved_delta", "expected_in_stock"),
+ [
+ # active reservation consumes the available quantity
+ (datetime.timedelta(minutes=5), False),
+ # expired reservation is ignored
+ (datetime.timedelta(minutes=-5), True),
+ ],
+)
+def test_variants_filter_by_stock_availability_respects_reservations(
+ reserved_delta,
+ expected_in_stock,
+ api_client,
+ product_with_two_variants,
+ checkout_line,
+ channel_USD,
+):
+ # given
+ variants = list(product_with_two_variants.variants.all().order_by("pk"))
+ reserved_variant = variants[0]
+ stock = reserved_variant.stocks.first()
+ Reservation.objects.create(
+ checkout_line=checkout_line,
+ stock=stock,
+ quantity_reserved=stock.quantity,
+ reserved_until=timezone.now() + reserved_delta,
+ )
+
+ variables = {
+ "where": {"stockAvailability": "IN_STOCK"},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ returned_ids = {
+ node["node"]["id"] for node in content["data"]["productVariants"]["edges"]
+ }
+ reserved_variant_id = graphene.Node.to_global_id(
+ "ProductVariant", reserved_variant.id
+ )
+ assert (reserved_variant_id in returned_ids) is expected_in_stock
+
+
+ ("quantity_input", "warehouse_indexes", "variant_indexes"),
+ [
+ # aggregated over all warehouses: v1=100, v2=35, v3=30
+ ({"lte": 40}, [], [1, 2]),
+ ({"gte": 50}, [], [0]),
+ ({"gte": 10, "lte": 30}, [], [2]),
+ ({"gte": 1000}, [], []),
+ ({"lte": None, "gte": None}, [], []),
+ # scoped to a single warehouse, any quantity
+ (None, [1], [1]),
+ (None, [2], [0, 1, 2]),
+ ],
+)
+def test_variants_filter_by_stocks(
+ quantity_input,
+ warehouse_indexes,
+ variant_indexes,
+ api_client,
+ product_with_single_variant,
+ product_with_two_variants,
+ warehouse,
+ channel_USD,
+):
+ # given
+ v1 = product_with_single_variant.variants.first()
+ v2, v3 = product_with_two_variants.variants.all().order_by("pk")
+ variants = [v1, v2, v3]
+
+ # reset fixture-provided stocks for a deterministic setup
+ Stock.objects.filter(product_variant__in=variants).delete()
+
+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ second_warehouse.slug = "second-warehouse"
+ second_warehouse.pk = None
+ second_warehouse.save()
+
+ third_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ third_warehouse.slug = "third-warehouse"
+ third_warehouse.pk = None
+ third_warehouse.save()
+
+ warehouses = [warehouse, second_warehouse, third_warehouse]
+ warehouse_ids = [
+ graphene.Node.to_global_id("Warehouse", warehouses[index].pk)
+ for index in warehouse_indexes
+ ]
+
+ Stock.objects.bulk_create(
+ [
+ Stock(warehouse=third_warehouse, product_variant=v1, quantity=100),
+ Stock(warehouse=second_warehouse, product_variant=v2, quantity=10),
+ Stock(warehouse=third_warehouse, product_variant=v2, quantity=25),
+ Stock(warehouse=third_warehouse, product_variant=v3, quantity=30),
+ ]
+ )
+
+ variables = {
+ "where": {
+ "stocks": {"quantity": quantity_input, "warehouseIds": warehouse_ids}
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ returned_ids = {
+ node["node"]["id"] for node in content["data"]["productVariants"]["edges"]
+ }
+ expected_ids = {
+ graphene.Node.to_global_id("ProductVariant", variants[index].id)
+ for index in variant_indexes
+ }
+ assert returned_ids == expected_ids
+
+
+def test_variants_filter_by_none_as_stocks(
+ api_client, product_with_single_variant, channel_USD
+):
+ # given
+ variables = {
+ "where": {"stocks": None},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["productVariants"]["edges"] == []
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 27db0e94ba..e577c20f04 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -10136,6 +10136,20 @@ input ProductVariantWhereInput @doc(category: "Products") {
"""
attributes: [AssignedAttributeWhereInput!]
+ """
+ Filter by variants having a specific stock status in the given channel.
+
+ Added in Saleor 3.24.
+ """
+ stockAvailability: StockAvailability
+
+ """
+ Filter by stock of the variant.
+
+ Added in Saleor 3.24.
+ """
+ stocks: ProductStockFilterInput
+
"""List of conditions that must be met."""
AND: [ProductVariantWhereInput!]