Skip to content

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

Fix quantity available for stocks with cc warehouses (#10343)

Iga Karbowiakfd5a3b24bcb9
diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.py
index 57fd618126..9dc169a9b3 100644
--- a/saleor/graphql/product/tests/test_variant_availability.py
+++ b/saleor/graphql/product/tests/test_variant_availability.py
@@ -8,7 +8,8 @@ from django_countries import countries
from ....channel.utils import DEPRECATION_WARNING_MESSAGE
from ....shipping.models import ShippingZone
-from ....warehouse.models import PreorderReservation, Reservation
+from ....warehouse import WarehouseClickAndCollectOption
+from ....warehouse.models import PreorderReservation, Reservation, Stock
from ...tests.utils import get_graphql_content
COUNTRY_CODE = "US"
@@ -51,6 +52,95 @@ def test_variant_quantity_available_without_country_code_or_channel(
)
+def test_variant_quantity_available_without_country_code_stock_only_in_cc_warehouse(
+ api_client, variant, channel_USD, warehouse_for_cc
+):
+ # given
+ quantity = 4
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=quantity
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_QUANTITY_AVAILABLE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["quantityAvailable"] == quantity
+
+
+def test_variant_quantity_available_without_country_code_local_cc_warehouse(
+ api_client, variant, channel_USD, warehouse_for_cc, warehouse
+):
+ # given
+ quantity_cc = 7
+ # stock for collection point warehouse
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=quantity_cc
+ )
+
+ quantity = 5
+ # stock for standard warehouse
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=quantity
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_QUANTITY_AVAILABLE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["quantityAvailable"] == quantity_cc
+
+
+def test_variant_quantity_available_without_country_code_global_cc_warehouse(
+ api_client, variant, channel_USD, warehouse_for_cc, warehouse
+):
+ # given
+ quantity_cc = 4
+
+ warehouse_for_cc.click_and_collect_option = (
+ WarehouseClickAndCollectOption.ALL_WAREHOUSES
+ )
+ warehouse_for_cc.save(update_fields=["click_and_collect_option"])
+
+ # stock for collection point warehouse
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=quantity_cc
+ )
+
+ quantity = 5
+ # stock for standard warehouse
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=quantity
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_QUANTITY_AVAILABLE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["quantityAvailable"] == quantity + quantity_cc
+
+
def test_variant_quantity_available_when_one_stock_is_exceeded(
api_client, variant_with_many_stocks, channel_USD
):
@@ -160,6 +250,115 @@ def test_variant_quantity_available_with_null_as_country_code(
assert variant_data["byAddress"] == 7
+def test_variant_quantity_available_with_country_code_and_cc_warehouse_without_zone(
+ api_client,
+ variant,
+ channel_USD,
+ warehouse_for_cc,
+ warehouse,
+):
+ """Ensure the quantity from the collection point without shipping zone is not
+ returned when the country code is given."""
+ # given
+ quantity_cc = 7
+ # stock for local collection point warehouse
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=quantity_cc
+ )
+
+ quantity = 5
+ # stock for standard warehouse
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=quantity
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ "address": {"country": COUNTRY_CODE},
+ "country": COUNTRY_CODE,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["byAddress"] == quantity
+ assert variant_data["deprecatedByCountry"] == quantity
+
+
+def test_variant_quantity_available_with_country_code_and_local_cc_warehouse_with_zone(
+ api_client, variant, channel_USD, warehouse_for_cc, warehouse, shipping_zone
+):
+ """Ensure the quantity from the local collection point without shipping zone
+ is returned."""
+ # given
+ quantity_cc = 7
+ # stock for local collection point warehouse
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=quantity_cc
+ )
+ warehouse_for_cc.shipping_zones.add(shipping_zone)
+
+ quantity = 5
+ # stock for standard warehouse
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=quantity
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ "address": {"country": COUNTRY_CODE},
+ "country": COUNTRY_CODE,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["byAddress"] == quantity_cc + quantity
+ assert variant_data["deprecatedByCountry"] == quantity + quantity_cc
+
+
+def test_variant_quantity_available_with_country_code_and_global_cc_warehouse(
+ api_client, variant, channel_USD, warehouse_for_cc, shipping_zone, warehouse
+):
+ # given
+ quantity_cc = 7
+ # stock for local collection point warehouse
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=quantity_cc
+ )
+ warehouse_for_cc.shipping_zones.add(shipping_zone)
+
+ quantity = 5
+ # stock for standard warehouse
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=quantity
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ "address": {"country": COUNTRY_CODE},
+ "country": COUNTRY_CODE,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["byAddress"] == quantity + quantity_cc
+ assert variant_data["deprecatedByCountry"] == quantity + quantity_cc
+
+
def test_variant_quantity_available_with_max(
api_client, variant_with_many_stocks, site_settings, channel_USD
):
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 1bbcb79265..35e355dffd 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -1034,7 +1034,6 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
has_required_permissions = has_one_of_permissions(
requestor, ALL_PRODUCTS_PERMISSIONS
)
- channel_slug = str(root.channel_slug)
def calculate_is_available(quantities):
for qty in quantities:
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 61196db708..4b46ba8a6a 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -76,13 +76,66 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
stocks = Stock.objects.using(self.database_connection_name).filter(
product_variant_id__in=variant_ids
)
+ additional_warehouse_filter = True if country_code or channel_slug else False
+
+ warehouse_shipping_zones = self.get_warehouse_shipping_zones(
+ country_code, channel_slug
+ )
+ cc_warehouses = self.get_click_and_collect_warehouses(
+ channel_slug, country_code
+ )
+
+ warehouse_shipping_zones_map = defaultdict(list)
+ for warehouse_shipping_zone in warehouse_shipping_zones:
+ warehouse_shipping_zones_map[warehouse_shipping_zone.warehouse_id].append(
+ warehouse_shipping_zone.shippingzone_id
+ )
+ if additional_warehouse_filter:
+ stocks = stocks.filter(
+ Q(warehouse_id__in=warehouse_shipping_zones_map.keys())
+ | Q(warehouse_id__in=cc_warehouses.values("id"))
+ )
+
+ stocks = stocks.annotate_available_quantity()
+
+ 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.
+ (
+ quantity_by_shipping_zone_by_variant,
+ variants_with_global_cc_warehouses,
+ ) = self.prepare_quantity_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,
+ variants_with_global_cc_warehouses,
+ )
+
+ # Return the quantities after capping them at the maximum quantity allowed in
+ # checkout. This prevent users from tracking the store's precise stock levels.
+ global_quantity_limit = (
+ self.context.site.settings.limit_quantity_per_checkout # type: ignore
+ )
+ return [
+ (
+ variant_id,
+ min(quantity_map[variant_id], global_quantity_limit or sys.maxsize),
+ )
+ for variant_id in variant_ids
+ ]
+
+ def get_warehouse_shipping_zones(self, country_code, channel_slug):
+ """Get the WarehouseShippingZone instances for a given channel and country."""
WarehouseShippingZone = Warehouse.shipping_zones.through # type: ignore
warehouse_shipping_zones = WarehouseShippingZone.objects.using(
self.database_connection_name
).all()
- additional_warehouse_filter = False
if country_code or channel_slug:
- additional_warehouse_filter = True
if country_code:
shipping_zones = (
ShippingZone.objects.using(self.database_connection_name)
@@ -94,6 +147,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
)
if channel_slug:
ShippingZoneChannel = Channel.shipping_zones.through # type: ignore
+ WarehouseChannel = Channel.warehouses.through # type: ignore
channels = (
Channel.objects.using(self.database_connection_name)
.filter(slug=channel_slug)
@@ -104,22 +158,53 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
.filter(Exists(channels.filter(pk=OuterRef("channel_id"))))
.values("shippingzone_id")
)
+ warehouse_channels = (
+ WarehouseChannel.objects.using(self.database_connection_name)
+ .filter(
+ Exists(channels.filter(pk=OuterRef("channel_id"))),
+ )
+ .values("warehouse_id")
+ )
warehouse_shipping_zones = warehouse_shipping_zones.filter(
Exists(
shipping_zone_channels.filter(
shippingzone_id=OuterRef("shippingzone_id")
)
- )
+ ),
+ Exists(
+ warehouse_channels.filter(warehouse_id=OuterRef("warehouse_id"))
+ ),
)
- warehouse_shipping_zones_map = defaultdict(list)
- for warehouse_shipping_zone in warehouse_shipping_zones:
- warehouse_shipping_zones_map[warehouse_shipping_zone.warehouse_id].append(
- warehouse_shipping_zone.shippingzone_id
+ return warehouse_shipping_zones
+
+ def get_click_and_collect_warehouses(self, channel_slug, country_code):
+ """Get the collection point warehouses for a given channel and country code."""
+ warehouses = Warehouse.objects.none()
+ if not country_code and channel_slug:
+ channels = (
+ Channel.objects.using(self.database_connection_name)
+ .filter(slug=channel_slug)
+ .values("pk")
)
- if additional_warehouse_filter:
- stocks = stocks.filter(warehouse_id__in=warehouse_shipping_zones_map.keys())
- stocks = stocks.annotate_available_quantity()
+ WarehouseChannel = Channel.warehouses.through # type: ignore
+ warehouse_channels = (
+ WarehouseChannel.objects.using(self.database_connection_name)
+ .filter(
+ Exists(channels.filter(pk=OuterRef("channel_id"))),
+ )
+ .values("warehouse_id")
+ )
+ warehouses = Warehouse.objects.filter(
+ Exists(warehouse_channels.filter(warehouse_id=OuterRef("id"))),
+ click_and_collect_option__in=[
+ WarehouseClickAndCollectOption.LOCAL_STOCK,
+ WarehouseClickAndCollectOption.ALL_WAREHOUSES,
+ ],
+ )
+ return warehouses
+ def prepare_stocks_reservations_map(self, variant_ids):
+ """Prepare stock id to quantity reserved map for provided variant ids."""
stocks_reservations = defaultdict(int)
if is_reservation_enabled(self.context.site.settings): # type: ignore
# Can't do second annotation on same queryset because it made
@@ -133,50 +218,89 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
)
for stock_id, quantity_reserved in reservations_qs:
stocks_reservations[stock_id] = quantity_reserved
-
- # 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.
- quantity_by_shipping_zone_by_product_variant: DefaultDict[
+ return stocks_reservations
+
+ def prepare_quantity_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:
+ {
+ variant_id: {
+ shipping_zone_id/warehouse_id: quantity
+ }
+ }
+
+ In case of the collection point warehouses the warehouse_id is used instead of
+ the shipping zone id. Every stock of the collection point warehouse is treated
+ 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))
+ variants_with_global_cc_warehouses = []
for stock in stocks:
reserved_quantity = stocks_reservations[stock.id]
quantity = max(0, stock.available_quantity - reserved_quantity)
variant_id = stock.product_variant_id
warehouse_id = stock.warehouse_id
- shipping_zone_ids = warehouse_shipping_zones_map[warehouse_id]
- for shipping_zone_id in shipping_zone_ids:
- quantity_by_shipping_zone_by_product_variant[variant_id][
- shipping_zone_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][
+ shipping_zone_id
+ ] += quantity
+ 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_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
+
+ def prepare_quantity_map(
+ self,
+ country_code,
+ quantity_by_shipping_zone_by_product_variant,
+ variants_with_global_cc_warehouses,
+ ):
+ """Prepare the variant id to quantity map.
+
+ When the country code is known, the available quantity is the sum of quantities
+ from all shipping zones supporting given country. When the country is not known
+ the highest known quantity is returned.
+
+ The local warehouses are treated as a magic single-warehouse shipping zone.
+ When the variant has any global collection point warehouse, the quantity is the
+ sum of the quantities from all shipping zones.
+ In case of global warehouses the available quantity of such collection point
+ is the sum of the available quantities from all stocks that passed the country
+ or channel conditions.
+ """
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()
- if country_code:
- # When country code is known, return the sum of quantities from all
+ if country_code or variant_id in variants_with_global_cc_warehouses:
+ # 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)
else:
# When country code is unknown, return the highest known quantity.
quantity_map[variant_id] = max(quantity_values)
- # Return the quantities after capping them at the maximum quantity allowed in
- # checkout. This prevent users from tracking the store's precise stock levels.
- global_quantity_limit = (
- self.context.site.settings.limit_quantity_per_checkout # type: ignore
- )
- return [
- (
- variant_id,
- min(quantity_map[variant_id], global_quantity_limit or sys.maxsize),
- )
- for variant_id in variant_ids
- ]
+ return quantity_map
class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(