Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove repeated shipping API calls from checkout lines mutations (#8744)
Rafał Pitoń3d8387eb159f
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 1facff5f87..b0a9e3d052 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -239,61 +239,96 @@ def fetch_checkout_info(lines: Iterable[CheckoutLineInfo],discounts: Iterable["DiscountInfo"],manager: "PluginsManager",+ *,+ # Ugly hack to disable fetching shipping methods if they aren't needed+ # Preventing multiple redundant and potentially costful API calls in+ # checkout lines add/update/delete mutations+ fetch_shipping_methods: bool = True,) -> CheckoutInfo:"""Fetch checkout as CheckoutInfo object."""+ checkout_info = CheckoutInfo(+ checkout=checkout,+ user=checkout.user,+ channel=checkout.channel,+ billing_address=checkout.billing_address,+ shipping_address=checkout.shipping_address,+ delivery_method_info=DeliveryMethodBase(),+ shipping_method_channel_listings=None,+ valid_shipping_methods=[],+ valid_pick_up_points=[],+ )- from .utils import get_external_shipping_id+ valid_pick_up_points = get_valid_collection_points_for_checkout_info(+ checkout.shipping_address, lines, checkout_info+ )+ checkout_info.valid_pick_up_points = valid_pick_up_points++ if fetch_shipping_methods:+ populate_checkout_info_shippings(checkout_info, lines, discounts, manager)++ return checkout_info- channel = checkout.channel- shipping_address = checkout.shipping_address- shipping_channel_listings = None+def populate_checkout_info_shippings(+ checkout_info: CheckoutInfo,+ lines: Iterable[CheckoutLineInfo],+ discounts: Iterable["DiscountInfo"],+ manager: "PluginsManager",+):+ from .utils import get_external_shipping_id++ checkout = checkout_info.checkout+ channel = checkout_info.channel+ shipping_address = checkout_info.shipping_addressshipping_method = checkout.shipping_method++ external_shipping_methods = (+ get_valid_external_shipping_method_list_for_checkout_info(+ checkout_info, shipping_address, lines, discounts, manager+ )+ )++ shipping_channel_listings = Noneif shipping_method:shipping_channel_listings = ShippingMethodChannelListing.objects.filter(shipping_method=shipping_method, channel=channel).first()+delivery_method: Optional[Union["ShippingMethodData", "Warehouse"]] = convert_to_shipping_method_data(shipping_method)else:delivery_method = checkout.collection_point+ checkout_info.shipping_method_channel_listings = shipping_channel_listings+if not delivery_method:external_shipping_method_id = get_external_shipping_id(checkout)- delivery_method = manager.get_shipping_method(- checkout=checkout,- channel_slug=channel.slug,- shipping_method_id=external_shipping_method_id,- )+ if external_shipping_method_id:+ external_shipping_methods_map = {+ external_shipping_method.id: external_shipping_method+ for external_shipping_method in external_shipping_methods+ }+ delivery_method = external_shipping_methods_map.get(+ external_shipping_method_id+ )- delivery_method_info = get_delivery_method_info(delivery_method, shipping_address)- checkout_info = CheckoutInfo(- checkout=checkout,- user=checkout.user,- channel=channel,- billing_address=checkout.billing_address,- shipping_address=shipping_address,- delivery_method_info=delivery_method_info,- shipping_method_channel_listings=shipping_channel_listings,- valid_shipping_methods=[],- valid_pick_up_points=[],- )+ if delivery_method:+ delivery_method_info = get_delivery_method_info(+ delivery_method, shipping_address+ )+ checkout_info.delivery_method_info = delivery_method_info- valid_shipping_methods: List[- "ShippingMethodData"- ] = get_valid_shipping_method_list_for_checkout_info(- checkout_info, shipping_address, lines, discounts, manager+ valid_shipping_methods: List["ShippingMethodData"] = list(+ itertools.chain(+ get_valid_local_shipping_method_list_for_checkout_info(+ checkout_info, shipping_address, lines, discounts, manager+ ),+ external_shipping_methods,+ ))- valid_pick_up_points = get_valid_collection_points_for_checkout_info(- shipping_address, lines, checkout_info- )checkout_info.valid_shipping_methods = valid_shipping_methods- checkout_info.valid_pick_up_points = valid_pick_up_points- checkout_info.delivery_method_info = delivery_method_info-- return checkout_infodef update_checkout_info_shipping_address(diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 003b45ffc8..f415fc0d39 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -19,6 +19,7 @@ from ...checkout.fetch import (fetch_checkout_lines,get_valid_collection_points_for_checkout_info,get_valid_shipping_method_list_for_checkout_info,+ populate_checkout_info_shippings,)from ...checkout.utils import (add_promo_code_to_checkout,@@ -583,11 +584,7 @@ class CheckoutLinesAdd(BaseMutation):)lines = fetch_checkout_lines(checkout)- checkout_info.valid_shipping_methods = (- get_valid_shipping_method_list_for_checkout_info(- checkout_info, checkout_info.shipping_address, lines, discounts, manager- )- )+ populate_checkout_info_shippings(checkout_info, lines, discounts, manager)checkout_info.valid_pick_up_points = (get_valid_collection_points_for_checkout_info(checkout_info.shipping_address, lines, checkout_info@@ -619,7 +616,13 @@ class CheckoutLinesAdd(BaseMutation):variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)input_quantities = group_quantity_by_variants(lines)- checkout_info = fetch_checkout_info(checkout, [], discounts, manager)+ checkout_info = fetch_checkout_info(+ checkout,+ [],+ discounts,+ manager,+ fetch_shipping_methods=False,+ )lines = fetch_checkout_lines(checkout)lines = cls.clean_input(@@ -634,17 +637,6 @@ class CheckoutLinesAdd(BaseMutation):replace,)- checkout_info.valid_shipping_methods = (- get_valid_shipping_method_list_for_checkout_info(- checkout_info, checkout_info.shipping_address, lines, discounts, manager- )- )- checkout_info.valid_pick_up_points = (- get_valid_collection_points_for_checkout_info(- checkout_info.shipping_address, lines, checkout_info- )- )-update_checkout_shipping_method_if_invalid(checkout_info, lines)recalculate_checkout_discount(manager, checkout_info, lines, info.context.discountsdiff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 0b32b6e21a..6afc17d4f4 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -8,7 +8,7 @@ from graphene import Nodefrom .....checkout import calculationsfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkout-from .....checkout.utils import add_variants_to_checkout+from .....checkout.utils import add_variants_to_checkout, set_external_shipping_idfrom .....plugins.manager import get_plugins_managerfrom .....product.models import ProductVariant, ProductVariantChannelListingfrom .....warehouse.models import Stock@@ -706,7 +706,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(60):+ with django_assert_num_queries(57):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"token": checkout.token,@@ -720,7 +720,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(60):+ with django_assert_num_queries(57):variables = {"token": checkout.token,"lines": [],@@ -761,7 +761,9 @@ MUTATION_CHECKOUT_LINES_ADD = (@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)+@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")def test_add_checkout_lines(+ mock_send_request,api_client,checkout_with_single_item,stock,@@ -769,7 +771,104 @@ def test_add_checkout_lines(product_with_single_variant,product_with_two_variants,count_queries,+ shipping_app,+ settings,):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ mock_json_response = [+ {+ "id": "abcd",+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ variables = {+ "checkoutId": Node.to_global_id("Checkout", checkout_with_single_item.pk),+ "lines": [+ {+ "quantity": 1,+ "variantId": Node.to_global_id(+ "ProductVariant", stock.product_variant.pk+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_default_variant.variants.first().pk,+ ),+ },+ {+ "quantity": 10,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_single_variant.variants.first().pk,+ ),+ },+ {+ "quantity": 3,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_two_variants.variants.first().pk,+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_two_variants.variants.last().pk,+ ),+ },+ ],+ }+ response = get_graphql_content(+ api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ )+ assert not response["data"]["checkoutLinesAdd"]["errors"]+ assert mock_send_request.call_count == 1++[email protected]_queries(autouse=False)+@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_add_checkout_lines_with_external_shipping(+ mock_send_request,+ api_client,+ checkout_with_single_item,+ address,+ stock,+ product_with_default_variant,+ product_with_single_variant,+ product_with_two_variants,+ count_queries,+ shipping_app,+ settings,+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ external_shipping_method_id = Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ checkout_with_single_item.shipping_address = address+ set_external_shipping_id(checkout_with_single_item, external_shipping_method_id)+ checkout_with_single_item.save()+variables = {"checkoutId": Node.to_global_id("Checkout", checkout_with_single_item.pk),"lines": [@@ -813,6 +912,10 @@ def test_add_checkout_lines(api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables))assert not response["data"]["checkoutLinesAdd"]["errors"]+ # Two API calls:+ # - mutate() logic+ # - dataloader for lines totalPrice+ assert mock_send_request.call_count == 2@pytest.mark.django_db@@ -859,7 +962,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(59):+ with django_assert_num_queries(56):variables = {"checkoutId": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -872,7 +975,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(59):+ with django_assert_num_queries(56):variables = {"checkoutId": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,