Skip to content

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

Fix duplicated stock when calculate avaiable quantity

fowczrekd398ec8c404e
diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.py
index e0dfe7ea3b..0d2d34c002 100644
--- a/saleor/graphql/product/tests/test_variant_availability.py
+++ b/saleor/graphql/product/tests/test_variant_availability.py
@@ -9,7 +9,7 @@ from django_countries import countries
from ....channel.utils import DEPRECATION_WARNING_MESSAGE
from ....shipping.models import ShippingZone
from ....warehouse import WarehouseClickAndCollectOption
-from ....warehouse.models import PreorderReservation, Reservation, Stock
+from ....warehouse.models import PreorderReservation, Reservation, Stock, Warehouse
from ...tests.utils import get_graphql_content
COUNTRY_CODE = "US"
@@ -302,6 +302,28 @@ def test_variant_quantity_available_with_country_code(
assert variant_data["byAddress"] == 7
+def test_variant_quantity_available_with_country_code_warehouse_in_many_shipping_zones(
+ api_client, variant_with_many_stocks, channel_USD, shipping_zone_JPY
+):
+ shipping_zone = ShippingZone.objects.create(
+ name="Test",
+ countries=[code for code, name in countries],
+ )
+ shipping_zone.channels.add(channel_USD)
+ warehouse = Warehouse.objects.get(slug="warehouse2")
+ warehouse.shipping_zones.add(shipping_zone)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "address": {"country": COUNTRY_CODE},
+ "channel": channel_USD.slug,
+ }
+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["deprecatedByCountry"] == 7
+ assert variant_data["byAddress"] == 7
+
+
def test_variant_quantity_available_with_country_code_no_channel_shipping_zones(
api_client, variant_with_many_stocks, channel_USD
):
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index e9866072e7..ae14074d34 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -111,19 +111,22 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
stocks_reservations = self.prepare_stocks_reservations_map(variant_ids)
# A single country code (or a missing country code) can return results from
- # multiple shipping zones. We want to combine all quantities within a single
- # zone and then find out which zone contains the highest total.
+ # multiple shipping zones. We want to prepare warehouse by shipping zone map
+ # and quantity by warehouse map. To be able to calculate max quantity available
+ # in any shipping zones combination without duplicating warehouse quantity.
(
- quantity_by_shipping_zone_by_variant,
+ warehouse_ids_by_shipping_zone_by_variant,
variants_with_global_cc_warehouses,
- ) = self.prepare_quantity_by_shipping_zone_and_variant_map(
+ available_quantity_by_warehouse_id,
+ ) = self.prepare_warehouse_ids_by_shipping_zone_and_variant_map(
stocks, stocks_reservations, warehouse_shipping_zones_map, cc_warehouses
)
quantity_map = self.prepare_quantity_map(
country_code,
- quantity_by_shipping_zone_by_variant,
+ warehouse_ids_by_shipping_zone_by_variant,
variants_with_global_cc_warehouses,
+ available_quantity_by_warehouse_id,
)
# Return the quantities after capping them at the maximum quantity allowed in
@@ -231,15 +234,17 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
stocks_reservations[stock_id] = quantity_reserved
return stocks_reservations
- def prepare_quantity_by_shipping_zone_and_variant_map(
+ def prepare_warehouse_ids_by_shipping_zone_and_variant_map(
self, stocks, stocks_reservations, warehouse_shipping_zones_map, cc_warehouses
):
"""Combine all quantities within a single zone.
- Prepare the map in the following format:
+ Prepare `warehouse_ids_by_shipping_zone_by_variant` map in the following format:
{
variant_id: {
- shipping_zone_id/warehouse_id: quantity
+ shipping_zone_id/warehouse_id: [
+ warehouse_id
+ ]
}
}
@@ -248,10 +253,11 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
as a magic single-warehouse shipping zone.
"""
cc_warehouses_in_bulk = cc_warehouses.in_bulk()
- quantity_by_shipping_zone_by_variant: DefaultDict[
- int, DefaultDict[int, int]
- ] = defaultdict(lambda: defaultdict(int))
+ warehouse_ids_by_shipping_zone_by_variant: DefaultDict[
+ int, DefaultDict[int, List[UUID]]
+ ] = defaultdict(lambda: defaultdict(list))
variants_with_global_cc_warehouses = []
+ available_quantity_by_warehouse_id: DefaultDict[UUID, int] = defaultdict(int)
for stock in stocks:
reserved_quantity = stocks_reservations[stock.id]
quantity = stock.available_quantity - reserved_quantity
@@ -261,31 +267,37 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
quantity = max(0, quantity)
variant_id = stock.product_variant_id
warehouse_id = stock.warehouse_id
+ available_quantity_by_warehouse_id[warehouse_id] += quantity
if shipping_zone_ids := warehouse_shipping_zones_map[warehouse_id]:
for shipping_zone_id in shipping_zone_ids:
- quantity_by_shipping_zone_by_variant[variant_id][
+ warehouse_ids_by_shipping_zone_by_variant[variant_id][
shipping_zone_id
- ] += quantity
+ ].append(warehouse_id)
else:
cc_option = cc_warehouses_in_bulk[warehouse_id].click_and_collect_option
# every stock of a collection point warehouse should treat as a magic
# single-warehouse shipping zone
- quantity_by_shipping_zone_by_variant[variant_id][
+ warehouse_ids_by_shipping_zone_by_variant[variant_id][warehouse_id] = [
warehouse_id
- ] = quantity
+ ]
# in case of global warehouses the quantity available will be the sum
# of the available quantity for that variant from all stocks,
# so we need to keep information for which variant there is a warehouse
# with the global stock
if cc_option == WarehouseClickAndCollectOption.ALL_WAREHOUSES:
variants_with_global_cc_warehouses.append(variant_id)
- return quantity_by_shipping_zone_by_variant, variants_with_global_cc_warehouses
+ return (
+ warehouse_ids_by_shipping_zone_by_variant,
+ variants_with_global_cc_warehouses,
+ available_quantity_by_warehouse_id,
+ )
def prepare_quantity_map(
self,
country_code,
- quantity_by_shipping_zone_by_product_variant,
+ warehouse_ids_by_shipping_zone_by_variant,
variants_with_global_cc_warehouses,
+ available_quantity_by_warehouse_id,
):
"""Prepare the variant id to quantity map.
@@ -303,16 +315,31 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
quantity_map: DefaultDict[int, int] = defaultdict(int)
for (
variant_id,
- quantity_by_shipping_zone,
- ) in quantity_by_shipping_zone_by_product_variant.items():
- quantity_values = quantity_by_shipping_zone.values()
+ warehouse_ids_shipping_zone,
+ ) in warehouse_ids_by_shipping_zone_by_variant.items():
if country_code or variant_id in variants_with_global_cc_warehouses:
+ used_warehouse_ids = []
+ for warehouse_ids in warehouse_ids_shipping_zone.values():
+ used_warehouse_ids.extend(warehouse_ids)
+ used_warehouse_ids = set(used_warehouse_ids)
# When country code is known or the global collection point warehouse
# for this variant exists, return the sum of quantities from all
# shipping zones supporting given country.
- quantity_map[variant_id] = sum(quantity_values)
+ quantity = 0
+ for warehouse_id in used_warehouse_ids:
+ quantity += available_quantity_by_warehouse_id[warehouse_id]
+ quantity_map[variant_id] = quantity
else:
# When country code is unknown, return the highest known quantity.
+ quantity_values = []
+ for (
+ warehouse_ids_per_shipping_zones
+ ) in warehouse_ids_shipping_zone.values():
+ quantity = 0
+ for warehouse_id in warehouse_ids_per_shipping_zones:
+ quantity += available_quantity_by_warehouse_id[warehouse_id]
+ quantity_values.append(quantity)
+
quantity_map[variant_id] = max(quantity_values)
return quantity_map