Skip to content

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

Denormalized number of orders placed by the user (#17859)

Iga Karbowiak22d9d8914f17
diff --git a/saleor/account/lock_objects.py b/saleor/account/lock_objects.py
new file mode 100644
index 0000000000..329d631c68
--- /dev/null
+++ b/saleor/account/lock_objects.py
@@ -0,0 +1,5 @@
+from .models import User
+
+
+def user_qs_select_for_update():
+ return User.objects.order_by("pk").select_for_update(of=("self",))
diff --git a/saleor/account/migrations/0090_user_number_of_orders.py b/saleor/account/migrations/0090_user_number_of_orders.py
new file mode 100644
index 0000000000..c1b7b78eec
--- /dev/null
+++ b/saleor/account/migrations/0090_user_number_of_orders.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.1 on 2025-06-24 07:49
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0089_user_user_email_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="number_of_orders",
+ field=models.PositiveIntegerField(db_default=0, default=0),
+ ),
+ ]
diff --git a/saleor/account/migrations/0091_populate_user_number_of_orders.py b/saleor/account/migrations/0091_populate_user_number_of_orders.py
new file mode 100644
index 0000000000..9cddb67f51
--- /dev/null
+++ b/saleor/account/migrations/0091_populate_user_number_of_orders.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.1 on 2025-06-24 08:18
+
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_22 import populate_user_number_of_orders_task
+
+
+def populate_user_number_of_orders(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ populate_user_number_of_orders_task.delay()
+
+ sender = registry.get_app_config("order")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0090_user_number_of_orders"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_user_number_of_orders,
+ reverse_code=migrations.RunPython.noop,
+ )
+ ]
diff --git a/saleor/account/migrations/tasks/__init__.py b/saleor/account/migrations/tasks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/account/migrations/tasks/saleor3_22.py b/saleor/account/migrations/tasks/saleor3_22.py
new file mode 100644
index 0000000000..4d183f30e6
--- /dev/null
+++ b/saleor/account/migrations/tasks/saleor3_22.py
@@ -0,0 +1,52 @@
+from collections import defaultdict
+
+from django.db import transaction
+
+from ....celeryconf import app
+from ....core.db.connection import allow_writer
+from ....order import OrderStatus
+from ....order.models import Order
+from ...models import User
+
+BATCH_SIZE = 1000
+
+
+@allow_writer()
+def populate_user_number_of_orders_task(user_pk=0):
+ users = User.objects.filter(pk__gt=user_pk).order_by("pk")
+ user_ids = list(users.values_list("id", flat=True)[:BATCH_SIZE])
+
+ if not user_ids:
+ return
+
+ user_total_orders = defaultdict(int)
+ orders = (
+ Order.objects.exclude(status=OrderStatus.DRAFT)
+ .filter(user_id__in=user_ids)
+ .values("user_id", "id")
+ )
+
+ for order in orders:
+ user_total_orders[order["user_id"]] += 1
+
+ with transaction.atomic():
+ users = (
+ User.objects.filter(pk__in=user_ids)
+ .order_by("pk")
+ .select_for_update(of=(["self"]))
+ )
+ users_to_update = []
+ for user in users:
+ total_orders = user_total_orders.get(user.id)
+
+ # Skip if the total orders count is the same to avoid unnecessary updates
+ if total_orders == user.number_of_orders:
+ continue
+
+ user.number_of_orders = total_orders
+ users_to_update.append(user)
+
+ User.objects.bulk_update(users_to_update, ["number_of_orders"])
+
+ populate_user_number_of_orders_task.delay(user_ids[-1])
diff --git a/saleor/account/models.py b/saleor/account/models.py
index c3f9cec087..a68bbb38b6 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -190,6 +190,9 @@ class User(
search_document = models.TextField(blank=True, default="")
uuid = models.UUIDField(default=uuid4, unique=True)
+ # Denormalized number of orders placed by the user
+ number_of_orders = models.PositiveIntegerField(default=0, db_default=0)
+
USERNAME_FIELD = "email"
RETURN_ID_IN_API_RESPONSE = True
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index e8b2f84bf9..34c16d1b42 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -2,13 +2,15 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING
from django.conf import settings
-from django.db.models import Exists, OuterRef
+from django.db.models import Exists, F, OuterRef
from ..app.models import App
from ..checkout import AddressType
+from ..core.tracing import traced_atomic_transaction
from ..core.utils.events import call_event
from ..permission.models import Permission
from ..plugins.manager import get_plugins_manager
+from .lock_objects import user_qs_select_for_update
from .models import Group, User
if TYPE_CHECKING:
@@ -194,3 +196,20 @@ def send_user_event(user: User, created: bool, updated: bool):
event = manager.staff_updated if user.is_staff else manager.customer_updated
if event:
call_event(event, user)
+
+
+def update_user_orders_count(user_orders_count: dict[int, int]):
+ user_ids = [user_id for user_id, count in user_orders_count.items() if count > 0]
+ users_to_update = []
+ with traced_atomic_transaction():
+ users = user_qs_select_for_update().filter(id__in=user_ids)
+ users_in_bulk = users.in_bulk()
+ for user_id, count in user_orders_count.items():
+ if count > 0:
+ user = users_in_bulk.get(user_id)
+ if user:
+ user.number_of_orders = F("number_of_orders") + count
+ users_to_update.append(user)
+
+ if users_to_update:
+ User.objects.bulk_update(users_to_update, ["number_of_orders"])
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 4e7179ff87..619d90648f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -188,12 +188,15 @@ def test_checkout_complete(
items={"accepted": "false"}
)
checkout.tax_exemption = True
+ checkout.user = customer_user
checkout.save()
checkout.metadata_storage.save()
customer_user.addresses.clear()
user_address_count = customer_user.addresses.count()
+ user_orders_count = customer_user.number_of_orders
+
checkout_line = checkout.lines.first()
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
@@ -316,6 +319,9 @@ def test_checkout_complete(
& {order.billing_address.pk, order.shipping_address.pk}
)
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_orders_count + 1
+
@pytest.mark.integration
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 5e3f4e6d21..75d39c461b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -337,6 +337,7 @@ def test_checkout_with_authorized(
transaction_item_generator,
address,
shipping_method,
+ customer_user,
):
# given
checkout = checkout_with_gift_card
@@ -348,9 +349,12 @@ def test_checkout_with_authorized(
items={"accepted": "false"}
)
checkout.tax_exemption = True
+ checkout.user = customer_user
checkout.save()
checkout.metadata_storage.save()
+ user_number_of_orders = customer_user.number_of_orders
+
checkout_line = checkout.lines.first()
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
@@ -436,6 +440,9 @@ def test_checkout_with_authorized(
assert not Checkout.objects.filter()
assert not len(Reservation.objects.all())
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_number_of_orders + 1
+
def test_checkout_with_charged(
user_api_client,
@@ -444,6 +451,7 @@ def test_checkout_with_charged(
transaction_item_generator,
address,
shipping_method,
+ customer_user,
):
# given
checkout = checkout_with_gift_card
@@ -455,9 +463,12 @@ def test_checkout_with_charged(
items={"accepted": "false"}
)
checkout.tax_exemption = True
+ checkout.user = customer_user
checkout.save()
checkout.metadata_storage.save()
+ user_number_of_orders = customer_user.number_of_orders
+
checkout_line = checkout.lines.first()
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
@@ -537,6 +548,9 @@ def test_checkout_with_charged(
assert not Checkout.objects.filter()
assert not len(Reservation.objects.all())
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_number_of_orders + 1
+
def test_checkout_price_override(
user_api_client,
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index e9405d0ac9..fb375bc396 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -11,12 +11,14 @@ from uuid import UUID
import graphene
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
+from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from graphql import GraphQLError
from prices import Money
from ....account.models import Address, User
+from ....account.utils import update_user_orders_count
from ....app.models import App
from ....channel.models import Channel
from ....core import JobStatus
@@ -2085,6 +2087,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
order_input,
object_storage: dict[str, Any],
info: ResolveInfo,
+ user_orders_count: dict[int, int],
) -> OrderBulkCreateData:
order_data = OrderBulkCreateData()
cls.validate_order_input(order_input, order_data, object_storage)
@@ -2142,6 +2145,8 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
order_data.order.created_at = order_input["created_at"]
order_data.order.status = order_input["status"]
order_data.order.user = order_data.user
+ if order_data.user:
+ user_orders_count[order_data.user.id] += 1
order_data.order.billing_address = order_data.billing_address
order_data.order.shipping_address = order_data.shipping_address
order_data.order.language_code = order_input["language_code"]
@@ -2473,6 +2478,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
return OrderBulkCreate(count=0, results=result)
orders_data: list[OrderBulkCreateData] = []
+ user_orders_count: dict[int, int] = defaultdict(int)
with traced_atomic_transaction():
# Create dictionary, which stores already resolved objects:
# - key for instances: "{model_name}.{key_name}.{key_value}"
@@ -2480,7 +2486,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
object_storage: dict[str, Any] = cls.get_all_instances(orders_input)
for order_input in orders_input:
orders_data.append(
- cls.create_single_order(order_input, object_storage, info)
+ cls.create_single_order(
+ order_input, object_storage, info, user_orders_count
+ )
)
error_policy = data.get("error_policy") or ErrorPolicy.REJECT_EVERYTHING
@@ -2508,5 +2516,6 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
results.append(
OrderBulkCreateResult(order=order_detail, errors=order_data.errors)
)
- count = sum([order_data.order is not None for order_data in orders_data])
- return OrderBulkCreate(count=count, results=results)
+ transaction.on_commit(lambda: update_user_orders_count(user_orders_count))
+ count = sum([order_data.order is not None for order_data in orders_data])
+ return OrderBulkCreate(count=count, results=results)
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index d2f28e8877..1dc2df2b38 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -91,9 +91,13 @@ def test_draft_order_complete(
permission_group_manage_orders,
staff_user,
draft_order,
+ customer_user,
):
# given
order = draft_order
+ order.user = customer_user
+ order.save(update_fields=["user"])
+
permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created
@@ -102,6 +106,8 @@ def test_draft_order_complete(
# Ensure no allocation were created
assert not Allocation.objects.filter(order_line__order=order).exists()
+ user_orders_count = customer_user.number_of_orders
+
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
@@ -140,6 +146,9 @@ def test_draft_order_complete(
assert order_created_mock.called
store_user_addresses_from_draft_order_mock.assert_called_once()
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_orders_count + 1
+
def test_draft_order_complete_no_automatically_confirm_all_new_orders(
staff_api_client,
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
index 8d4250fd5f..bef381d90e 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
@@ -654,6 +654,7 @@ def test_order_bulk_create(
invoice_count = Invoice.objects.count()
discount_count = OrderDiscount.objects.count()
voucher_code = "mirumee"
+ user_orders_count = customer_user.number_of_orders
expected_shipping_net_price = Decimal(50)
expected_shipping_gross_price = Decimal(60)
@@ -964,16 +965,21 @@ def test_order_bulk_create(
assert Invoice.objects.count() == invoice_count + 1
assert OrderDiscount.objects.count() == discount_count + 1
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_orders_count + 1
+
def test_order_bulk_create_multiple_orders(
staff_api_client,
permission_manage_orders,
permission_manage_orders_import,
order_bulk_input,
+ customer_user,
):
# given
orders_count = Order.objects.count()
order_lines_count = OrderLine.objects.count()
+ user_orders_count = customer_user.number_of_orders
order_1 = order_bulk_input
order_2 = order_bulk_input
@@ -1004,6 +1010,9 @@ def test_order_bulk_create_multiple_orders(
assert Order.objects.count() == orders_count + 2
assert OrderLine.objects.count() == order_lines_count + 2
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_orders_count + 2
+
def test_order_bulk_create_multiple_lines(
staff_api_client,
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index a97796394c..3e49269a6f 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -9,6 +9,7 @@ import graphene
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import transaction
+from django.db.models import F
from ..account.models import User
from ..app.models import App
@@ -297,6 +298,10 @@ def order_created(
extra={"tax_error": order.tax_error, "order_id": order_id},
)
+ if order_user := order.user:
+ order_user.number_of_orders = F("number_of_orders") + 1
+ order_user.save(update_fields=["number_of_orders"])
+
events.order_created_event(
order=order, user=user, app=app, from_draft=from_draft, automatic=automatic
)
diff --git a/saleor/order/tasks.py b/saleor/order/tasks.py
index 4ab000d3a4..f2ee85cc5a 100644
--- a/saleor/order/tasks.py
+++ b/saleor/order/tasks.py
@@ -1,11 +1,14 @@
import datetime
import logging
+from collections import Counter
from django.conf import settings
from django.db.models import Exists, F, Func, OuterRef, Subquery, Value
from django.db.models.functions import Greatest
from django.utils import timezone
+from ..account.lock_objects import user_qs_select_for_update
+from ..account.models import User
from ..celeryconf import app
from ..channel.models import Channel
from ..core.db.connection import allow_writer
@@ -207,8 +210,32 @@ def delete_expired_orders_task():
# Wrap ids_batch with a list as it comes from the replica DB and delete is done on
# the writer DB. This avoids mixing querysets from different DBs.
ids_batch = list(ids_batch)
+ user_orders_count = Counter(
+ Order.objects.filter(id__in=ids_batch, user_id__isnull=False)
+ .using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .values_list("user_id", flat=True)
+ )
with allow_writer():
Order.objects.filter(id__in=ids_batch).delete()
+ reduce_user_number_of_orders(user_orders_count)
+
delete_expired_orders_task.delay()
+
+
+@allow_writer()
+def reduce_user_number_of_orders(user_orders_count: dict[int, int]):
+ user_ids = list(user_orders_count.keys())
+ users_to_update = []
+ with traced_atomic_transaction():
+ users = user_qs_select_for_update().filter(id__in=user_ids)
+ users_in_bulk = users.in_bulk()
+ for user_id, order_count in user_orders_count.items():
+ user = users_in_bulk.get(user_id)
+ if user:
+ user.number_of_orders = max(user.number_of_orders - order_count, 0)
+ users_to_update.append(user)
+
+ if users_to_update:
+ User.objects.bulk_update(users_to_update, ["number_of_orders"])
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 64ccfcd890..49ddbf7b48 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -3701,7 +3701,12 @@ def test_order_created_triggers_webhooks(
order.status = OrderStatus.UNCONFIRMED
order.should_refresh_prices = True
order.charge_status = OrderChargeStatus.FULL
- order.save(update_fields=["status", "should_refresh_prices", "charge_status"])
+ order.user = customer_user
+ order.save(
+ update_fields=["status", "should_refresh_prices", "charge_status", "user"]
+ )
+
+ user_number_of_orders = customer_user.number_of_orders
order.channel.automatically_confirm_all_new_orders = True
order.channel.save(update_fields=["automatically_confirm_all_new_orders"])
@@ -3811,6 +3816,9 @@ def test_order_created_triggers_webhooks(
any_order=True,
)
+ customer_user.refresh_from_db()
+ assert customer_user.number_of_orders == user_number_of_orders + 1
+
@patch(
"saleor.order.actions.call_order_event",
diff --git a/saleor/order/tests/test_tasks.py b/saleor/order/tests/test_tasks.py
index 5cb1a700b3..0a36194f96 100644
--- a/saleor/order/tests/test_tasks.py
+++ b/saleor/order/tests/test_tasks.py
@@ -7,6 +7,7 @@ from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
+from ...account.models import User
from ...core.models import EventDelivery
from ...discount.models import VoucherCustomer
from ...warehouse.models import Allocation
@@ -705,6 +706,50 @@ def test_delete_expired_orders_task_schedule_itself(
assert Order.objects.count() == 2
+@freeze_time("2020-03-18 12:00:00")
+def test_delete_expired_orders_task_customer_lines_count_adjusted(
+ order_list, allocations, channel_USD, customer_user, customer_user2
+):
+ # given
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
+ channel_USD.save()
+
+ now = timezone.now()
+ order_1 = order_list[0]
+ order_1.expired_at = now
+ order_1.status = OrderStatus.EXPIRED
+ order_1.user = customer_user
+ order_1.save(update_fields=["expired_at", "status", "user"])
+
+ order_2 = order_list[1]
+ order_2.expired_at = now - datetime.timedelta(days=5)
+ order_2.status = OrderStatus.EXPIRED
+ order_2.user = customer_user
+ order_2.save(update_fields=["expired_at", "status", "user"])
+
+ order_3 = order_list[2]
+ order_3.expired_at = now - datetime.timedelta(days=7)
+ order_3.status = OrderStatus.EXPIRED
+ order_3.user = customer_user2
+ order_3.save(update_fields=["expired_at", "status", "user"])
+
+ customer_user.number_of_orders = 2
+ customer_user2.number_of_orders = 1
+ User.objects.bulk_update([customer_user, customer_user2], ["number_of_orders"])
+
+ # when
+ delete_expired_orders_task()
+
+ # then
+ assert Order.objects.count() == 1
+ assert order_1.id == Order.objects.get().id
+
+ customer_user.refresh_from_db()
+ customer_user2.refresh_from_db()
+ assert customer_user.number_of_orders == 1
+ assert customer_user2.number_of_orders == 0
+
+
def test_bulk_release_voucher_usage_voucher_usage_mismatch(
order_list, allocations, channel_USD, voucher_customer
):