Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow adding an item to the cart when there is a stock only in cc warehouse (#10368)
Iga Karbowiak5d49802fd4dc
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex e16288f8c0..d43fb36c67 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -343,7 +343,7 @@ def _create_lines_for_order(quantities,checkout_info.channel.slug,global_quantity_limit=None,- collection_point_pk=checkout_info.delivery_method_info.warehouse_pk,+ delivery_method_info=checkout_info.delivery_method_info,additional_filter_lookup=additional_warehouse_lookup,existing_lines=lines,replace=True,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex f34a17f6e8..ea0cf3914e 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -73,6 +73,7 @@ class CheckoutLinesAdd(BaseMutation):checkout_lines_data,country,channel_slug,+ delivery_method_info,lines=None,):variants, quantities = get_variants_and_total_quantities(@@ -84,6 +85,7 @@ class CheckoutLinesAdd(BaseMutation):country,channel_slug,info.context.site.settings.limit_quantity_per_checkout,+ delivery_method_info=delivery_method_info,existing_lines=lines,check_reservations=is_reservation_enabled(info.context.site.settings),)@@ -109,6 +111,7 @@ class CheckoutLinesAdd(BaseMutation):checkout_lines_data,checkout.get_country(),channel_slug,+ checkout_info.delivery_method_info,lines=lines,)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex 5de36c3c69..aa1f354a22 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -96,6 +96,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):checkout_lines_data,country,channel_slug,+ delivery_method_info,lines=None,):variants, quantities = get_variants_and_total_quantities(@@ -108,6 +109,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):country,channel_slug,info.context.site.settings.limit_quantity_per_checkout,+ delivery_method_info=delivery_method_info,allow_zero_quantity=True,existing_lines=lines,replace=True,diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.pyindex b3f113d1d1..addbdfeac8 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py@@ -1,4 +1,4 @@-from typing import Iterable+from typing import TYPE_CHECKING, Iterableimport graphenefrom django.core.exceptions import ValidationError@@ -38,6 +38,9 @@ from .utils import (update_checkout_shipping_method_if_invalid,)+if TYPE_CHECKING:+ from ....checkout.fetch import DeliveryMethodBase+class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):checkout = graphene.Field(Checkout, description="An updated checkout.")@@ -82,6 +85,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):lines: Iterable["CheckoutLineInfo"],country: str,channel_slug: str,+ delivery_method_info: "DeliveryMethodBase",) -> None:variant_ids = [line_info.variant.id for line_info in lines]variants = list(@@ -96,6 +100,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):country,channel_slug,info.context.site.settings.limit_quantity_per_checkout,+ delivery_method_info=delivery_method_info,# Set replace=True to avoid existing_lines and quantities from# being counted twice by the check_stock_quantity_bulkreplace=True,@@ -161,7 +166,13 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):# Resolve and process the lines, validating variants quantitiesif lines:- cls.process_checkout_lines(info, lines, country, checkout_info.channel.slug)+ cls.process_checkout_lines(+ info,+ lines,+ country,+ checkout_info.channel.slug,+ checkout_info.delivery_method_info,+ )update_checkout_shipping_method_if_invalid(checkout_info, lines)diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 9630bdf9e1..cc0569b12e 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -124,6 +124,7 @@ def check_lines_quantity(country,channel_slug,global_quantity_limit,+ delivery_method_info=None,allow_zero_quantity=False,existing_lines=None,replace=False,@@ -164,6 +165,7 @@ def check_lines_quantity(quantities,channel_slug,global_quantity_limit,+ delivery_method_info=delivery_method_info,existing_lines=existing_lines,replace=replace,check_reservations=check_reservations,diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 696b1231f8..b50edb16d1 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -864,10 +864,11 @@ def test_add_checkout_lines_with_external_shipping(api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables))assert not response["data"]["checkoutLinesAdd"]["errors"]- # Two api calls:+ # Three api calls:# - post-mutate() logic used to validate currently selected method# - fetch_checkout_prices_if_expired - calculating all prices for checkout- assert mock_send_request.call_count == 2+ # - in check_stock_quantity_bulk to check if the shipping method is set+ assert mock_send_request.call_count == 3@pytest.mark.django_dbdiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.pyindex 072ef3bd4d..5c1db4856d 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py@@ -750,6 +750,62 @@ def test_checkout_create_no_email(api_client, stock, graphql_address_data, channassert new_checkout.shipping_address.city == shipping_address["city"].upper()+def test_checkout_create_stock_only_in_cc_warehouse(+ api_client, stock, graphql_address_data, channel_USD, warehouse_for_cc+):+ """Create checkout object using GraphQL API."""+ # given+ variant = stock.product_variant+ variant.stocks.all().delete()++ Stock.objects.create(+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ shipping_address = graphql_address_data+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id}],+ "email": test_email,+ "shippingAddress": shipping_address,+ }+ }+ assert not Checkout.objects.exists()++ # when+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)++ # then+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ new_checkout = Checkout.objects.first()+ assert new_checkout is not None+ checkout_data = content["checkout"]+ assert checkout_data["token"] == str(new_checkout.token)+ assert new_checkout.lines.count() == 1+ checkout_line = new_checkout.lines.first()+ assert checkout_line.variant == variant+ assert checkout_line.quantity == 1+ assert new_checkout.shipping_address is not None+ assert new_checkout.shipping_address.first_name == shipping_address["firstName"]+ assert new_checkout.shipping_address.last_name == shipping_address["lastName"]+ assert (+ new_checkout.shipping_address.street_address_1+ == shipping_address["streetAddress1"]+ )+ assert (+ new_checkout.shipping_address.street_address_2+ == shipping_address["streetAddress2"]+ )+ assert new_checkout.shipping_address.postal_code == shipping_address["postalCode"]+ assert new_checkout.shipping_address.country == shipping_address["country"]+ assert new_checkout.shipping_address.city == shipping_address["city"].upper()+ assert not Reservation.objects.exists()++def test_checkout_create_with_invalid_channel_slug(api_client, stock, graphql_address_data, channel_USD):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex 59f0aad08f..42a2181375 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -61,8 +61,10 @@ def test_checkout_lines_add(checkout_with_item,stock,):+ # givenvariant = stock.product_variantcheckout = checkout_with_item+line = checkout.lines.first()lines, _ = fetch_checkout_lines(checkout)assert calculate_checkout_quantity(lines) == 3@@ -74,7 +76,11 @@ def test_checkout_lines_add("lines": [{"variantId": variant_id, "quantity": 1}],"channelSlug": checkout.channel.slug,}++ # whenresponse = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["checkoutLinesAdd"]assert not data["errors"]@@ -94,6 +100,100 @@ def test_checkout_lines_add(assert mocked_invalidate_checkout_prices.call_count == 1+ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_add_only_stock_in_cc_warehouse(+ mocked_update_shipping_method, user_api_client, checkout_with_item, warehouse_for_cc+):+ """Ensure the line can be added to the checkout when the only available quantity+ is in a stock from the collection point warehouse without shipping zone assigned."""+ # given+ checkout = checkout_with_item++ line = checkout.lines.first()+ variant = line.variant+ variant.stocks.all().delete()++ Stock.objects.create(+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10+ )++ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ previous_last_change = checkout.last_change++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert len(lines) == 1+ line = lines[0].line+ assert line.variant == variant+ assert line.quantity == 4+ assert calculate_checkout_quantity(lines) == 4+ assert not Reservation.objects.exists()++ manager = get_plugins_manager()+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_add_only_stock_in_cc_warehouse_delivery_method_set(+ user_api_client, checkout_with_item, warehouse_for_cc, shipping_method+):+ """Ensure the insufficient error is raised when the only available quantity is in+ a stock from the collection point warehouse without shipping zone assigned+ and the checkout has shipping method set."""+ # given+ checkout = checkout_with_item++ line = checkout.lines.first()+ variant = line.variant+ variant.stocks.all().delete()++ # set stock for a collection point warehouse+ Stock.objects.create(+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10+ )++ checkout.shipping_method = shipping_method+ checkout.save(update_fields=["shipping_method"])++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert data["errors"][0]["field"] == "quantity"++def test_checkout_lines_add_with_reservations(site_settings_with_reservations, user_api_client, checkout_with_item, stock):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex f1c02e42bb..7ade758f66 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -259,6 +259,101 @@ def test_checkout_lines_update_block_when_variant_id_and_line_id_provided(assert data["errors"][0]["message"] == expected_message+ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_update_only_stock_in_cc_warehouse(+ mocked_update_shipping_method, user_api_client, checkout_with_item, warehouse_for_cc+):+ """Ensure the insufficient error is not raised when the only available quantity+ is in a stock from the collection point warehouse without shipping zone assigned."""+ # given+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant++ variant.stocks.all().delete()++ Stock.objects.create(+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10+ )++ assert line.quantity == 3+ previous_last_change = checkout.last_change++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert calculate_checkout_quantity(lines) == 1++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_update_only_stock_in_cc_warehouse_delivery_method_set(+ user_api_client, checkout_with_item, warehouse_for_cc, shipping_method+):+ """Ensure the insufficient error is raised when the only available quantity is in+ a stock from the collection point warehouse without shipping zone assigned+ and the checkout has shipping method set."""+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant = line.variant++ variant.stocks.all().delete()++ # set stock for a collection point warehouse+ Stock.objects.create(+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10+ )++ checkout.shipping_method = shipping_method+ checkout.save(update_fields=["shipping_method"])++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert data["errors"][0]["field"] == "quantity"++def test_checkout_lines_update_checkout_with_voucher(user_api_client, checkout_with_item, voucher_percentage):diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex f4120d2241..0759b43d23 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -3587,6 +3587,41 @@ def test_products_query_with_filter_stock_availability_channel_without_shipping_assert products[0]["node"]["id"] == product_id+def test_products_query_with_filter_stock_availability_only_stock_in_cc_warehouse(+ query_products_with_filter,+ user_api_client,+ product,+ order_line,+ channel_USD,+ warehouse_for_cc,+):+ # given+ variant = product.variants.first()+ variant.stocks.all().delete()++ Stock.objects.create(+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10+ )++ variables = {+ "filter": {"stockAvailability": "IN_STOCK"},+ "channel": channel_USD.slug,+ }++ # when+ response = user_api_client.post_graphql(query_products_with_filter, variables)++ # then+ content = get_graphql_content(response)++ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(+ "Product", product.id+ )++@pytest.mark.parametrize("quantity_input, warehouse_indexes, count, indexes_of_products_in_result",[diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 6c6b8e6b20..5f886403d6 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -16,6 +16,7 @@ from django.db.models import F, QuerySet, Sumfrom django.db.models.functions import Coalescefrom ..checkout.error_codes import CheckoutErrorCode+from ..checkout.fetch import DeliveryMethodBasefrom ..core.exceptions import InsufficientStock, InsufficientStockDatafrom ..product.models import ProductVariantChannelListingfrom .models import Reservation, Stock, StockQuerySet@@ -121,7 +122,7 @@ def check_stock_and_preorder_quantity_bulk(quantities: Iterable[int],channel_slug: str,global_quantity_limit: Optional[int],- collection_point_pk: Optional[str] = None,+ delivery_method_info: Optional["DeliveryMethodBase"] = None,additional_filter_lookup: Optional[Dict[str, Any]] = None,existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,replace: bool = False,@@ -145,7 +146,7 @@ def check_stock_and_preorder_quantity_bulk(stock_quantities,channel_slug,global_quantity_limit,- collection_point_pk,+ delivery_method_info,additional_filter_lookup,existing_lines,replace,@@ -213,7 +214,7 @@ def check_stock_quantity_bulk(quantities: Iterable[int],channel_slug: str,global_quantity_limit: Optional[int],- collection_point_pk: Optional[str] = None,+ delivery_method_info: Optional["DeliveryMethodBase"] = None,additional_filter_lookup: Optional[Dict[str, Any]] = None,existing_lines: Iterable["CheckoutLineInfo"] = None,replace=False,@@ -227,12 +228,23 @@ def check_stock_quantity_bulk(if additional_filter_lookup is not None:filter_lookup.update(additional_filter_lookup)+ # in case when the delivery method is not set yet, we should check the stock+ # quantity in standard warehouses available in a given channel and country, and+ # in the collection point warehouses for the channel+ include_cc_warehouses = (+ not delivery_method_info.delivery_method if delivery_method_info else True+ )# in case of click and collect order, we need to check local or global stock# regardless of the country code+ collection_point = (+ delivery_method_info.warehouse_pk if delivery_method_info else None+ )stocks = (Stock.objects.for_channel_and_click_and_collect(channel_slug)- if collection_point_pk- else Stock.objects.for_channel_and_country(channel_slug, country_code)+ if collection_point+ else Stock.objects.for_channel_and_country(+ channel_slug, country_code, include_cc_warehouses+ ))all_variants_stocks = stocks.filter(**filter_lookup).annotate_available_quantity()diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex d5c9e00baf..80584f5602 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -223,8 +223,19 @@ class StockQuerySet(models.QuerySet):)def for_channel_and_country(- self, channel_slug: str, country_code: Optional[str] = None+ self,+ channel_slug: str,+ country_code: Optional[str] = None,+ include_cc_warehouses: bool = False,):+ """Get stocks for given channel and country_code.++ The returned stocks, must be in warehouse that is available in provided channel+ and in the shipping zone that is available in the given channel and country.+ When the country_code is not provided or include_cc_warehouses is set to True,+ also the stocks from collection point warehouses allowed in given channel are+ returned.+ """ShippingZoneChannel = Channel.shipping_zones.through # type: ignoreWarehouseShippingZone = ShippingZone.warehouses.through # type: ignoreWarehouseChannel = Channel.warehouses.through # type: ignore@@ -234,7 +245,11 @@ class StockQuerySet(models.QuerySet):shipping_zone_channels = ShippingZoneChannel.objects.filter(Exists(channels.filter(pk=OuterRef("channel_id"))))+ warehouse_channels = WarehouseChannel.objects.filter(+ Exists(channels.filter(pk=OuterRef("channel_id")))+ ).values("warehouse_id")+ cc_warehouses = Warehouse.objects.none()if country_code:shipping_zones = ShippingZone.objects.filter(countries__contains=country_code@@ -242,13 +257,19 @@ class StockQuerySet(models.QuerySet):shipping_zone_channels = shipping_zone_channels.filter(Exists(shipping_zones.filter(pk=OuterRef("shippingzone_id"))))+ if not country_code or include_cc_warehouses:+ # when the country code is not provided we should also include+ # the collection point warehouses+ cc_warehouses = Warehouse.objects.filter(+ Exists(warehouse_channels.filter(warehouse_id=OuterRef("id"))),+ click_and_collect_option__in=[+ WarehouseClickAndCollectOption.LOCAL_STOCK,+ WarehouseClickAndCollectOption.ALL_WAREHOUSES,+ ],+ )shipping_zone_channels.values("shippingzone_id")- warehouse_channels = WarehouseChannel.objects.filter(- Exists(channels.filter(pk=OuterRef("channel_id")))- ).values("warehouse_id")-warehouse_shipping_zones = WarehouseShippingZone.objects.filter(Exists(shipping_zone_channels.filter(@@ -261,6 +282,7 @@ class StockQuerySet(models.QuerySet):Exists(warehouse_shipping_zones.filter(warehouse_id=OuterRef("warehouse_id")))+ | Exists(cc_warehouses.filter(id=OuterRef("warehouse_id"))))def get_variant_stocks_for_country(