Skip to content

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

Clear and prevent duplicated gift lines (#18610)

Iga Karbowiak3bf31ab2fefc
diff --git a/saleor/celeryconf.py b/saleor/celeryconf.py
index 66488044de..c837abe789 100644
--- a/saleor/celeryconf.py
+++ b/saleor/celeryconf.py
@@ -42,5 +42,12 @@ app.autodiscover_tasks(
],
related_name="saleor3_22",
)
+app.autodiscover_tasks(
+ packages=[
+ "saleor.checkout.migrations.tasks",
+ "saleor.order.migrations.tasks",
+ ],
+ related_name="saleor3_20",
+)
app.autodiscover_tasks(lambda: discover_plugins_modules(settings.PLUGINS))
app.autodiscover_tasks(related_name="search_tasks")
diff --git a/saleor/checkout/migrations/0077_checkout_idx_checkout_created_at.py b/saleor/checkout/migrations/0077_checkout_idx_checkout_created_at.py
new file mode 100644
index 0000000000..260db04df1
--- /dev/null
+++ b/saleor/checkout/migrations/0077_checkout_idx_checkout_created_at.py
@@ -0,0 +1,19 @@
+# Generated by Django 4.2.26 on 2025-12-08 11:22
+
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("checkout", "0076_checkout_discount_expiration"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="checkout",
+ index=models.Index(fields=["created_at"], name="idx_checkout_created_at"),
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0078_clean_duplicated_gift_lines.py b/saleor/checkout/migrations/0078_clean_duplicated_gift_lines.py
new file mode 100644
index 0000000000..cc7f511a95
--- /dev/null
+++ b/saleor/checkout/migrations/0078_clean_duplicated_gift_lines.py
@@ -0,0 +1,28 @@
+# Generated by Django 4.2.26 on 2025-12-02 11:13
+
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_20 import clean_duplicated_gift_lines_task
+
+
+def clean_duplicated_gift_lines(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ clean_duplicated_gift_lines_task.delay()
+
+ sender = registry.get_app_config("checkout")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0077_checkout_idx_checkout_created_at"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ clean_duplicated_gift_lines,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0082_merge_20251211_1339.py b/saleor/checkout/migrations/0082_merge_20251211_1339.py
new file mode 100644
index 0000000000..58aee9b2c1
--- /dev/null
+++ b/saleor/checkout/migrations/0082_merge_20251211_1339.py
@@ -0,0 +1,12 @@
+# Generated by Django 4.2.26 on 2025-12-11 13:39
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0078_clean_duplicated_gift_lines"),
+ ("checkout", "0081_merge_20251107_1134"),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/migrations/0086_merge_20251212_0956.py b/saleor/checkout/migrations/0086_merge_20251212_0956.py
new file mode 100644
index 0000000000..afe06ec4d0
--- /dev/null
+++ b/saleor/checkout/migrations/0086_merge_20251212_0956.py
@@ -0,0 +1,15 @@
+# Generated by Django 5.2.8 on 2025-12-12 08:56
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0082_merge_20251211_1339"),
+ (
+ "checkout",
+ "0085_checkout_delivery_methods_stale_at_checkoutdelivery_and_more",
+ ),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/migrations/tasks/saleor3_20.py b/saleor/checkout/migrations/tasks/saleor3_20.py
new file mode 100644
index 0000000000..2facf4862b
--- /dev/null
+++ b/saleor/checkout/migrations/tasks/saleor3_20.py
@@ -0,0 +1,50 @@
+from django.db.models import Exists, OuterRef
+
+from ....celeryconf import app
+from ....discount import DiscountType
+from ....discount.models import CheckoutLineDiscount
+from ...models import Checkout, CheckoutLine
+
+# Takes about 0.1 second to process
+DUPLICATED_LINES_CHECKOUT_BATCH_SIZE = 250
+
+
+def clean_duplicated_gift_lines_task(created_after=None):
+ extra_order_filter = {}
+ if created_after:
+ extra_order_filter["created_at__gt"] = created_after
+
+ # fetch gift line discounts to narrow down the filter on checkout lines
+ gift_line_discounts = CheckoutLineDiscount.objects.filter(
+ type=DiscountType.ORDER_PROMOTION, line__isnull=False
+ )
+ gift_lines = CheckoutLine.objects.filter(
+ Exists(gift_line_discounts.filter(line_id=OuterRef("id")))
+ )
+
+ checkout_data = list(
+ Checkout.objects.filter(Exists(gift_lines.filter(checkout_id=OuterRef("pk"))))
+ .order_by("created_at")
+ .filter(**extra_order_filter)
+ .values_list("pk", "created_at")[:DUPLICATED_LINES_CHECKOUT_BATCH_SIZE]
+ )
+
+ checkout_ids = [data[0] for data in checkout_data]
+ if not checkout_ids:
+ return
+
+ checkout_created_after = checkout_data[-1][1]
+ lines = CheckoutLine.objects.filter(
+ checkout_id__in=checkout_ids, is_gift=True
+ ).order_by("checkout_id", "id")
+ seen_checkouts = set()
+ lines_to_delete = []
+ for line in lines:
+ if line.checkout_id in seen_checkouts:
+ lines_to_delete.append(line.id)
+ else:
+ seen_checkouts.add(line.checkout_id)
+
+ CheckoutLine.objects.filter(id__in=lines_to_delete).delete()
+ clean_duplicated_gift_lines_task.delay(created_after=checkout_created_after)
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index b331c1668a..f97dbf667c 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -325,7 +325,8 @@ class Checkout(models.Model):
BTreeIndex(
fields=["last_automatic_completion_attempt"],
name="automaticcompletionattempt_idx",
- )
+ ),
+ models.Index(fields=["created_at"], name="idx_checkout_created_at"),
]
def __iter__(self):
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index dcc43d16fb..52e6a4461e 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -15,13 +15,19 @@ from prices import Money
from ...channel.models import Channel
from ...checkout.fetch import CheckoutLineInfo
-from ...checkout.lock_objects import checkout_lines_qs_select_for_update
+from ...checkout.lock_objects import (
+ checkout_lines_qs_select_for_update,
+ checkout_qs_select_for_update,
+)
from ...checkout.models import Checkout, CheckoutLine
from ...core.db.connection import allow_writer
from ...core.exceptions import InsufficientStock
from ...core.taxes import zero_money
from ...order.fetch import EditableOrderLineInfo
-from ...order.lock_objects import order_lines_qs_select_for_update
+from ...order.lock_objects import (
+ order_lines_qs_select_for_update,
+ order_qs_select_for_update,
+)
from ...order.models import Order
from ...product.models import (
Product,
@@ -429,6 +435,17 @@ def delete_gift_line(
lines_info.remove(gift_line_info) # type: ignore[arg-type]
+def _lock_order_or_checkout(
+ order_or_checkout: Checkout | Order,
+):
+ if isinstance(order_or_checkout, Checkout):
+ _checkout = (
+ checkout_qs_select_for_update().filter(pk=order_or_checkout.pk).first()
+ )
+ else:
+ _order = order_qs_select_for_update().filter(pk=order_or_checkout.pk).first()
+
+
def create_gift_line(
order_or_checkout: Checkout | Order,
gift_listing: "ProductVariantChannelListing",
@@ -437,9 +454,11 @@ def create_gift_line(
defaults = _get_defaults_for_gift_line(
order_or_checkout, gift_listing, line_discount_data
)
- line, created = order_or_checkout.lines.get_or_create(
- is_gift=True, defaults=defaults
- )
+ with transaction.atomic():
+ _lock_order_or_checkout(order_or_checkout)
+ line, created = order_or_checkout.lines.get_or_create(
+ is_gift=True, defaults=defaults
+ )
if not created:
fields_to_update = []
for field, value in defaults.items():
@@ -776,12 +795,18 @@ def _handle_order_promotion(
line_discount_data: DiscountInfo,
rule_info: VariantPromotionRuleInfo,
):
- discount_object, created = order_or_checkout.discounts.get_or_create(
- type=DiscountType.ORDER_PROMOTION,
- defaults=asdict(line_discount_data),
- )
+ with transaction.atomic():
+ # As we do not have the unique constraint on order/checkout discount model,
+ # we need to lock the order/checkout to avoid creating duplicate promotion
+ # discounts in concurrent requests
+ _lock_order_or_checkout(order_or_checkout)
+ discount_object, created = order_or_checkout.discounts.get_or_create(
+ type=DiscountType.ORDER_PROMOTION,
+ defaults=asdict(line_discount_data),
+ )
discount_amount = line_discount_data.amount_value
promotion_rule = cast(PromotionRule, line_discount_data.promotion_rule)
+
if not created:
fields_to_update: list[str] = []
update_promotion_discount(
@@ -813,6 +838,10 @@ def _handle_gift_reward(
else OrderLineDiscount
)
with transaction.atomic():
+ # As we do not have the unique constraint on checkout and order line for gift
+ # lines, so we need to lock the order/checkout to avoid creating duplicate
+ # gift lines
+ _lock_order_or_checkout(order_or_checkout)
line = create_gift_line(order_or_checkout, gift_listing, line_discount_data)
(
line_discount,
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index c3e917a52c..4e12420ec9 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -569,7 +569,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(102):
+ with django_assert_num_queries(105):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -1285,7 +1285,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(101):
+ with django_assert_num_queries(107):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1320,7 +1320,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(132):
+ with django_assert_num_queries(140):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/order/migrations/0198_clean_duplicated_gift_lines.py b/saleor/order/migrations/0198_clean_duplicated_gift_lines.py
new file mode 100644
index 0000000000..00493556f4
--- /dev/null
+++ b/saleor/order/migrations/0198_clean_duplicated_gift_lines.py
@@ -0,0 +1,28 @@
+# Generated by Django 4.2.26 on 2025-12-02 13:33
+
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_20 import clean_duplicated_gift_lines_task
+
+
+def clean_duplicated_gift_lines(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ clean_duplicated_gift_lines_task.delay()
+
+ sender = registry.get_app_config("checkout")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0197_fix_negative_total_net_for_orders_using_gift_cards"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ clean_duplicated_gift_lines,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/order/migrations/0207_merge_20251211_1339.py b/saleor/order/migrations/0207_merge_20251211_1339.py
new file mode 100644
index 0000000000..76799837a3
--- /dev/null
+++ b/saleor/order/migrations/0207_merge_20251211_1339.py
@@ -0,0 +1,12 @@
+# Generated by Django 4.2.26 on 2025-12-11 13:39
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0198_clean_duplicated_gift_lines"),
+ ("order", "0206_order_shipping_method_metadata_and_more"),
+ ]
+
+ operations = []
diff --git a/saleor/order/migrations/0219_merge_20251212_0955.py b/saleor/order/migrations/0219_merge_20251212_0955.py
new file mode 100644
index 0000000000..b51b259dc1
--- /dev/null
+++ b/saleor/order/migrations/0219_merge_20251212_0955.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.8 on 2025-12-12 08:55
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0207_merge_20251211_1339"),
+ ("order", "0218_merge_20251112_1035"),
+ ]
+
+ operations = []
diff --git a/saleor/order/migrations/tasks/saleor3_20.py b/saleor/order/migrations/tasks/saleor3_20.py
new file mode 100644
index 0000000000..4f82689c59
--- /dev/null
+++ b/saleor/order/migrations/tasks/saleor3_20.py
@@ -0,0 +1,46 @@
+from django.db.models import Exists, OuterRef
+
+from ....celeryconf import app
+from ...models import Order, OrderLine, OrderStatus
+
+# Takes about 0.1 second to process
+DUPLICATED_LINES_ORDER_BATCH_SIZE = 200
+
+
+def clean_duplicated_gift_lines_task(created_after=None):
+ extra_filter = {}
+ if created_after:
+ extra_filter["created_at__gt"] = created_after
+
+ order_data = list(
+ Order.objects.filter(
+ status=OrderStatus.DRAFT,
+ )
+ .filter(
+ Exists(
+ OrderLine.objects.filter(is_gift=True).filter(order_id=OuterRef("pk"))
+ )
+ )
+ .order_by("created_at")
+ .filter(**extra_filter)
+ .values_list("pk", "created_at")[:DUPLICATED_LINES_ORDER_BATCH_SIZE]
+ )
+ order_ids = [data[0] for data in order_data]
+ if not order_ids:
+ return
+
+ order_created_after = order_data[-1][1]
+ lines = OrderLine.objects.filter(order_id__in=order_ids, is_gift=True).order_by(
+ "order_id", "id"
+ )
+ seen_orders = set()
+ lines_to_delete = []
+ for line in lines:
+ if line.order_id in seen_orders:
+ lines_to_delete.append(line.id)
+ else:
+ seen_orders.add(line.order_id)
+
+ OrderLine.objects.filter(id__in=lines_to_delete).delete()
+ clean_duplicated_gift_lines_task.delay(created_after=order_created_after)