Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix product availability (#11355)
Iga Karbowiak32bbfb8851b9
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.pyindex daa43a7f82..194a62c5a0 100644--- a/saleor/graphql/product/tests/queries/test_product_query.py+++ b/saleor/graphql/product/tests/queries/test_product_query.py@@ -11,10 +11,14 @@ from measurement.measures import Weightfrom .....attribute.models import AttributeValuefrom .....attribute.utils import associate_attribute_values_to_instancefrom .....core.units import WeightUnits-from .....product.models import ProductChannelListing, ProductVariantChannelListing+from .....product.models import (+ Product,+ ProductChannelListing,+ ProductVariantChannelListing,+)from .....tests.utils import dummy_editorjsfrom .....thumbnail.models import Thumbnail-from .....warehouse.models import Stock+from .....warehouse.models import Allocation, Stockfrom ....core.enums import ThumbnailFormatEnumfrom ....tests.utils import get_graphql_content, get_graphql_content_from_response@@ -2251,3 +2255,103 @@ def test_product_attribute_field_filtering_not_found(# thencontent = get_graphql_content(response)assert content["data"]["product"]["attribute"] is None+++QUERY_PRODUCTS_AVAILABILITY = """+ query ($channel:String){+ products(first: 10, channel: $channel) {+ totalCount+ edges {+ node {+ id+ name+ isAvailable+ variants {+ quantityAvailable+ stocks {+ quantity+ }+ }+ }+ }+ }+ }+"""+++def test_fetch_all_products_with_availability_data(+ staff_api_client, permission_manage_products, product_list, channel_USD, order_line+):+ # given+ product_1, product_2, product_3 = product_list+ allocations = []++ product_1_qty = 0+ product_1_qty_allocated = 1+ product_1_stock = product_1.variants.first().stocks.first()+ product_1_stock.quantity = product_1_qty+ product_1_stock.save(update_fields=["quantity"])+ allocations.append(+ Allocation(+ order_line=order_line,+ stock=product_1_stock,+ quantity_allocated=product_1_qty_allocated,+ )+ )++ product_2_qty = 15+ product_2_qty_allocated = 2+ product_2_stock = product_2.variants.first().stocks.first()+ product_2_stock.quantity = product_2_qty+ product_2_stock.save(update_fields=["quantity"])+ allocations.append(+ Allocation(+ order_line=order_line,+ stock=product_2_stock,+ quantity_allocated=product_2_qty_allocated,+ )+ )++ product_3_qty = 10+ product_3_qty_allocated = 0+ product_3_stock = product_3.variants.first().stocks.first()+ product_3_stock.quantity = product_3_qty+ product_3_stock.save(update_fields=["quantity"])++ Allocation.objects.bulk_create(allocations)++ variables = {"channel": channel_USD.slug}++ # when+ response = staff_api_client.post_graphql(+ QUERY_PRODUCTS_AVAILABILITY,+ variables,+ permissions=(permission_manage_products,),+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ num_products = Product.objects.count()+ assert content["data"]["products"]["totalCount"] == num_products+ product_data = content["data"]["products"]["edges"]+ assert len(product_data) == num_products+ for product, quantity, quantity_allocated in zip(+ product_list,+ [product_1_qty, product_2_qty, product_3_qty],+ [product_1_qty_allocated, product_2_qty_allocated, product_3_qty_allocated],+ ):+ data = {+ "node": {+ "id": graphene.Node.to_global_id("Product", product.id),+ "name": product.name,+ "isAvailable": quantity > 0,+ "variants": [+ {+ "quantityAvailable": max(quantity - quantity_allocated, 0),+ "stocks": [{"quantity": quantity}],+ }+ ],+ }+ }+ assert data in product_datadiff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex ae14074d34..9c1d7082db 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -117,7 +117,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader((warehouse_ids_by_shipping_zone_by_variant,variants_with_global_cc_warehouses,- available_quantity_by_warehouse_id,+ available_quantity_by_warehouse_id_and_variant_id,) = self.prepare_warehouse_ids_by_shipping_zone_and_variant_map(stocks, stocks_reservations, warehouse_shipping_zones_map, cc_warehouses)@@ -126,7 +126,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(country_code,warehouse_ids_by_shipping_zone_by_variant,variants_with_global_cc_warehouses,- available_quantity_by_warehouse_id,+ available_quantity_by_warehouse_id_and_variant_id,)# Return the quantities after capping them at the maximum quantity allowed in@@ -257,7 +257,9 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(int, DefaultDict[int, List[UUID]]] = defaultdict(lambda: defaultdict(list))variants_with_global_cc_warehouses = []- available_quantity_by_warehouse_id: DefaultDict[UUID, int] = defaultdict(int)+ available_quantity_by_warehouse_id_and_variant_id: DefaultDict[+ UUID, dict(int, int)+ ] = defaultdict(lambda: defaultdict(int))for stock in stocks:reserved_quantity = stocks_reservations[stock.id]quantity = stock.available_quantity - reserved_quantity@@ -267,7 +269,9 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(quantity = max(0, quantity)variant_id = stock.product_variant_idwarehouse_id = stock.warehouse_id- available_quantity_by_warehouse_id[warehouse_id] += quantity+ available_quantity_by_warehouse_id_and_variant_id[warehouse_id][+ variant_id+ ] += quantityif shipping_zone_ids := warehouse_shipping_zones_map[warehouse_id]:for shipping_zone_id in shipping_zone_ids:warehouse_ids_by_shipping_zone_by_variant[variant_id][@@ -289,7 +293,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(return (warehouse_ids_by_shipping_zone_by_variant,variants_with_global_cc_warehouses,- available_quantity_by_warehouse_id,+ available_quantity_by_warehouse_id_and_variant_id,)def prepare_quantity_map(@@ -297,7 +301,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(country_code,warehouse_ids_by_shipping_zone_by_variant,variants_with_global_cc_warehouses,- available_quantity_by_warehouse_id,+ available_quantity_by_warehouse_id_and_variant_id,):"""Prepare the variant id to quantity map.@@ -327,7 +331,9 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(# shipping zones supporting given country.quantity = 0for warehouse_id in used_warehouse_ids:- quantity += available_quantity_by_warehouse_id[warehouse_id]+ quantity += available_quantity_by_warehouse_id_and_variant_id[+ warehouse_id+ ][variant_id]quantity_map[variant_id] = quantityelse:# When country code is unknown, return the highest known quantity.@@ -337,7 +343,9 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader() in warehouse_ids_shipping_zone.values():quantity = 0for warehouse_id in warehouse_ids_per_shipping_zones:- quantity += available_quantity_by_warehouse_id[warehouse_id]+ quantity += available_quantity_by_warehouse_id_and_variant_id[+ warehouse_id+ ][variant_id]quantity_values.append(quantity)quantity_map[variant_id] = max(quantity_values)