Skip to content

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

Add quantityAvailable field to ProductVariant type

fowczrek45fb813815ff
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 8461b8dcbd..93a033efd2 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -21,6 +21,7 @@ from ....product.utils.costs import get_margin_for_variant, get_product_costs_da
from ....warehouse.availability import (
get_available_quantity,
get_available_quantity_for_customer,
+ get_max_available_quantity_for_customer,
get_quantity_allocated,
is_product_in_stock,
is_variant_in_stock,
@@ -238,7 +239,6 @@ class ProductVariant(CountableDjangoObjectType):
digital_content = graphene.Field(
DigitalContent, description="Digital content for the product variant."
)
-
stocks = graphene.Field(
graphene.List(Stock),
description="Stocks for the product variant.",
@@ -248,6 +248,13 @@ class ProductVariant(CountableDjangoObjectType):
required=False,
),
)
+ quantity_available = graphene.Int(
+ required=True,
+ description="Quantity of a product available for sale in one checkout.",
+ country_code=graphene.Argument(
+ CountryCodeEnum, description="Two-letter ISO 3166-1 country code.",
+ ),
+ )
class Meta:
description = (
@@ -263,6 +270,14 @@ class ProductVariant(CountableDjangoObjectType):
return root.stocks.annotate_available_quantity().all()
return root.stocks.annotate_available_quantity().for_country(country_code).all()
+ @staticmethod
+ def resolve_quantity_available(
+ root: models.ProductVariant, info, country_code=None
+ ):
+ if not country_code:
+ return get_max_available_quantity_for_customer(root)
+ return get_available_quantity_for_customer(root, country_code)
+
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
def resolve_digital_content(root: models.ProductVariant, *_args):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 3cc68c2d05..51f19dce31 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3732,6 +3732,7 @@ type ProductVariant implements Node & ObjectWithMetadata {
translation(languageCode: LanguageCodeEnum!): ProductVariantTranslation
digitalContent: DigitalContent
stocks(countryCode: CountryCode): [Stock]
+ quantityAvailable(countryCode: CountryCode): Int!
}
type ProductVariantBulkCreate {
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index ccb86874ff..04684e3afb 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -5,6 +5,7 @@ from django.db.models import Sum
from django.db.models.functions import Coalesce
from ..core.exceptions import InsufficientStock
+from ..shipping.models import ShippingZone
from .models import Stock, StockQuerySet
if TYPE_CHECKING:
@@ -61,6 +62,26 @@ def get_available_quantity_for_customer(
return min(_get_available_quantity(stocks), settings.MAX_CHECKOUT_LINE_QUANTITY)
+def get_max_available_quantity_for_customer(variant: "ProductVariant") -> int:
+ """Return maximum checkout line quantity for all shipping zones."""
+ availability_in_shipping_zones = (
+ ShippingZone.objects.filter(warehouses__stock__product_variant=variant)
+ .values("pk")
+ .annotate(
+ available_quantity=Sum("warehouses__stock__quantity")
+ - Coalesce(Sum("warehouses__stock__allocations__quantity_allocated"), 0)
+ )
+ .values_list("available_quantity", flat=True)
+ )
+
+ if not availability_in_shipping_zones:
+ return 0
+ if not variant.track_inventory:
+ return settings.MAX_CHECKOUT_LINE_QUANTITY
+ max_available_in_shipping_zone = max(availability_in_shipping_zones)
+ return min(max_available_in_shipping_zone, settings.MAX_CHECKOUT_LINE_QUANTITY)
+
+
def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:
stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
if not stocks:
diff --git a/tests/api/benchmark/test_variant.py b/tests/api/benchmark/test_variant.py
index acba6d2634..63cb6a72d3 100644
--- a/tests/api/benchmark/test_variant.py
+++ b/tests/api/benchmark/test_variant.py
@@ -11,7 +11,12 @@ from tests.api.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_retrieve_variant_list(
- product_variant_list, api_client, count_queries, warehouse
+ product_variant_list,
+ api_client,
+ count_queries,
+ warehouse,
+ warehouse_no_shipping_zone,
+ shipping_zone_without_countries,
):
query = """
fragment BasicProductFields on Product {
@@ -81,6 +86,9 @@ def test_retrieve_variant_list(
node {
...ProductVariantFields
stockQuantity
+ quantityAvailable
+ quantityAvailablePl: quantityAvailable(countryCode: PL)
+ quantityAvailableUS: quantityAvailable(countryCode: US)
product {
...BasicProductFields
}
@@ -89,12 +97,20 @@ def test_retrieve_variant_list(
}
}
"""
- Stock.objects.bulk_create(
+ warehouse_2 = warehouse_no_shipping_zone
+ warehouse_2.shipping_zones.add(shipping_zone_without_countries)
+ stocks = [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=1)
+ for variant in product_variant_list
+ ]
+ stocks.extend(
[
- Stock(product_variant=variant, warehouse=warehouse)
+ Stock(product_variant=variant, warehouse=warehouse_2, quantity=2)
for variant in product_variant_list
]
)
+ Stock.objects.bulk_create(stocks)
+
variables = {
"ids": [
graphene.Node.to_global_id("ProductVariant", variant.pk)
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 9589008add..37b72a6fa5 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -3411,6 +3411,70 @@ def test_variant_availability_without_inventory_tracking_not_available(
assert variant_data["stockQuantity"] == 0
+@patch("saleor.graphql.product.types.products.get_available_quantity_for_customer")
+def test_variant_quantity_available_with_country_code(
+ mock_get_available_quantity_for_customer, api_client, variant
+):
+ query = """
+ query variantAvailability($id: ID!, $country: CountryCode) {
+ productVariant(id: $id) {
+ quantityAvailable(countryCode: $country)
+ }
+ }
+ """
+ country = "PL"
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "country": country,
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data
+ mock_get_available_quantity_for_customer.assert_called_once_with(variant, "PL")
+
+
+@patch("saleor.graphql.product.types.products.get_max_available_quantity_for_customer")
+def test_variant_quantity_available_without_country_code(
+ mock_get_max_available_quantity_for_customer, api_client, variant
+):
+ query = """
+ query variantAvailability($id: ID!) {
+ productVariant(id: $id) {
+ quantityAvailable
+ }
+ }
+ """
+ variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data
+ mock_get_max_available_quantity_for_customer.assert_called_once_with(variant)
+
+
+@patch("saleor.graphql.product.types.products.get_max_available_quantity_for_customer")
+def test_variant_quantity_available_with_null_as_country_code(
+ mock_get_available_quantity_for_customer, api_client, variant
+):
+ query = """
+ query variantAvailability($id: ID!, $country: CountryCode) {
+ productVariant(id: $id) {
+ quantityAvailable(countryCode: $country)
+ }
+ }
+ """
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "country": None,
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data
+ mock_get_available_quantity_for_customer.assert_called_once_with(variant)
+
+
@pytest.mark.parametrize(
"collection_filter, count",
[
diff --git a/tests/test_stock_availability.py b/tests/test_stock_availability.py
index b64d6edd6f..63979f0bad 100644
--- a/tests/test_stock_availability.py
+++ b/tests/test_stock_availability.py
@@ -7,9 +7,10 @@ from saleor.warehouse.availability import (
check_stock_quantity,
get_available_quantity,
get_available_quantity_for_customer,
+ get_max_available_quantity_for_customer,
get_quantity_allocated,
)
-from saleor.warehouse.models import Allocation
+from saleor.warehouse.models import Allocation, Stock
COUNTRY_CODE = "US"
@@ -90,6 +91,68 @@ def test_get_available_quantity_for_customer_without_stocks(variant_with_many_st
assert available_quantity == 0
+def test_get_max_available_quantity_for_customer(
+ variant_with_many_stocks,
+ warehouse_no_shipping_zone,
+ shipping_zone_without_countries,
+):
+ warehouse_no_shipping_zone.shipping_zones.add(shipping_zone_without_countries)
+ Stock.objects.create(
+ warehouse=warehouse_no_shipping_zone,
+ product_variant=variant_with_many_stocks,
+ quantity=12,
+ )
+
+ available_quantity = get_max_available_quantity_for_customer(
+ variant_with_many_stocks
+ )
+ assert available_quantity == 12
+
+
+def test_get_max_available_quantity_for_customer_with_allocations(
+ variant_with_many_stocks, order_line_with_allocation_in_many_stocks
+):
+ available_quantity = get_max_available_quantity_for_customer(
+ variant_with_many_stocks
+ )
+ assert available_quantity == 4
+
+
+def test_get_max_available_quantity_for_customer_without_stocks(
+ variant_with_many_stocks,
+):
+ variant_with_many_stocks.stocks.all().delete()
+ available_quantity = get_max_available_quantity_for_customer(
+ variant_with_many_stocks
+ )
+ assert available_quantity == 0
+
+
+@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
+def test_get_max_available_quantity_for_customer_with_max(
+ variant_with_many_stocks, settings
+):
+ stock = variant_with_many_stocks.stocks.first()
+ stock.quantity = 16
+ stock.save(update_fields=["quantity"])
+ available_quantity = get_max_available_quantity_for_customer(
+ variant_with_many_stocks
+ )
+ assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
+
+
+@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
+def test_get_max_available_quantity_for_customer_without_inventory_tracking(
+ variant_with_many_stocks, settings
+):
+ variant_with_many_stocks.track_inventory = False
+ variant_with_many_stocks.save(update_fields=["track_inventory"])
+ available_quantity = get_max_available_quantity_for_customer(
+ variant_with_many_stocks
+ )
+ assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
+
+
def test_get_quantity_allocated(
variant_with_many_stocks, order_line_with_allocation_in_many_stocks
):