Skip to content

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

Refactor quantity available

fowczrekcaddab149416
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 93a033efd2..6272e7f5b9 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -21,7 +21,6 @@ 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,
@@ -189,7 +188,8 @@ class ProductVariant(CountableDjangoObjectType):
required=True,
description="Quantity of a product available for sale.",
deprecation_reason=(
- "Use the stock field instead. This field will be removed after 2020-07-31."
+ "Use the quantity_available field instead. "
+ "This field will be removed after 2020-07-31."
),
)
price_override = graphene.Field(
@@ -274,8 +274,6 @@ class ProductVariant(CountableDjangoObjectType):
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
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index bd5d8ad85f..d378286e2f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3720,7 +3720,7 @@ type ProductVariant implements Node & ObjectWithMetadata {
meta: [MetaStore]! @deprecated(reason: "Use the `metadata` field. This field will be removed after 2020-07-31.")
quantity: Int! @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
quantityAllocated: Int @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
- stockQuantity: Int! @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
+ stockQuantity: Int! @deprecated(reason: "Use the quantity_available field instead. This field will be removed after 2020-07-31.")
priceOverride: Money
pricing: VariantPricingInfo
isAvailable: Boolean @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 04684e3afb..1c5bff3189 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -1,11 +1,11 @@
-from typing import TYPE_CHECKING
+from collections import defaultdict
+from typing import TYPE_CHECKING, Dict
from django.conf import settings
-from django.db.models import Sum
+from django.db.models import Q, 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:
@@ -51,35 +51,39 @@ def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
def get_available_quantity_for_customer(
- variant: "ProductVariant", country_code: str
+ variant: "ProductVariant", country_code: str = None
) -> int:
- """Return maximum checkout line quantity."""
- stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
- if not stocks:
- return 0
- if not variant.track_inventory:
- return settings.MAX_CHECKOUT_LINE_QUANTITY
- return min(_get_available_quantity(stocks), settings.MAX_CHECKOUT_LINE_QUANTITY)
-
+ """Return maximum 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")
+ Returns maximum checkout quantity for the given variant and country code.
+ If country code is missing return maximum checkout quantity from shipping zones.
+ """
+ query = Q(product_variant=variant)
+ if country_code:
+ query &= Q(warehouse__shipping_zones__countries__contains=country_code)
+ stocks = (
+ Stock.objects.filter(query)
.annotate(
- available_quantity=Sum("warehouses__stock__quantity")
- - Coalesce(Sum("warehouses__stock__allocations__quantity_allocated"), 0)
+ available_quantity=Sum("quantity")
+ - Coalesce(Sum("allocations__quantity_allocated"), 0)
)
- .values_list("available_quantity", flat=True)
+ .values_list("warehouse__shipping_zones", "available_quantity")
)
- if not availability_in_shipping_zones:
+ if not stocks:
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)
+
+ available_quantity_in_shipping_zones: Dict = defaultdict(int)
+ for shipping_zone_pk, available_quantity in stocks:
+ available_quantity_in_shipping_zones[shipping_zone_pk] += available_quantity
+
+ max_available_quantity = max(
+ available_quantity_in_shipping_zones.items(), key=lambda x: x[1]
+ )[1]
+
+ return min(max_available_quantity, settings.MAX_CHECKOUT_LINE_QUANTITY)
def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 37b72a6fa5..b585787c30 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -3434,9 +3434,9 @@ def test_variant_quantity_available_with_country_code(
mock_get_available_quantity_for_customer.assert_called_once_with(variant, "PL")
-@patch("saleor.graphql.product.types.products.get_max_available_quantity_for_customer")
+@patch("saleor.graphql.product.types.products.get_available_quantity_for_customer")
def test_variant_quantity_available_without_country_code(
- mock_get_max_available_quantity_for_customer, api_client, variant
+ mock_get_available_quantity_for_customer, api_client, variant
):
query = """
query variantAvailability($id: ID!) {
@@ -3450,10 +3450,10 @@ def test_variant_quantity_available_without_country_code(
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)
+ mock_get_available_quantity_for_customer.assert_called_once_with(variant, None)
-@patch("saleor.graphql.product.types.products.get_max_available_quantity_for_customer")
+@patch("saleor.graphql.product.types.products.get_available_quantity_for_customer")
def test_variant_quantity_available_with_null_as_country_code(
mock_get_available_quantity_for_customer, api_client, variant
):
@@ -3472,7 +3472,7 @@ def test_variant_quantity_available_with_null_as_country_code(
content = get_graphql_content(response)
variant_data = content["data"]["productVariant"]
assert variant_data
- mock_get_available_quantity_for_customer.assert_called_once_with(variant)
+ mock_get_available_quantity_for_customer.assert_called_once_with(variant, None)
@pytest.mark.parametrize(
diff --git a/tests/test_stock_availability.py b/tests/test_stock_availability.py
index 63979f0bad..108a4ed142 100644
--- a/tests/test_stock_availability.py
+++ b/tests/test_stock_availability.py
@@ -7,7 +7,6 @@ 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, Stock
@@ -91,66 +90,51 @@ 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,
+@override_settings(MAX_CHECKOUT_LINE_QUANTITY=2)
+def test_get_available_quantity_for_customer_with_max(
+ variant_with_many_stocks, settings
):
- 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
+ available_quantity = get_available_quantity_for_customer(
+ variant_with_many_stocks, COUNTRY_CODE
)
- assert available_quantity == 12
+ assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
-def test_get_max_available_quantity_for_customer_with_allocations(
+def test_get_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
+ available_quantity = get_available_quantity_for_customer(
+ variant_with_many_stocks, COUNTRY_CODE
)
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(
+def test_get_available_quantity_for_customer_without_inventory_tracking(
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
+ variant_with_many_stocks.track_inventory = False
+ variant_with_many_stocks.save(update_fields=["track_inventory"])
+ available_quantity = get_available_quantity_for_customer(
+ variant_with_many_stocks, COUNTRY_CODE
)
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
+def test_get_available_quantity_for_customer_without_country(
+ variant_with_many_stocks,
+ warehouse_no_shipping_zone,
+ shipping_zone_without_countries,
):
- 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
+ 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,
)
- assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
+
+ available_quantity = get_available_quantity_for_customer(variant_with_many_stocks)
+ assert available_quantity == 12
def test_get_quantity_allocated(