Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Check lines quantity based on available warehouses for given channel
IKarbowiaka789165ee7f4
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex b96989cc59..1f640f79ca 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -15,6 +15,7 @@ from ...checkout.fetch import (CheckoutLineInfo,fetch_checkout_info,fetch_checkout_lines,+ get_valid_shipping_method_list_for_checkout_info,update_checkout_info_shipping_method,)from ...checkout.utils import (@@ -107,7 +108,7 @@ def update_checkout_shipping_method_if_invalid(checkout.save(update_fields=["shipping_method", "last_change"])-def check_lines_quantity(variants, quantities, country):+def check_lines_quantity(variants, quantities, country, channel_slug):"""Clean quantities and check if stock is sufficient for each checkout line."""for quantity in quantities:if quantity < 0:@@ -130,7 +131,7 @@ def check_lines_quantity(variants, quantities, country):})try:- check_stock_quantity_bulk(variants, country, quantities)+ check_stock_quantity_bulk(variants, country, quantities, channel_slug)except InsufficientStock as e:errors = [ValidationError(@@ -245,7 +246,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):@classmethoddef clean_checkout_lines(- cls, lines, country, channel_id+ cls, lines, country, channel) -> Tuple[List[product_models.ProductVariant], List[int]]:variant_ids = [line["variant_id"] for line in lines]variants = cls.get_nodes_or_error(@@ -258,9 +259,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):)quantities = [line["quantity"] for line in lines]- validate_variants_available_for_purchase(variants, channel_id)- validate_variants_available_in_channel(variants, channel_id)- check_lines_quantity(variants, quantities, country)+ validate_variants_available_for_purchase(variants, channel.id)+ validate_variants_available_in_channel(variants, channel.id)+ check_lines_quantity(variants, quantities, country, channel.slug)return variants, quantities@classmethod@@ -343,7 +344,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):(cleaned_input["variants"],cleaned_input["quantities"],- ) = cls.clean_checkout_lines(lines, country, cleaned_input["channel"].id)+ ) = cls.clean_checkout_lines(lines, country, cleaned_input["channel"])# Use authenticated user's email as default emailif user.is_authenticated:@@ -447,12 +448,18 @@ class CheckoutLinesAdd(BaseMutation):checkout = cls.get_node_or_error(info, checkout_id, only_type=Checkout, field="checkout_id")+ discounts = info.context.discounts+ manager = info.context.pluginsvariant_ids = [line.get("variant_id") for line in lines]variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)quantities = [line.get("quantity") for line in lines]- check_lines_quantity(variants, quantities, checkout.get_country())+ checkout_info = fetch_checkout_info(checkout, [], discounts, manager)++ check_lines_quantity(+ variants, quantities, checkout.get_country(), checkout_info.channel.slug+ )validate_variants_available_for_purchase(variants, checkout.channel_id)validate_variants_available_in_channel(variants, checkout.channel_id)@@ -471,10 +478,11 @@ class CheckoutLinesAdd(BaseMutation):code=exc.code,)- manager = info.context.pluginslines = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(- checkout, lines, info.context.discounts, manager+ checkout_info.valid_shipping_methods = (+ get_valid_shipping_method_list_for_checkout_info(+ checkout_info, checkout_info.shipping_address, lines, discounts, manager+ ))update_checkout_shipping_method_if_invalid(checkout_info, lines)@@ -629,7 +637,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):@classmethoddef process_checkout_lines(- cls, lines: Iterable["CheckoutLineInfo"], country: str+ cls, lines: Iterable["CheckoutLineInfo"], country: str, channel_slug: str) -> None:variant_ids = [line_info.variant.id for line_info in lines]variants = list(@@ -638,7 +646,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):).prefetch_related("product__product_type")) # FIXME: is this prefetch needed?quantities = [line_info.line.quantity for line_info in lines]- check_lines_quantity(variants, quantities, country)+ check_lines_quantity(variants, quantities, country, channel_slug)@classmethoddef perform_mutation(cls, _root, info, checkout_id, shipping_address):@@ -686,7 +694,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):# Resolve and process the lines, validating variants quantitiesif lines:- cls.process_checkout_lines(lines, country)+ cls.process_checkout_lines(lines, country, checkout_info.channel.slug)update_checkout_shipping_method_if_invalid(checkout_info, lines)diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex a210ac4399..3161b55707 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -569,6 +569,35 @@ def test_checkout_create_with_invalid_channel_slug(assert error["field"] == "channel"+def test_checkout_create_no_channel_shipping_zones(+ api_client, stock, graphql_address_data, channel_USD+):+ """Create checkout object using GraphQL API."""+ channel_USD.shipping_zones.clear()+ variant = stock.product_variant+ 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()+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ new_checkout = Checkout.objects.first()+ assert new_checkout is None+ errors = content["checkoutErrors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"++def test_checkout_create_multiple_warehouse(api_client, variant_with_many_stocks, graphql_address_data, channel_USD):@@ -1472,6 +1501,32 @@ def test_checkout_lines_add_with_unavailable_variant(assert errors[0]["variants"] == [variant_id]+def test_checkout_lines_add_no_channel_shipping_zones(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()+ line = checkout.lines.first()+ assert line.quantity == 3+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ variables = {+ "checkoutId": checkout_id,+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesAdd"]+ errors = data["checkoutErrors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"++def test_checkout_lines_add_with_unpublished_product(user_api_client, checkout_with_item, stock, channel_USD):@@ -1748,6 +1803,32 @@ def test_checkout_lines_update_with_unavailable_variant(assert errors[0]["variants"] == [variant_id]+def test_checkout_lines_update_channel_without_shipping_zones(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ variables = {+ "checkoutId": checkout_id,+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ errors = data["checkoutErrors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"++def test_create_checkout_with_unpublished_product(user_api_client, checkout_with_item, stock, channel_USD):@@ -2188,6 +2269,29 @@ def test_checkout_shipping_address_update_insufficient_stocks(assert errors[0]["field"] == "quantity"+def test_checkout_shipping_address_update_channel_without_shipping_zones(+ user_api_client,+ checkout_with_item,+ graphql_address_data,+):+ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()+ assert checkout.shipping_address is None+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ shipping_address = graphql_address_data+ variables = {"checkoutId": checkout_id, "shippingAddress": shipping_address}++ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutShippingAddressUpdate"]+ errors = data["checkoutErrors"]+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"++def test_checkout_shipping_address_with_invalid_phone_number_returns_error(user_api_client, checkout_with_item, graphql_address_data):diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 5f3682fe79..6fc72ef649 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -37,13 +37,13 @@ def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity:raise InsufficientStock([InsufficientStockData(variant=variant)])-def check_stock_quantity_bulk(variants, country_code, quantities):+def check_stock_quantity_bulk(variants, country_code, quantities, channel_slug=None):"""Validate if there is stock available for given variants in given country.:raises InsufficientStock: when there is not enough items in stock for a variant."""all_variants_stocks = (- Stock.objects.for_country(country_code)+ Stock.objects.for_country(country_code, channel_slug).filter(product_variant__in=variants).annotate_available_quantity())@@ -63,8 +63,7 @@ def check_stock_quantity_bulk(variants, country_code, quantities):variant=variant, available_quantity=available_quantity))-- if variant.track_inventory:+ elif variant.track_inventory:if quantity > available_quantity:insufficient_stocks.append(InsufficientStockData(