Skip to content

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

Filter out products with low quantity

Mira Szewczykaf01da9af33e
diff --git a/saleor/stock/utils/availability.py b/saleor/stock/utils/availability.py
index fca0b0e6a6..45411f2a74 100644
--- a/saleor/stock/utils/availability.py
+++ b/saleor/stock/utils/availability.py
@@ -1,4 +1,7 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
+
+from django.conf import settings
+from django.db.models import Sum
from ...core.exceptions import InsufficientStock
from ...product.models import Product
@@ -58,3 +61,14 @@ def are_all_product_variants_in_stock(product: "Product", country_code: str) ->
product_variants = product.variants.exclude(id__in=variants_with_stocks).exists()
return are_all_available and not product_variants
+
+
+def products_with_low_stock(threshold: Optional[int] = None):
+ if threshold is None:
+ threshold = getattr(settings, "LOW_STOCK_THRESHOLD", 3000)
+ stocks = (
+ Stock.objects.select_related("product_variant")
+ .values("product_variant__product_id", "warehouse_id")
+ .annotate(total_stock=Sum("quantity"))
+ )
+ return stocks.filter(total_stock__lte=threshold).distinct()
diff --git a/tests/test_stock.py b/tests/test_stock.py
index 4a084f054a..b9cb99c436 100644
--- a/tests/test_stock.py
+++ b/tests/test_stock.py
@@ -5,6 +5,7 @@ from saleor.stock.models import Stock
from saleor.stock.utils.availability import (
are_all_product_variants_in_stock,
check_stock_quantity,
+ products_with_low_stock,
)
COUNTRY_CODE = "US"
@@ -58,3 +59,30 @@ def test_are_all_product_variants_in_stock_stock_empty(product):
def test_are_all_product_variants_in_stock_lack_of_stocks(product):
Stock.objects.all().delete()
assert not are_all_product_variants_in_stock(product, COUNTRY_CODE)
+
+
+def test_products_with_low_stock_one_stock(product, settings):
+ settings.LOW_STOCK_THRESHOLD = 70
+ stock = Stock.objects.first()
+ result = products_with_low_stock()
+ assert len(result) == 1
+ stock_result = result[0]
+ assert (
+ stock_result["product_variant__product_id"] == stock.product_variant.product_id
+ )
+ assert stock_result["warehouse_id"] == stock.warehouse_id
+ assert stock_result["total_stock"] == stock.quantity
+
+
+def test_products_with_low_stock_many_stocks(stock, settings):
+ settings.LOW_STOCK_THRESHOLD = 70
+ quantity = Stock.objects.all().values_list("quantity", flat=True)
+ result = products_with_low_stock()
+ assert result[0]["total_stock"] == sum(quantity)
+
+
+def test_products_with_low_stock_filter_properly(stock, settings):
+ quantities = Stock.objects.order_by("quantity").values_list("quantity", flat=True)
+ settings.LOW_STOCK_THRESHOLD = quantities[0] + 1
+ result = products_with_low_stock()
+ assert len(result) == 0