Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Checkout lines add performance (#7536)
Tomasz Szymańskia8fbcf64c8a9
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 8b0cad5025..d0bc0c2eda 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -126,16 +126,20 @@ def calculate_checkout_quantity(lines: Iterable["CheckoutLineInfo"]):return sum([line_info.line.quantity for line_info in lines])-def add_variants_to_checkout(checkout, variants, quantities, channel_slug):+def add_variants_to_checkout(+ checkout, variants, quantities, channel_slug, skip_stock_check=False+):"""Add variants to checkout.- Suitable for new checkouts as it always creates new checkout lines without checking- if there are any existing ones already.+ If a variant is not placed in checkout, a new checkout line will be created.+ Otherwise, its quantity will be replaced (if greater than 0).+ If quantity is set to 0, checkout line will be deleted."""# check quantitiescountry_code = checkout.get_country()- check_stock_quantity_bulk(variants, country_code, quantities, channel_slug)+ if not skip_stock_check:+ check_stock_quantity_bulk(variants, country_code, quantities, channel_slug)channel_listings = product_models.ProductChannelListing.objects.filter(channel_id=checkout.channel.id,@@ -149,13 +153,28 @@ def add_variants_to_checkout(checkout, variants, quantities, channel_slug):if not product_channel_listing or not product_channel_listing.is_published:raise ProductNotPublished()- # create checkout lines- lines = []+ variant_ids_in_lines = {line.variant_id: line for line in checkout.lines.all()}+ to_create = []+ to_update = []+ to_delete = []for variant, quantity in zip(variants, quantities):- lines.append(- CheckoutLine(checkout=checkout, variant=variant, quantity=quantity)- )- checkout.lines.bulk_create(lines)+ if variant.pk in variant_ids_in_lines:+ line = variant_ids_in_lines[variant.pk]+ if quantity > 0:+ line.quantity = quantity+ to_update.append(line)+ else:+ to_delete.append(line)+ else:+ to_create.append(+ CheckoutLine(checkout=checkout, variant=variant, quantity=quantity)+ )+ if to_delete:+ CheckoutLine.objects.filter(pk__in=[line.pk for line in to_delete]).delete()+ if to_update:+ CheckoutLine.objects.bulk_update(to_update, ["quantity"])+ if to_create:+ CheckoutLine.objects.bulk_create(to_create)return checkoutdiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 694b0e6ca3..644d184cc5 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -19,7 +19,6 @@ from ...checkout.fetch import ()from ...checkout.utils import (add_promo_code_to_checkout,- add_variant_to_checkout,add_variants_to_checkout,calculate_checkout_quantity,change_billing_address_in_checkout,@@ -443,10 +442,11 @@ class CheckoutLinesAdd(BaseMutation):@classmethoddef clean_input(- cls, checkout, variants, quantities, checkout_info, manager, discounts, replace+ cls, checkout, variants, quantities, checkout_info, manager, discounts):+ channel_slug = checkout_info.channel.slugcls.validate_checkout_lines(- variants, quantities, checkout.get_country(), checkout_info.channel.slug+ variants, quantities, checkout.get_country(), channel_slug)variants_db_ids = {variant.id for variant in variants}validate_variants_available_for_purchase(variants_db_ids, checkout.channel_id)@@ -457,19 +457,19 @@ class CheckoutLinesAdd(BaseMutation):)if variants and quantities:- for variant, quantity in zip(variants, quantities):- try:- checkout = add_variant_to_checkout(- checkout_info, variant, quantity, replace=replace- )- except InsufficientStock as exc:- error = prepare_insufficient_stock_checkout_validation_error(exc)- raise ValidationError({"lines": error})- except ProductNotPublished as exc:- raise ValidationError(- "Can't add unpublished product.",- code=exc.code,- )+ try:+ checkout = add_variants_to_checkout(+ checkout,+ variants,+ quantities,+ channel_slug,+ skip_stock_check=True, # already checked by validate_checkout_lines+ )+ except ProductNotPublished as exc:+ raise ValidationError(+ "Can't add unpublished product.",+ code=exc.code,+ )lines = fetch_checkout_lines(checkout)checkout_info.valid_shipping_methods = (@@ -479,9 +479,7 @@ class CheckoutLinesAdd(BaseMutation):)@classmethod- def perform_mutation(- cls, _root, info, lines, checkout_id=None, token=None, replace=False- ):+ def perform_mutation(cls, _root, info, lines, checkout_id=None, token=None):# DEPRECATEDvalidate_one_of_args_is_in_mutation(CheckoutErrorCode, "checkout_id", checkout_id, "token", token@@ -504,7 +502,7 @@ class CheckoutLinesAdd(BaseMutation):checkout_info = fetch_checkout_info(checkout, [], discounts, manager)cls.clean_input(- checkout, variants, quantities, checkout_info, manager, discounts, replace+ checkout, variants, quantities, checkout_info, manager, discounts)lines = fetch_checkout_lines(checkout)@@ -538,9 +536,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):@classmethoddef perform_mutation(cls, root, info, lines, checkout_id=None, token=None):- return super().perform_mutation(- root, info, lines, checkout_id, token, replace=True- )+ return super().perform_mutation(root, info, lines, checkout_id, token)class CheckoutLineDelete(BaseMutation):diff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.pyindex 0409b3a70b..2477f1c20f 100644--- a/saleor/graphql/checkout/tests/test_checkout_lines.py+++ b/saleor/graphql/checkout/tests/test_checkout_lines.py@@ -97,6 +97,25 @@ def test_checkout_lines_add_with_unavailable_variant(assert errors[0]["variants"] == [variant_id]+def test_checkout_lines_add_with_insufficient_stock(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 49}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"++def test_checkout_lines_add_with_zero_quantity(user_api_client, checkout_with_item, stock):