Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix duplicate checkout line created by concurrent adds of the same variant (#19889) (#19891)

Marcin Wcisło3d55246dee47
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 526c5895e0..0e07a3d5e2 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,5 +1,6 @@
"""Checkout-related utility functions."""
+from collections import defaultdict
from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
@@ -223,6 +224,8 @@ def add_variants_to_checkout(
lines_by_id = {str(line.pk): line for line in checkout_lines}
variants_map = {str(variant.pk): variant for variant in variants}
+ _match_lines_data_to_locked_lines(checkout_lines_data, checkout_lines)
+
new_variant_ids = set()
non_existing_line_ids = set()
for line_data in checkout_lines_data:
@@ -303,6 +306,28 @@ def _get_line_if_exist(line_data, lines_by_ids):
return None
+def _match_lines_data_to_locked_lines(checkout_lines_data, checkout_lines):
+ """Point input lines at the lines that exist now that the checkout is locked.
+
+ The input lines are resolved against the checkout lines before the checkout
+ row lock is taken, so a concurrent request may have created a line for the
+ same variant in the meantime. Without this step both requests would create
+ their own line for the variant instead of merging into one.
+ """
+ lines_by_variant_id: dict[str, list[CheckoutLine]] = defaultdict(list)
+ for line in checkout_lines:
+ lines_by_variant_id[str(line.variant_id)].append(line)
+
+ for line_data in checkout_lines_data:
+ if line_data.line_id or line_data.force_new_line or not line_data.variant_id:
+ continue
+ matching_lines = lines_by_variant_id[str(line_data.variant_id)]
+ # When the variant is already in multiple lines a new line is created,
+ # which mirrors the resolution done before the lock was taken.
+ if len(matching_lines) == 1:
+ line_data.line_id = str(matching_lines[0].pk)
+
+
def _append_line_to_update(to_update, to_delete, line_data, replace, line):
if line_data.metadata_list:
line.store_value_in_metadata(
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 1f98f668c6..f9b80f9bc1 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -58,6 +58,7 @@ class CheckoutLineData:
custom_price_reason: str | None = None
custom_price_reason_to_update: bool = False
metadata_list: list = field(default_factory=list)
+ force_new_line: bool = False
def mark_checkout_deliveries_as_stale_if_needed(
@@ -322,7 +323,9 @@ def group_lines_input_on_add(
if force_new_line:
line_data = CheckoutLineData(
- variant_id=variant_db_id, metadata_list=metadata_list_from_input
+ variant_id=variant_db_id,
+ metadata_list=metadata_list_from_input,
+ force_new_line=True,
)
grouped_checkout_lines_data.append(line_data)
else:
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index a61da03f3d..6bc1885be1 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -2317,3 +2317,39 @@ def test_checkout_lines_add_checkout_removed_before_adding_variants_to_checkout(
data["errors"][0]["message"]
== f"{MISSING_NODE_ERROR_MESSAGE_PREFIX} {checkout_global_id}"
)
+
+
+def test_concurrent_add_of_same_variant_merges_into_single_line(
+ user_api_client, checkout, stock
+):
+ # given
+ variant = stock.product_variant
+ quantity = 2
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {
+ "variantId": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "quantity": quantity,
+ }
+ ],
+ }
+ assert checkout.lines.exists() is False
+
+ def add_same_variant_in_parallel_request(*args, **kwargs):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ assert get_graphql_content(response)["data"]["checkoutLinesAdd"]["errors"] == []
+
+ # when
+ with race_condition.RunBefore(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.add_variants_to_checkout",
+ add_same_variant_in_parallel_request,
+ ):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["checkoutLinesAdd"]["errors"] == []
+ line = checkout.lines.get()
+ assert line.variant_id == variant.pk
+ assert line.quantity == quantity * 2
diff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.py
index 1cf2a8f73a..7629784b82 100644
--- a/saleor/graphql/checkout/tests/mutations/test_utils.py
+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py
@@ -101,6 +101,7 @@ def test_group_on_add_when_same_variants_in_multiple_lines_and_force_new_line():
quantity_to_update=True,
custom_price=None,
custom_price_to_update=False,
+ force_new_line=True,
),
CheckoutLineData(
variant_id="1",