Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix shared adress instances (#18651)
Iga Karbowiakd3847fa5f518
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 5e52b73378..6a8e96f87e 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -1652,6 +1652,17 @@ def create_order_from_checkout(if delete_checkout:delete_checkouts([checkout_info.checkout.pk])checkout_info.checkout.pk = None+ else:+ checkout = checkout_info.checkout+ update_fields = []+ if checkout.shipping_address:+ checkout.shipping_address = checkout.shipping_address.get_copy()+ update_fields.append("shipping_address")+ if checkout.billing_address:+ checkout.billing_address = checkout.billing_address.get_copy()+ update_fields.append("billing_address")+ if update_fields:+ checkout.save(update_fields=update_fields)return orderexcept InsufficientStock:_complete_checkout_fail_handler(diff --git a/saleor/checkout/migrations/0083_fix_shared_address_instances.py b/saleor/checkout/migrations/0083_fix_shared_address_instances.pynew file mode 100644index 0000000000..0f62587cdd--- /dev/null+++ b/saleor/checkout/migrations/0083_fix_shared_address_instances.py@@ -0,0 +1,25 @@+# Generated by Django 4.2.26 on 2025-12-22 10:10++from django.apps import apps as registry+from django.db import migrations+from django.db.models.signals import post_migrate++from .tasks.saleor3_21 import fix_shared_address_instances_task+++def fix_shared_address_instances(apps, schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ fix_shared_address_instances_task.delay()++ sender = registry.get_app_config("order")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0082_merge_20251211_1339"),+ ]++ operations = [+ migrations.RunPython(fix_shared_address_instances, migrations.RunPython.noop),+ ]diff --git a/saleor/checkout/migrations/0087_merge_20251223_1336.py b/saleor/checkout/migrations/0087_merge_20251223_1336.pynew file mode 100644index 0000000000..babe9a33f8--- /dev/null+++ b/saleor/checkout/migrations/0087_merge_20251223_1336.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.8 on 2025-12-23 12:36++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0083_fix_shared_address_instances"),+ ("checkout", "0086_merge_20251212_0956"),+ ]++ operations = []diff --git a/saleor/checkout/migrations/tasks/saleor3_21.py b/saleor/checkout/migrations/tasks/saleor3_21.pynew file mode 100644index 0000000000..49bb6d8235--- /dev/null+++ b/saleor/checkout/migrations/tasks/saleor3_21.py@@ -0,0 +1,50 @@+from django.db.models import Exists, OuterRef++from ....account.models import Address+from ....celeryconf import app+from ....checkout.models import Checkout+from ....core.db.connection import allow_writer+from ....order.models import Order++# Takes about 0.5 second to process+BATCH_SIZE = 250+++BILLING_FIELD = "billing_address"+SHIPPING_FIELD = "shipping_address"+++@allow_writer()+def fix_shared_address_instances_task(field=BILLING_FIELD):+ """Fix shared address instances between checkouts and orders.++ First process billing addresses, then shipping addresses.+ """+ filter = {+ f"{field}_id__isnull": False,+ }+ checkouts = Checkout.objects.filter(+ Exists(Order.objects.filter(**{f"{field}_id": OuterRef(f"{field}_id")})),+ **filter,+ )[:BATCH_SIZE]++ if not checkouts:+ if field == BILLING_FIELD:+ fix_shared_address_instances_task.delay(field=SHIPPING_FIELD)+ return++ checkout_instances = []+ addresses_to_create = []+ for checkout in checkouts:+ address_data = getattr(checkout, field).as_data()+ addresses_to_create.append(Address(**address_data))+ checkout_instances.append(checkout)+ # address instances returned in the same order as in the provided list+ addresses = Address.objects.bulk_create(addresses_to_create)++ for checkout, address in zip(checkout_instances, addresses, strict=True):+ setattr(checkout, field, address)+ Checkout.objects.bulk_update(checkout_instances, [field])++ fix_shared_address_instances_task.delay(field=field)diff --git a/saleor/checkout/tests/test_migrations_tasks.py b/saleor/checkout/tests/test_migrations_tasks.pynew file mode 100644index 0000000000..0cf9d5eb96--- /dev/null+++ b/saleor/checkout/tests/test_migrations_tasks.py@@ -0,0 +1,157 @@+from unittest import mock++from ..migrations.tasks.saleor3_21 import (+ BILLING_FIELD,+ SHIPPING_FIELD,+ fix_shared_address_instances_task,+)+from ..models import Checkout+++def test_fix_shared_billing_addresses(checkouts_list, order, address, address_usa):+ # given+ checkout1 = checkouts_list[0]+ checkout2 = checkouts_list[1]+ checkout3 = checkouts_list[2]++ # these two share address with order+ checkout1.billing_address = address+ checkout2.billing_address = address+ new_checkout_address = address.get_copy()+ checkout1.shipping_address = new_checkout_address+ checkout2.shipping_address = new_checkout_address+ # this one has unique address+ checkout3.billing_address = address_usa+ Checkout.objects.bulk_update(+ [checkout1, checkout2, checkout3], ["billing_address", "shipping_address"]+ )++ order.billing_address = address+ new_order_address = address.get_copy()+ order.shipping_address = new_order_address+ order.save(update_fields=["billing_address", "shipping_address"])++ # when+ fix_shared_address_instances_task()++ # then+ for checkout in [checkout1, checkout2]:+ checkout.refresh_from_db()+ assert checkout.billing_address_id != address.id+ assert checkout.billing_address.as_data() == address.as_data()+ assert checkout.shipping_address_id == new_checkout_address.id++ checkout3.refresh_from_db()+ assert checkout3.billing_address_id == address_usa.id+++def test_fix_shared_shipping_addresses(checkouts_list, order, address, address_usa):+ # given+ checkout1 = checkouts_list[0]+ checkout2 = checkouts_list[1]+ checkout3 = checkouts_list[2]++ # these two share address with order+ checkout1.shipping_address = address+ checkout2.shipping_address = address+ new_checkout_address = address.get_copy()+ checkout1.billing_address = new_checkout_address+ checkout2.billing_address = new_checkout_address+ # this one has unique address+ checkout3.shipping_address = address_usa+ Checkout.objects.bulk_update(+ [checkout1, checkout2, checkout3], ["shipping_address", "billing_address"]+ )++ new_order_address = address.get_copy()+ order.billing_address = new_order_address+ order.shipping_address = address+ order.save(update_fields=["shipping_address", "billing_address"])++ # when+ fix_shared_address_instances_task(field=SHIPPING_FIELD)++ # then+ for checkout in [checkout1, checkout2]:+ checkout.refresh_from_db()+ assert checkout.shipping_address_id != address.id+ assert checkout.shipping_address.as_data() == address.as_data()+ assert checkout.billing_address_id == new_checkout_address.id++ checkout3.refresh_from_db()+ assert checkout3.shipping_address_id == address_usa.id+++def test_no_checkouts_with_shared_addresses(checkout, order, address):+ # given+ checkout.billing_address = address+ checkout.save(update_fields=["billing_address"])++ # address linked to order is different instance, but same data+ order_address = address.get_copy()+ order.billing_address = order_address+ order.save(update_fields=["billing_address"])++ assert checkout.billing_address_id != order.billing_address_id++ # when+ fix_shared_address_instances_task()++ # then+ checkout.refresh_from_db()+ assert checkout.billing_address_id == address.id+++ "saleor.checkout.migrations.tasks.saleor3_21.fix_shared_address_instances_task.delay"+)+def test_task_switches_fields(mock_delay, checkout, order, address):+ # given+ # only shared shipping address exists+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ order.shipping_address = address+ order.save(update_fields=["shipping_address"])++ # when+ # Trigger with default billing field+ fix_shared_address_instances_task()++ # then+ # Should call itself with shipping field because no billing addresses were found to fix+ mock_delay.assert_called_once_with(field=SHIPPING_FIELD)++[email protected]("saleor.checkout.migrations.tasks.saleor3_21.BATCH_SIZE", 1)+ "saleor.checkout.migrations.tasks.saleor3_21.fix_shared_address_instances_task.delay"+)+def test_task_recursion(mock_delay, checkouts_list, order, address):+ # given+ # we have 2 checkouts sharing same address with order+ # batch size is 1, so it should process first checkout and then call delay+ checkout1 = checkouts_list[0]+ checkout2 = checkouts_list[1]++ order.billing_address = address+ order.save(update_fields=["billing_address"])++ checkout1.billing_address = address+ checkout2.billing_address = address+ Checkout.objects.bulk_update([checkout1, checkout2], ["billing_address"])++ # when+ fix_shared_address_instances_task()++ # then+ checkout1.refresh_from_db()+ checkout2.refresh_from_db()++ # only one should be fixed in first batch+ fixed_checkouts = [+ c for c in [checkout1, checkout2] if c.billing_address_id != address.id+ ]+ assert len(fixed_checkouts) == 1++ # ensure it triggered next batch+ mock_delay.assert_called_once_with(field=BILLING_FIELD)diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.pyindex 040c3c2c2d..95f7153fb6 100644--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py@@ -3254,9 +3254,9 @@ def test_order_from_checkout_builtin_shipping_method_metadata_denormalization(variables,permissions=[permission_handle_checkouts],)- content = get_graphql_content(response)# then+ content = get_graphql_content(response)data = content["data"]["orderCreateFromCheckout"]assert not data["errors"]order = Order.objects.first()@@ -3277,3 +3277,99 @@ def test_order_from_checkout_builtin_shipping_method_metadata_denormalization(# Ensure shipping method metadata in DB was cleared after denormalizationshipping_method.refresh_from_db()assert shipping_method.metadata == {}+++MUTATION_ORDER_CREATE_FROM_CHECKOUT_WITH_REMOVE_CHECKOUT_FLAG = """+mutation orderCreateFromCheckout(+ $id: ID!, $removeCheckout: Boolean+ ){+ orderCreateFromCheckout(+ id: $id, removeCheckout: $removeCheckout+ ){+ order{+ id+ status+ token+ original+ origin+ total {+ currency+ net {+ amount+ }+ gross {+ amount+ }+ }+ shippingAddress {+ id+ }+ billingAddress {+ id+ }+ deliveryMethod {+ ... on ShippingMethod {+ id+ name+ metadata {+ key+ value+ }+ }+ }+ }+ errors{+ field+ message+ code+ variants+ }+ }+}+"""+++def test_order_from_checkout_do_not_remove_checkout(+ app_api_client,+ permission_handle_checkouts,+ checkout_with_item,+ address,+ shipping_method,+ checkout_delivery,+):+ # given+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)+ checkout.billing_address = address+ checkout.save(+ update_fields=["assigned_delivery", "shipping_address", "billing_address"]+ )++ variables = {+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),+ "removeCheckout": False,+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_ORDER_CREATE_FROM_CHECKOUT_WITH_REMOVE_CHECKOUT_FLAG,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderCreateFromCheckout"]+ assert not data["errors"]++ # Ensure the checkout still exists+ assert Checkout.objects.filter(pk=checkout.pk).exists()++ order = Order.objects.first()+ checkout.refresh_from_db()+ assert order+ assert order.status == OrderStatus.UNCONFIRMED+ assert order.origin == OrderOrigin.CHECKOUT+ assert order.shipping_address.id != checkout.shipping_address.id+ assert order.billing_address.id != checkout.billing_address.id