Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve checkout search (#18767)
Iga Karbowiak3e5172f5acd0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1ce17066c3..177ee72d37 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,7 @@ All notable, unreleased changes to this project will be documented in this file.- Validation on `AppExtension` is now removed. Saleor will accept string values for `mount` and `target` from Manifest during App installation and JSON value for `options` field.Validation is now performed on the frontend (Dashboard). This change increases velocity of features related to apps and extensions, now Dashboard is only entity that ensures the contract- Improve user search. Use search vector functionality to enable searching users by email address, first name, last name, and addresses.+- Improved checkout search with search vectors. The `search_index_dirty` flag is set whenever indexed checkout data changes, and a background task runs every minute to update search vectors for dirty checkouts, processing the oldest first. Search results are returned in order of best match relevance.### Deprecations- Deprecate the `hasVariants` field on `ProductType`.diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.pyindex d03e50c47b..3a6ad15631 100644--- a/saleor/checkout/actions.py+++ b/saleor/checkout/actions.py@@ -1,6 +1,6 @@import datetimefrom decimal import Decimal-from typing import TYPE_CHECKING, Optional, cast+from typing import TYPE_CHECKING, Optionalfrom django.utils import timezone@@ -204,13 +204,11 @@ def update_last_transaction_modified_at_for_checkout(def transaction_amounts_for_checkout_updated(transaction: TransactionItem,+ checkout: Checkout,manager: "PluginsManager",user: Optional["User"],app: Optional["App"],):- if not transaction.checkout_id:- return- checkout = cast(Checkout, transaction.checkout)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)previous_charge_status = checkout_info.checkout.charge_statusdiff --git a/saleor/checkout/migrations/0089_checkout_search_vector.py b/saleor/checkout/migrations/0089_checkout_search_vector.pynew file mode 100644index 0000000000..7f501e1887--- /dev/null+++ b/saleor/checkout/migrations/0089_checkout_search_vector.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.8 on 2026-01-12 09:15++import django.contrib.postgres.search+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0088_reapply_fix_shared_address_instances"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="search_vector",+ field=django.contrib.postgres.search.SearchVectorField(+ blank=True, null=True+ ),+ ),+ ]diff --git a/saleor/checkout/migrations/0090_checkout_search_index_dirty.py b/saleor/checkout/migrations/0090_checkout_search_index_dirty.pynew file mode 100644index 0000000000..8b6c857dda--- /dev/null+++ b/saleor/checkout/migrations/0090_checkout_search_index_dirty.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.8 on 2026-01-12 09:15++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0089_checkout_search_vector"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="search_index_dirty",+ field=models.BooleanField(db_default=True, default=True),+ ),+ ]diff --git a/saleor/checkout/migrations/0091_checkout_checkout_tsearch.py b/saleor/checkout/migrations/0091_checkout_checkout_tsearch.pynew file mode 100644index 0000000000..6b9bb179e8--- /dev/null+++ b/saleor/checkout/migrations/0091_checkout_checkout_tsearch.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.8 on 2026-01-12 09:16++import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("checkout", "0090_checkout_search_index_dirty"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="checkout",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["search_vector"], name="checkout_tsearch"+ ),+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 6906af63a1..24f4374f0b 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -7,7 +7,8 @@ from typing import TYPE_CHECKING, Optionalfrom uuid import uuid4from django.conf import settings-from django.contrib.postgres.indexes import BTreeIndex+from django.contrib.postgres.indexes import BTreeIndex, GinIndex+from django.contrib.postgres.search import SearchVectorFieldfrom django.core.validators import MinValueValidatorfrom django.db import models, transactionfrom django.utils import timezone@@ -313,6 +314,9 @@ class Checkout(models.Model):max_length=TAX_ERROR_FIELD_LENGTH, blank=True, null=True)+ search_vector = SearchVectorField(blank=True, null=True)+ search_index_dirty = models.BooleanField(default=True, db_default=True)+class Meta:ordering = ("-last_change", "pk")permissions = (@@ -327,6 +331,10 @@ class Checkout(models.Model):name="automaticcompletionattempt_idx",),models.Index(fields=["created_at"], name="idx_checkout_created_at"),+ GinIndex(+ name="checkout_tsearch",+ fields=["search_vector"],+ ),]def __iter__(self):diff --git a/saleor/checkout/search/__init__.py b/saleor/checkout/search/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/checkout/search/indexing.py b/saleor/checkout/search/indexing.pynew file mode 100644index 0000000000..de01d6ed8b--- /dev/null+++ b/saleor/checkout/search/indexing.py@@ -0,0 +1,229 @@+from typing import TYPE_CHECKING++import graphene+from django.conf import settings+from django.contrib.postgres.search import SearchQuery, SearchRank+from django.db import transaction+from django.db.models import F, Q, Value++from ...account.search import (+ generate_address_search_vector_value,+ generate_email_vector,+)+from ...core.context import with_promise_context+from ...core.db.connection import allow_writer+from ...core.postgres import FlatConcatSearchVector, NoValidationSearchVector+from ..lock_objects import checkout_qs_select_for_update+from ..models import Checkout+from .loaders import CheckoutData, CheckoutLineData, TransactionData, load_checkout_data++if TYPE_CHECKING:+ from django.db.models import QuerySet++ from ...payment.models import Payment+ from ..models import Checkout+++@with_promise_context+def update_checkouts_search_vector(checkouts: list["Checkout"]):+ """Update search vectors for multiple checkouts using efficient data loading."""+ # update search_index_dirty flag before to ensure that will not update search vector+ # with outdated data+ with transaction.atomic():+ with allow_writer():+ # select and lock checkouts to ensure updating in correct order+ pks = (+ checkout_qs_select_for_update()+ .filter(+ pk__in=[checkout.pk for checkout in checkouts],+ search_index_dirty=True,+ )+ .values_list("pk", flat=True)+ )+ Checkout.objects.filter(pk__in=pks).update(search_index_dirty=False)++ checkout_pks = [checkout.pk for checkout in checkouts]+ try:+ checkout_data_map = load_checkout_data(checkouts)++ for checkout in checkouts:+ data = checkout_data_map.get(checkout.pk)+ if not data:+ continue++ checkout.search_vector = FlatConcatSearchVector(+ *prepare_checkout_search_vector_value(checkout, data)+ )+ except Exception:+ # Reset search_index_dirty flag if processing fails+ with transaction.atomic():+ with allow_writer():+ Checkout.objects.filter(pk__in=checkout_pks).update(+ search_index_dirty=True+ )+ raise++ with transaction.atomic():+ with allow_writer():+ _locked_checkouts = (+ checkout_qs_select_for_update()+ .filter(pk__in=[checkout.pk for checkout in checkouts])+ .values_list("pk", flat=True)+ )+ Checkout.objects.bulk_update(checkouts, ["search_vector"])+++def prepare_checkout_search_vector_value(+ checkout: "Checkout", data: CheckoutData+) -> list[NoValidationSearchVector]:+ """Prepare all search vector components for a checkout."""+ search_vectors = [+ NoValidationSearchVector(+ Value(str(checkout.token)), config="simple", weight="A"+ ),+ ]++ if checkout.email:+ search_vectors.extend(generate_email_vector(checkout.email))++ if data.user:+ search_vectors.extend(generate_email_vector(data.user.email))+ search_vectors.append(+ NoValidationSearchVector(+ Value(data.user.first_name), config="simple", weight="A"+ )+ )+ search_vectors.append(+ NoValidationSearchVector(+ Value(data.user.last_name), config="simple", weight="A"+ )+ )++ if data.billing_address:+ search_vectors += generate_address_search_vector_value(+ data.billing_address, weight="B"+ )+ if data.shipping_address:+ search_vectors += generate_address_search_vector_value(+ data.shipping_address, weight="B"+ )++ search_vectors += generate_checkout_payments_search_vector_value(data.payments)+ search_vectors += generate_checkout_lines_search_vector_value(data.lines)+ search_vectors += generate_checkout_transactions_search_vector_value(+ data.transactions+ )+ return search_vectors+++def generate_checkout_transactions_search_vector_value(+ transactions_data: list[TransactionData],+) -> list[NoValidationSearchVector]:+ """Generate search vectors for checkout transactions."""+ transaction_vectors = []+ for transaction_data in transactions_data[+ : settings.CHECKOUT_MAX_INDEXED_TRANSACTIONS+ ]:+ transaction = transaction_data.transaction+ transaction_vectors.append(+ NoValidationSearchVector(+ Value(graphene.Node.to_global_id("TransactionItem", transaction.token)),+ config="simple",+ weight="D",+ )+ )+ if transaction.psp_reference:+ transaction_vectors.append(+ NoValidationSearchVector(+ Value(transaction.psp_reference),+ config="simple",+ weight="D",+ )+ )++ for event in transaction_data.events:+ if event.psp_reference:+ transaction_vectors.append(+ NoValidationSearchVector(+ Value(event.psp_reference),+ config="simple",+ weight="D",+ )+ )++ return transaction_vectors+++def generate_checkout_payments_search_vector_value(+ payments: list["Payment"],+) -> list[NoValidationSearchVector]:+ """Generate search vectors for checkout payments."""+ payment_vectors = []+ for payment in payments[: settings.CHECKOUT_MAX_INDEXED_PAYMENTS]:+ payment_vectors.append(+ NoValidationSearchVector(+ Value(graphene.Node.to_global_id("Payment", payment.id)),+ config="simple",+ weight="D",+ )+ )+ if payment.psp_reference:+ payment_vectors.append(+ NoValidationSearchVector(+ Value(payment.psp_reference),+ config="simple",+ weight="D",+ )+ )+ return payment_vectors+++def generate_checkout_lines_search_vector_value(+ lines_data: list[CheckoutLineData],+) -> list[NoValidationSearchVector]:+ """Generate search vectors for checkout lines."""+ line_vectors = []+ for line_data in lines_data[: settings.CHECKOUT_MAX_INDEXED_LINES]:+ variant = line_data.variant+ if not variant:+ continue++ if variant.sku:+ line_vectors.append(+ NoValidationSearchVector(+ Value(variant.sku),+ config="simple",+ weight="C",+ )+ )++ product = line_data.product+ if product and product.name:+ line_vectors.append(+ NoValidationSearchVector(+ Value(product.name),+ config="simple",+ weight="C",+ )+ )+ if variant.name:+ line_vectors.append(+ NoValidationSearchVector(+ Value(variant.name),+ config="simple",+ weight="C",+ )+ )++ return line_vectors+++def search_checkouts(qs: "QuerySet[Checkout]", value) -> "QuerySet[Checkout]":+ """Filter checkouts by search query using the search_vector field."""+ if value:+ query = SearchQuery(value, search_type="websearch", config="simple")+ lookup = Q(search_vector=query)+ qs = qs.filter(lookup).annotate(+ search_rank=SearchRank(F("search_vector"), query)+ )+ return qsdiff --git a/saleor/checkout/search/loaders.py b/saleor/checkout/search/loaders.pynew file mode 100644index 0000000000..628011f18c--- /dev/null+++ b/saleor/checkout/search/loaders.py@@ -0,0 +1,176 @@+from itertools import chain+from typing import TYPE_CHECKING, NamedTuple+from uuid import UUID++from ...graphql.account.dataloaders import AddressByIdLoader, UserByUserIdLoader+from ...graphql.checkout.dataloaders.models import (+ CheckoutLinesByCheckoutTokenLoader,+ TransactionItemsByCheckoutIDLoader,+)+from ...graphql.core.context import SaleorContext+from ...graphql.payment.dataloaders import (+ PaymentsByCheckoutTokenLoader,+ TransactionEventByTransactionIdLoader,+)+from ...graphql.product.dataloaders.products import (+ ProductByIdLoader,+ ProductVariantByIdLoader,+)++if TYPE_CHECKING:+ from ...account.models import Address, User+ from ...payment.models import Payment, TransactionEvent, TransactionItem+ from ...product.models import Product, ProductVariant+ from ..models import Checkout, CheckoutLine+++class CheckoutLineData(NamedTuple):+ line: "CheckoutLine"+ variant: "ProductVariant | None"+ product: "Product | None"+++class TransactionData(NamedTuple):+ transaction: "TransactionItem"+ events: list["TransactionEvent"]+++class CheckoutData(NamedTuple):+ user: "User | None"+ billing_address: "Address | None"+ shipping_address: "Address | None"+ payments: list["Payment"]+ lines: list[CheckoutLineData]+ transactions: list[TransactionData]+++def load_checkout_data(checkouts: list["Checkout"]) -> dict[UUID, CheckoutData]:+ """Load all related data for checkouts using dataloaders for efficient querying."""+ context = SaleorContext()+ checkout_ids = [checkout.pk for checkout in checkouts]++ user_map = _load_users(context, checkouts)+ address_map = _load_addresses(context, checkouts)++ payments_list = PaymentsByCheckoutTokenLoader(context).load_many(checkout_ids).get()+ lines_list = (+ CheckoutLinesByCheckoutTokenLoader(context).load_many(checkout_ids).get()+ )+ transactions_list = (+ TransactionItemsByCheckoutIDLoader(context).load_many(checkout_ids).get()+ )++ all_lines = list(chain.from_iterable(lines_list))+ variant_map, product_map = _load_variants_and_products(context, all_lines)++ all_transactions = list(chain.from_iterable(transactions_list))+ transaction_events_map = _load_transaction_events(context, all_transactions)++ payments_by_checkout = dict(zip(checkout_ids, payments_list, strict=False))+ lines_by_checkout = dict(zip(checkout_ids, lines_list, strict=False))+ transactions_by_checkout = dict(zip(checkout_ids, transactions_list, strict=False))++ result = {}+ for checkout in checkouts:+ c_lines = lines_by_checkout.get(checkout.pk, [])+ line_data_list = _build_checkout_line_data(c_lines, variant_map, product_map)++ c_transactions = transactions_by_checkout.get(checkout.pk, [])+ transaction_data_list = _build_transaction_data(+ c_transactions, transaction_events_map+ )++ result[checkout.pk] = CheckoutData(+ user=user_map.get(checkout.user_id) if checkout.user_id else None,+ billing_address=address_map.get(checkout.billing_address_id)+ if checkout.billing_address_id+ else None,+ shipping_address=address_map.get(checkout.shipping_address_id)+ if checkout.shipping_address_id+ else None,+ payments=payments_by_checkout.get(checkout.pk, []),+ lines=line_data_list,+ transactions=transaction_data_list,+ )++ return result+++def _load_users(+ context: SaleorContext, checkouts: list["Checkout"]+) -> dict[int, "User"]:+ """Load users for checkouts."""+ users = (+ UserByUserIdLoader(context)+ .load_many([c.user_id for c in checkouts if c.user_id])+ .get()+ )+ return {user.id: user for user in users if user}+++def _load_addresses(+ context: SaleorContext, checkouts: list["Checkout"]+) -> dict[int, "Address"]:+ """Load billing and shipping addresses for checkouts."""+ address_ids = {c.billing_address_id for c in checkouts if c.billing_address_id}+ address_ids.update(+ {c.shipping_address_id for c in checkouts if c.shipping_address_id}+ )+ addresses = AddressByIdLoader(context).load_many(list(address_ids)).get()+ return {addr.id: addr for addr in addresses if addr}+++def _load_variants_and_products(+ context: SaleorContext, lines: list["CheckoutLine"]+) -> tuple[dict[int, "ProductVariant"], dict[int, "Product"]]:+ """Load variants and products for checkout lines."""+ variant_ids = [line.variant_id for line in lines if line.variant_id]+ variants = ProductVariantByIdLoader(context).load_many(variant_ids).get()+ variant_map = {v.id: v for v in variants if v}++ product_ids = [v.product_id for v in variants if v]+ products = ProductByIdLoader(context).load_many(product_ids).get()+ product_map = {p.id: p for p in products if p}++ return variant_map, product_map+++def _load_transaction_events(+ context: SaleorContext, transactions: list["TransactionItem"]+) -> dict[int, list["TransactionEvent"]]:+ """Load transaction events for transactions."""+ transaction_ids = [t.id for t in transactions]+ transaction_events_list = (+ TransactionEventByTransactionIdLoader(context).load_many(transaction_ids).get()+ )+ return dict(zip(transaction_ids, transaction_events_list, strict=False))+++def _build_checkout_line_data(+ lines: list["CheckoutLine"],+ variant_map: dict[int, "ProductVariant"],+ product_map: dict[int, "Product"],+) -> list[CheckoutLineData]:+ """Build CheckoutLineData objects from lines and related data."""+ line_data_list = []+ for line in lines:+ variant = variant_map.get(line.variant_id)+ product = product_map.get(variant.product_id) if variant else None+ line_data_list.append(+ CheckoutLineData(line=line, variant=variant, product=product)+ )+ return line_data_list+++def _build_transaction_data(+ transactions: list["TransactionItem"],+ transaction_events_map: dict[int, list["TransactionEvent"]],+) -> list[TransactionData]:+ """Build TransactionData objects from transactions and events."""+ transaction_data_list = []+ for transaction_item in transactions:+ events = transaction_events_map.get(transaction_item.id, [])+ transaction_data_list.append(+ TransactionData(transaction=transaction_item, events=events)+ )+ return transaction_data_listdiff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.pyindex 8e7d67df74..c13a6a721b 100644--- a/saleor/checkout/tasks.py+++ b/saleor/checkout/tasks.py@@ -23,6 +23,7 @@ from ..webhook.transport.utils import get_sqs_message_group_idfrom .complete_checkout import complete_checkoutfrom .fetch import fetch_checkout_info, fetch_checkout_linesfrom .models import Checkout, CheckoutLine+from .search.indexing import update_checkouts_search_vectorfrom .utils import delete_checkoutstask_logger: logging.Logger = get_task_logger(__name__)@@ -31,6 +32,9 @@ task_logger: logging.Logger = get_task_logger(__name__)# every 1 minute, so to avoid overlapping executions, the limit is set to 20.AUTOMATIC_COMPLETION_BATCH_SIZE = 20+# Results in update time ~0.5s+UPDATE_SEARCH_BATCH_SIZE = 100+@app.task@allow_writer()@@ -305,3 +309,61 @@ def automatic_checkout_completion_task(checkout_id,extra={"checkout_id": checkout_id},)+++ queue=settings.UPDATE_SEARCH_VECTOR_INDEX_QUEUE_NAME,+ expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC,+)+def update_checkouts_search_vector_task():+ """Update search vectors for dirty checkouts by delegating to parallel batch tasks.++ This task orchestrates the search vector update process by:+ - Fetching checkout IDs that need search index updates (search_index_dirty=True)+ - Dividing them into batches for parallel processing+ - Delegating each batch to a separate worker task++ Processing is done in batches to balance performance and resource usage,+ with multiple tasks running in parallel to speed up the overall process.+ """+ # to speed up processing, delegate multiple checkouts to batch processing tasks+ parallel_tasks = settings.CHECKOUT_SEARCH_UPDATE_PARALLEL_TASKS+ batch = UPDATE_SEARCH_BATCH_SIZE * parallel_tasks+ # process the oldest modified checkouts first to prevent repeated updates+ # in case of high update frequency of the checkout instance+ checkout_ids = list(+ Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(search_index_dirty=True)+ .order_by("last_change")+ .values_list("pk", flat=True)[:batch]+ )+ if not checkout_ids:+ return++ for i in range(parallel_tasks):+ start = i * UPDATE_SEARCH_BATCH_SIZE+ batch_ids = checkout_ids[start : start + UPDATE_SEARCH_BATCH_SIZE]+ if batch_ids:+ update_checkouts_search_vector_task_batch_process.delay(batch_ids)++[email protected](expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC)+def update_checkouts_search_vector_task_batch_process(pks: list[int]):+ """Process a batch of checkouts to update their search vectors.++ This worker task handles a subset of checkouts by:+ - Updating their search_vector fields with indexed content+ - Marking them as clean (search_index_dirty=False)++ :param pks: List of checkout primary keys to process in this batch.+ """+ checkouts = list(+ Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(+ pk__in=pks, search_index_dirty=True+ )+ )++ if not checkouts:+ return++ update_checkouts_search_vector(checkouts)diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.pyindex ff1d8e9e08..75632fe8ca 100644--- a/saleor/checkout/tests/test_actions.py+++ b/saleor/checkout/tests/test_actions.py@@ -54,7 +54,7 @@ def test_transaction_amounts_for_checkout_updated_fully_paid(# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -94,7 +94,7 @@ def test_transaction_amounts_for_checkout_updated_not_fully_paid_no_automatic_co# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -136,7 +136,7 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- second_transaction, manager=plugins_manager, user=None, app=None+ second_transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -188,7 +188,7 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_authorized(# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- second_transaction, manager=plugins_manager, user=None, app=None+ second_transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -226,7 +226,7 @@ def test_transaction_amounts_for_checkout_updated_fully_authorized(# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -269,7 +269,7 @@ def test_transaction_amounts_for_checkout_updated_updates_last_transaction_modif# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -298,7 +298,7 @@ def test_get_checkout_refundable_with_transaction_and_last_refund_success(# whentransaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -329,7 +329,7 @@ def test_get_checkout_refundable_with_transaction_and_last_refund_failure(# whentransaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -360,7 +360,7 @@ def test_get_checkout_refundable_with_transaction_without_funds(# whentransaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -392,7 +392,7 @@ def test_get_checkout_refundable_with_multiple_transactions_without_funds(# whentransaction_amounts_for_checkout_updated(- first_transaction, manager=plugins_manager, user=None, app=None+ first_transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -426,7 +426,7 @@ def test_get_checkout_refundable_with_multiple_transactions_with_failure_refund(# whentransaction_amounts_for_checkout_updated(- first_transaction, manager=plugins_manager, app=None, user=None+ first_transaction, checkout, manager=plugins_manager, app=None, user=None)# then@@ -463,7 +463,7 @@ def test_get_checkout_refundable_with_multiple_active_transactions(# whentransaction_amounts_for_checkout_updated(- first_transaction, manager=plugins_manager, user=None, app=None+ first_transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -1222,7 +1222,7 @@ def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# then@@ -1339,7 +1339,7 @@ def test_transaction_amounts_for_checkout_fully_authorized_triggers_sync_webhook# whenwith django_capture_on_commit_callbacks(execute=True):transaction_amounts_for_checkout_updated(- transaction, manager=plugins_manager, user=None, app=None+ transaction, checkout, manager=plugins_manager, user=None, app=None)# thendiff --git a/saleor/checkout/tests/test_search_indexing.py b/saleor/checkout/tests/test_search_indexing.pynew file mode 100644index 0000000000..d32c7e91ac--- /dev/null+++ b/saleor/checkout/tests/test_search_indexing.py@@ -0,0 +1,880 @@+from decimal import Decimal+from unittest.mock import patch++import graphene+import pytest++from ...payment.models import Payment, TransactionEvent, TransactionItem+from ...plugins.manager import get_plugins_manager+from ...tests import race_condition+from ..fetch import fetch_checkout_info+from ..models import Checkout, CheckoutMetadata+from ..search.indexing import (+ generate_checkout_lines_search_vector_value,+ generate_checkout_payments_search_vector_value,+ generate_checkout_transactions_search_vector_value,+ prepare_checkout_search_vector_value,+ search_checkouts,+ update_checkouts_search_vector,+)+from ..search.loaders import (+ CheckoutData,+ CheckoutLineData,+ TransactionData,+)+from ..utils import add_variant_to_checkout+++def checkout_list_with_relations(+ channel_USD, customer_user, address, address_usa, product+):+ """Create multiple checkouts with various relations for testing."""++ checkouts = []+ variant = product.variants.first()++ for i in range(3):+ checkout = Checkout.objects.create(+ currency=channel_USD.currency_code,+ channel=channel_USD,+ email=f"user{i}@example.com",+ user=customer_user if i % 2 == 0 else None,+ billing_address=address if i % 2 == 0 else None,+ shipping_address=address_usa if i % 2 == 1 else None,+ )+ checkout.set_country("US", commit=True)+ CheckoutMetadata.objects.create(checkout=checkout)++ # Add checkout line+ checkout_info = fetch_checkout_info(+ checkout, [], get_plugins_manager(allow_replica=False)+ )+ add_variant_to_checkout(checkout_info, variant, i + 1)+ checkout.save()++ # Add payment+ Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ checkout=checkout,+ total=Decimal("10.00") * (i + 1),+ currency="USD",+ psp_reference=f"PSP-REF-{i}",+ )++ # Add transaction+ transaction = TransactionItem.objects.create(+ name="Credit card",+ psp_reference=f"TRANS-PSP-{i}",+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout.pk,+ charged_value=Decimal(10) * (i + 1),+ )+ TransactionEvent.objects.create(+ psp_reference=f"EVENT-PSP-{i}",+ currency="USD",+ transaction=transaction,+ amount_value=Decimal(10),+ )++ checkouts.append(checkout)++ return checkouts+++def _extract_search_vector_values(search_vectors):+ """Extract values from NoValidationSearchVector objects."""+ values = []+ for sv in search_vectors:+ if hasattr(sv, "source_expressions") and sv.source_expressions:+ expr = sv.source_expressions[0]+ if hasattr(expr, "value"):+ values.append(str(expr.value))+ return values+++def test_update_checkouts_search_vector(checkout_with_item):+ # given+ checkout = checkout_with_item+ assert not checkout.search_vector++ # when+ update_checkouts_search_vector([checkout])++ # then+ checkout.refresh_from_db()+ assert checkout.search_vector+ assert checkout.search_index_dirty is False+++def test_update_checkouts_search_vector_multiple_checkouts(+ checkout_with_item, checkout+):+ # given+ assert not checkout_with_item.search_vector+ assert not checkout.search_vector++ # when+ update_checkouts_search_vector([checkout_with_item, checkout])++ # then+ checkout_with_item.refresh_from_db()+ checkout.refresh_from_db()+ assert checkout_with_item.search_vector+ assert checkout_with_item.search_index_dirty is False+ assert checkout.search_vector+ assert checkout.search_index_dirty is False+++def test_update_checkouts_search_vector_empty_list(db):+ # given+ checkouts = []++ # when/then - should not raise any errors+ update_checkouts_search_vector(checkouts)+++def test_update_checkouts_search_vector_constant_queries(+ checkout_list_with_relations, django_assert_num_queries+):+ """Ensure that data loaders are working correctly and number of db queries is constant."""+ # given+ checkout_list = checkout_list_with_relations++ # when & then+ # Expected query breakdown (14 total):+ # First transaction block:+ # 1. Select for update (filter dirty checkouts)+ # 2. Update search_index_dirty flag+ # Load checkout data:+ # 3. Load users (1 query)+ # 4. Load addresses (1 query)+ # 5. Load payments (1 query)+ # 6. Load checkout lines (1 query)+ # 7. Load transactions (1 query)+ # 8. Load product variants (1 query)+ # 9. Load products (1 query)+ # 10. Load transaction events (1 query)+ # Second transaction block:+ # 11. Transaction savepoint+ # 12. Select for update (lock checkouts)+ # 13. Bulk update search vectors+ # 14. Release savepoint++ expected_queries = 14+ with django_assert_num_queries(expected_queries):+ update_checkouts_search_vector(checkout_list[: len(checkout_list) - 1])+ with django_assert_num_queries(expected_queries):+ update_checkouts_search_vector(checkout_list)+++def test_prepare_checkout_search_vector_value_basic(checkout):+ # given+ checkout.email = "[email protected]"+ checkout.save(update_fields=["email"])+ data = CheckoutData(+ user=None,+ billing_address=None,+ shipping_address=None,+ payments=[],+ lines=[],+ transactions=[],+ )++ # when+ search_vectors = prepare_checkout_search_vector_value(checkout, data)++ # then+ search_vector_values = _extract_search_vector_values(search_vectors)+ assert str(checkout.token) in search_vector_values+ assert checkout.email in search_vector_values+++def test_prepare_checkout_search_vector_value_with_user(checkout, customer_user):+ # given+ checkout.user = customer_user+ checkout.email = "[email protected]"+ checkout.save(update_fields=["user", "email"])++ data = CheckoutData(+ user=customer_user,+ billing_address=None,+ shipping_address=None,+ payments=[],+ lines=[],+ transactions=[],+ )++ # when+ search_vectors = prepare_checkout_search_vector_value(checkout, data)++ # then+ search_vector_values = _extract_search_vector_values(search_vectors)+ assert str(checkout.token) in search_vector_values+ assert checkout.email in search_vector_values+ assert customer_user.email in search_vector_values+ assert customer_user.first_name in search_vector_values+ assert customer_user.last_name in search_vector_values+++def test_prepare_checkout_search_vector_value_with_addresses(+ checkout, address, address_usa+):+ # given+ checkout.billing_address = address+ checkout.shipping_address = address_usa+ checkout.save(update_fields=["billing_address", "shipping_address"])++ data = CheckoutData(+ user=None,+ billing_address=address,+ shipping_address=address_usa,+ payments=[],+ lines=[],+ transactions=[],+ )++ # when+ search_vectors = prepare_checkout_search_vector_value(checkout, data)++ # then+ search_vector_values = _extract_search_vector_values(search_vectors)+ assert str(checkout.token) in search_vector_values+ # Check billing address data is included+ assert address.city in search_vector_values+ # Check shipping address data is included+ assert address_usa.city in search_vector_values+++def test_prepare_checkout_search_vector_value_with_no_email(checkout):+ # given+ checkout.email = None+ checkout.save(update_fields=["email"])++ data = CheckoutData(+ user=None,+ billing_address=None,+ shipping_address=None,+ payments=[],+ lines=[],+ transactions=[],+ )++ # when+ search_vectors = prepare_checkout_search_vector_value(checkout, data)++ # then+ assert len(search_vectors) == 1+ search_vector_values = _extract_search_vector_values(search_vectors)+ assert str(checkout.token) in search_vector_values+++def test_generate_checkout_payments_search_vector_value_empty():+ # given+ payments = []++ # when+ result = generate_checkout_payments_search_vector_value(payments)++ # then+ assert result == []+++def test_generate_checkout_payments_search_vector_value(checkout):+ # given+ psp_ref_1 = "PSP-REF-123"+ psp_ref_2 = "PSP-REF-456"++ payment1 = Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ checkout=checkout,+ total=Decimal("10.00"),+ currency="USD",+ psp_reference=psp_ref_1,+ )+ payment2 = Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=False,+ checkout=checkout,+ total=Decimal("20.00"),+ currency="USD",+ psp_reference=psp_ref_2,+ )+ payments = [payment1, payment2]++ # when+ result = generate_checkout_payments_search_vector_value(payments)++ # then+ assert len(result) == 4+ search_vector_values = _extract_search_vector_values(result)+ assert psp_ref_1 in search_vector_values+ assert (+ str(graphene.Node.to_global_id("Payment", payment1.id)) in search_vector_values+ )+ assert psp_ref_2 in search_vector_values+ assert (+ str(graphene.Node.to_global_id("Payment", payment2.id)) in search_vector_values+ )+++def test_generate_checkout_payments_search_vector_value_respects_max_limit(+ checkout, settings+):+ # given+ limit = 5+ settings.CHECKOUT_MAX_INDEXED_PAYMENTS = limit+ payments = []+ for i in range(limit + 50):+ payments.append(+ Payment(+ gateway="mirumee.payments.dummy",+ is_active=True,+ checkout=checkout,+ total=Decimal("10.00"),+ currency="USD",+ psp_reference=f"PSP-REF-{i}",+ )+ )+ Payment.objects.bulk_create(payments)++ # when+ result = generate_checkout_payments_search_vector_value(payments)++ # then+ assert len(result) == limit * 2 # IDs + psp_references+++def test_generate_checkout_lines_search_vector_value_empty():+ # given+ lines = []++ # when+ result = generate_checkout_lines_search_vector_value(lines)++ # then+ assert result == []+++def test_generate_checkout_lines_search_vector_value(checkout_with_item, product):+ # given+ sku = "TEST-SKU-123"+ line = checkout_with_item.lines.first()+ variant = line.variant+ variant.sku = sku+ variant.save(update_fields=["sku"])++ line_data = CheckoutLineData(+ line=line,+ variant=variant,+ product=product,+ )++ # when+ result = generate_checkout_lines_search_vector_value([line_data])++ # then+ assert result+ search_vector_values = _extract_search_vector_values(result)+ assert sku in search_vector_values+ assert product.name in search_vector_values+++def test_generate_checkout_lines_search_vector_value_without_variant(+ checkout_with_item,+):+ # given+ line = checkout_with_item.lines.first()+ line_data = CheckoutLineData(+ line=line,+ variant=None,+ product=None,+ )++ # when+ result = generate_checkout_lines_search_vector_value([line_data])++ # then+ assert result == []+++def test_generate_checkout_lines_search_vector_value_without_sku(+ checkout_with_item, product+):+ # given+ line = checkout_with_item.lines.first()+ variant = line.variant+ variant.sku = None+ variant.save()++ line_data = CheckoutLineData(+ line=line,+ variant=variant,+ product=product,+ )++ # when+ result = generate_checkout_lines_search_vector_value([line_data])++ # then+ assert len(result) == 1+ search_vector_values = _extract_search_vector_values(result)+ assert product.name in search_vector_values+ # Variant name may be empty, only check if it's not empty+ if variant.name:+ assert variant.name in search_vector_values+++def test_generate_checkout_lines_search_vector_value_respects_max_limit(+ checkout, product, settings+):+ # given+ variant = product.variants.first()+ variant.name = "variant name"+ variant.sku = "variant-sku-001"+ variant.save(update_fields=["name", "sku"])++ product.name = "product name"+ product.save(update_fields=["name"])++ limit = 10+ settings.CHECKOUT_MAX_INDEXED_LINES = limit++ lines_data = []+ for _ in range(limit + 50):+ line_data = CheckoutLineData(+ line=checkout.lines.first(), # Use actual line instead of None+ variant=variant,+ product=product,+ )+ lines_data.append(line_data)++ # when+ result = generate_checkout_lines_search_vector_value(lines_data)++ # then+ # Should respect limit (10)+ # Each line can have up to 3 vectors (SKU, product name, variant name)+ assert len(result) == limit * 3+++def test_generate_checkout_transactions_search_vector_value_empty():+ # given+ transactions = []++ # when+ result = generate_checkout_transactions_search_vector_value(transactions)++ # then+ assert result == []+++def test_generate_checkout_transactions_search_vector_value(checkout):+ # given+ transaction_psp_ref = "PSP-TRANS-123"+ event_psp_ref = "EVENT-PSP-123"++ transaction = TransactionItem.objects.create(+ name="Credit card",+ psp_reference=transaction_psp_ref,+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout.pk,+ charged_value=Decimal(10),+ )+ event = TransactionEvent.objects.create(+ psp_reference=event_psp_ref,+ currency="USD",+ transaction=transaction,+ amount_value=Decimal(10),+ )++ transaction_data = TransactionData(+ transaction=transaction,+ events=[event],+ )++ # when+ result = generate_checkout_transactions_search_vector_value([transaction_data])++ # then+ assert len(result) == 3+ search_vector_values = _extract_search_vector_values(result)+ assert transaction_psp_ref in search_vector_values+ assert event_psp_ref in search_vector_values+++def test_generate_checkout_transactions_search_vector_value_without_psp_reference(+ checkout,+):+ # given+ transaction = TransactionItem.objects.create(+ name="Credit card",+ psp_reference=None,+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout.pk,+ charged_value=Decimal(10),+ )++ transaction_data = TransactionData(+ transaction=transaction,+ events=[],+ )++ # when+ result = generate_checkout_transactions_search_vector_value([transaction_data])++ # then+ # Should include only transaction global ID+ assert len(result) == 1+++def test_generate_checkout_transactions_search_vector_value_with_multiple_events(+ checkout,+):+ # given+ transaction_psp_ref = "PSP-TRANS-123"+ event1_psp_ref = "EVENT-PSP-1"+ event2_psp_ref = "EVENT-PSP-2"++ transaction = TransactionItem.objects.create(+ name="Credit card",+ psp_reference=transaction_psp_ref,+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout.pk,+ charged_value=Decimal(10),+ )+ event1 = TransactionEvent.objects.create(+ psp_reference=event1_psp_ref,+ currency="USD",+ transaction=transaction,+ amount_value=Decimal(10),+ )+ event2 = TransactionEvent.objects.create(+ psp_reference=event2_psp_ref,+ currency="USD",+ transaction=transaction,+ amount_value=Decimal(10),+ )+ event3 = TransactionEvent.objects.create(+ psp_reference=None,+ currency="USD",+ transaction=transaction,+ amount_value=Decimal(10),+ )++ transaction_data = TransactionData(+ transaction=transaction,+ events=[event1, event2, event3],+ )++ # when+ result = generate_checkout_transactions_search_vector_value([transaction_data])++ # then+ assert len(result) == 4+ search_vector_values = _extract_search_vector_values(result)+ assert transaction_psp_ref in search_vector_values+ assert event1_psp_ref in search_vector_values+ assert event2_psp_ref in search_vector_values+++def test_generate_checkout_transactions_search_vector_value_respects_max_limit(+ checkout, settings+):+ # given+ limit = 5+ settings.CHECKOUT_MAX_INDEXED_TRANSACTIONS = 5+ transactions_data = []+ for i in range(limit + 2):+ transaction = TransactionItem(+ name="Credit card",+ psp_reference=f"PSP-TRANS-{i}",+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout.pk,+ charged_value=Decimal(10),+ )+ transactions_data.append(+ TransactionData(+ transaction=transaction,+ events=[],+ )+ )++ # when+ result = generate_checkout_transactions_search_vector_value(transactions_data)++ # then+ # Should respect transaction limit (5) - 5 IDs + 5 psp_references = 10+ assert len(result) == limit * 2+++def test_search_checkouts_with_value(checkout, checkout_JPY):+ # given+ checkout.email = "[email protected]"+ checkout.save(update_fields=["email"])+ update_checkouts_search_vector([checkout, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, "[email protected]")++ # then+ assert result.count() == 1+ assert result.first() == checkout+++def test_search_checkouts_without_value(checkout, checkout_JPY):+ # given+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, None)++ # then+ assert result.count() == Checkout.objects.count()+++def test_search_checkouts_by_token(checkout, checkout_JPY):+ # given+ update_checkouts_search_vector([checkout, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, str(checkout.token))++ # then+ assert result.count() == 1+ assert result.first() == checkout+++def test_search_checkouts_by_user_email(checkout, checkout_JPY, customer_user):+ # given+ checkout.user = customer_user+ checkout.save(update_fields=["user"])++ checkout_JPY.user = customer_user+ checkout_JPY.save(update_fields=["user"])++ update_checkouts_search_vector([checkout, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, customer_user.email)++ # then+ assert result.count() == 2+++def test_search_checkouts_by_user_name(checkout, checkout_JPY, customer_user):+ # given+ checkout.user = customer_user+ checkout.save(update_fields=["user"])++ checkout_JPY.user = None+ checkout_JPY.save(update_fields=["user"])+ update_checkouts_search_vector([checkout, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, customer_user.first_name)++ # then+ assert result.count() == 1+ assert result.first() == checkout+++def test_search_checkouts_by_product_name(checkout_with_item, checkout_JPY, product):+ # given+ update_checkouts_search_vector([checkout_with_item, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, product.name)++ # then+ assert result.count() == 1+ assert result.first() == checkout_with_item+++def test_search_checkouts_by_sku(checkout_with_item, checkout_JPY):+ # given+ sku = "UNIQUE-SKU-999"+ line = checkout_with_item.lines.first()+ variant = line.variant+ variant.sku = sku+ variant.save(update_fields=["sku"])+ update_checkouts_search_vector([checkout_with_item, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, sku)++ # then+ assert result.count() == 1+ assert result.first() == checkout_with_item+++def test_search_checkouts_by_payment_psp_reference(checkout, checkout_JPY):+ # given+ psp_reference = "UNIQUE-PSP-REF-789"+ Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ checkout=checkout_JPY,+ total=Decimal("10.00"),+ currency="USD",+ psp_reference=psp_reference,+ )+ update_checkouts_search_vector([checkout, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, psp_reference)++ # then+ assert result.count() == 1+ assert result.first() == checkout_JPY+++def test_search_checkouts_by_transaction_psp_reference(checkout, checkout_JPY):+ # given+ psp_reference = "UNIQUE-TRANS-PSP-456"+ TransactionItem.objects.create(+ name="Credit card",+ psp_reference=psp_reference,+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout_JPY.pk,+ charged_value=Decimal(10),+ )+ update_checkouts_search_vector([checkout, checkout_JPY])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, psp_reference)++ # then+ assert result.count() == 1+ assert result.first() == checkout_JPY+++def test_search_checkouts_by_partial_email(checkout, checkout_with_item):+ # given+ checkout.email = "[email protected]"+ checkout.save(update_fields=["email"])+ checkout_with_item.email = "[email protected]"+ checkout_with_item.save(update_fields=["email"])++ update_checkouts_search_vector([checkout, checkout_with_item])+ qs = Checkout.objects.all()++ # when+ result = search_checkouts(qs, "test")++ # then+ results_list = list(result)+ assert len(results_list) == 1+ assert results_list[0] == checkout+++def test_update_checkouts_search_vector_handles_deleted_checkout(+ checkout_with_item, checkout_JPY+):+ # given+ assert not checkout_with_item.search_vector+ assert not checkout_JPY.search_vector++ checkouts = [checkout_with_item, checkout_JPY]++ def delete_checkout(*args, **kwargs):+ Checkout.objects.filter(pk=checkout_JPY.pk).delete()++ # when+ with race_condition.RunAfter(+ "saleor.checkout.search.indexing.load_checkout_data", delete_checkout+ ):+ update_checkouts_search_vector(checkouts)++ # then+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.search_vector+ assert checkout_with_item.search_index_dirty is False+ assert not Checkout.objects.filter(pk=checkout_JPY.pk).exists()+++def test_update_checkouts_search_vector_handles_deleted_checkout_before_lock(+ checkout_with_item, checkout_JPY+):+ # given+ assert not checkout_with_item.search_vector+ assert not checkout_JPY.search_vector++ checkouts = [checkout_with_item, checkout_JPY]++ def delete_checkout(*args, **kwargs):+ Checkout.objects.filter(pk=checkout_JPY.pk).delete()++ # when+ with race_condition.RunBefore(+ "saleor.checkout.search.indexing.checkout_qs_select_for_update", delete_checkout+ ):+ update_checkouts_search_vector(checkouts)++ # then+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.search_vector+ assert checkout_with_item.search_index_dirty is False+ assert not Checkout.objects.filter(pk=checkout_JPY.pk).exists()+++def test_update_checkouts_search_vector_resets_flag_on_prepare_exception(+ checkout_with_item,+):+ # given+ checkout = checkout_with_item+ checkout.search_index_dirty = True+ checkout.save(update_fields=["search_index_dirty"])+ assert not checkout.search_vector++ # when+ with patch(+ "saleor.checkout.search.indexing.prepare_checkout_search_vector_value",+ side_effect=ValueError("Test error"),+ ):+ with pytest.raises(ValueError, match="Test error"):+ update_checkouts_search_vector([checkout])++ # then+ checkout.refresh_from_db()+ assert checkout.search_index_dirty is True+ assert not checkout.search_vector+++def test_update_checkouts_search_vector_resets_flag_on_load_data_exception(+ checkout_with_item,+):+ # given+ checkout = checkout_with_item+ checkout.search_index_dirty = True+ checkout.save(update_fields=["search_index_dirty"])+ assert not checkout.search_vector++ # when+ with patch(+ "saleor.checkout.search.indexing.load_checkout_data",+ side_effect=RuntimeError("Database error"),+ ):+ with pytest.raises(RuntimeError, match="Database error"):+ update_checkouts_search_vector([checkout])++ # then+ checkout.refresh_from_db()+ assert checkout.search_index_dirty is True+ assert not checkout.search_vectordiff --git a/saleor/checkout/tests/test_search_loaders.py b/saleor/checkout/tests/test_search_loaders.pynew file mode 100644index 0000000000..527493f81a--- /dev/null+++ b/saleor/checkout/tests/test_search_loaders.py@@ -0,0 +1,87 @@+from decimal import Decimal++from ...payment.models import Payment, TransactionItem+from ..search.loaders import load_checkout_data+++def test_load_checkout_data(checkout_with_item, customer_user, address, address_usa):+ # given+ checkout_with_item.user = customer_user+ checkout_with_item.billing_address = address+ checkout_with_item.shipping_address = address_usa+ checkout_with_item.save()++ Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ checkout=checkout_with_item,+ total=Decimal("10.00"),+ currency="USD",+ )++ TransactionItem.objects.create(+ name="Credit card",+ psp_reference="PSP-123",+ available_actions=["refund"],+ currency="USD",+ checkout_id=checkout_with_item.pk,+ charged_value=Decimal(10),+ )++ # when+ result = load_checkout_data([checkout_with_item])++ # then+ assert checkout_with_item.pk in result+ checkout_data = result[checkout_with_item.pk]+ assert checkout_data.user == customer_user+ assert checkout_data.billing_address == address+ assert checkout_data.shipping_address == address_usa+ assert len(checkout_data.payments) == 1+ assert len(checkout_data.lines) == checkout_with_item.lines.count()+ assert len(checkout_data.transactions) == 1+++def test_load_checkout_data_empty_list():+ # given+ checkouts = []++ # when+ result = load_checkout_data(checkouts)++ # then+ assert result == {}+++def test_load_checkout_data_with_no_relations(checkout):+ # given+ checkout.user = None+ checkout.billing_address = None+ checkout.shipping_address = None+ checkout.save()++ # when+ result = load_checkout_data([checkout])++ # then+ assert checkout.pk in result+ checkout_data = result[checkout.pk]+ assert checkout_data.user is None+ assert checkout_data.billing_address is None+ assert checkout_data.shipping_address is None+ assert checkout_data.payments == []+ assert checkout_data.lines == []+ assert checkout_data.transactions == []+++def test_load_checkout_data_multiple_checkouts(checkout_with_item, checkout_JPY):+ # given+ checkouts = [checkout_with_item, checkout_JPY]++ # when+ result = load_checkout_data(checkouts)++ # then+ assert len(result) == 2+ assert checkout_with_item.pk in result+ assert checkout_JPY.pk in resultdiff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.pyindex 8ca10c74e2..891ef42450 100644--- a/saleor/checkout/tests/test_tasks.py+++ b/saleor/checkout/tests/test_tasks.py@@ -20,6 +20,8 @@ from ..tasks import (delete_expired_checkouts,task_logger,trigger_automatic_checkout_completion_task,+ update_checkouts_search_vector_task,+ update_checkouts_search_vector_task_batch_process,)@@ -1444,3 +1446,195 @@ def test_trigger_automatic_checkout_completion_task_with_cut_off_date(]assert eligible_checkout.pk in called_checkoutsassert ineligible_checkout_due_to_cut_off.pk not in called_checkouts+++ "saleor.checkout.tasks.update_checkouts_search_vector_task_batch_process.delay"+)+def test_update_checkouts_search_vector_task_updates_dirty_checkouts(+ mock_batch_process,+ checkouts_list,+):+ # given+ assert len(checkouts_list) > 3+ dirty_checkouts = checkouts_list[:3]+ for checkout in dirty_checkouts:+ checkout.search_index_dirty = True++ for checkout in checkouts_list[3:]:+ checkout.search_index_dirty = False++ Checkout.objects.bulk_update(checkouts_list, ["search_index_dirty"])++ # when+ update_checkouts_search_vector_task()++ # then+ mock_batch_process.assert_called_once()+ called_pks = mock_batch_process.call_args[0][0]+ assert len(called_pks) == 3+ assert set(called_pks) == {c.pk for c in dirty_checkouts}+++ "saleor.checkout.tasks.update_checkouts_search_vector_task_batch_process.delay"+)+def test_update_checkouts_search_vector_task_respects_batch_size(+ mock_batch_process,+ checkouts_list,+):+ # given+ batch_size = 1+ parallel_tasks = 5++ assert len(checkouts_list) >= batch_size * parallel_tasks+ # Mark more checkouts as dirty than the batch size+ for checkout in checkouts_list[: batch_size * parallel_tasks]:+ checkout.search_index_dirty = True++ Checkout.objects.bulk_update(checkouts_list, ["search_index_dirty"])++ # when+ with mock.patch("saleor.checkout.tasks.UPDATE_SEARCH_BATCH_SIZE", batch_size):+ update_checkouts_search_vector_task()++ # then+ # Should spawn 5 parallel tasks (default parallel_tasks value)+ assert mock_batch_process.call_count == 5+ # Each call should have batch_size items+ all_pks = []+ for call in mock_batch_process.call_args_list:+ called_pks = call[0][0]+ assert len(called_pks) == batch_size+ all_pks.extend(called_pks)++ # Verify each batch gets unique PKs - no duplicates+ assert len(all_pks) == len(set(all_pks))+++ "saleor.checkout.tasks.update_checkouts_search_vector_task_batch_process.delay"+)+def test_update_checkouts_search_vector_task_no_dirty_checkouts(+ mock_batch_process,+ checkouts_list,+):+ # given+ Checkout.objects.update(search_index_dirty=False)++ # when+ update_checkouts_search_vector_task()++ # then+ mock_batch_process.assert_not_called()+++ "saleor.checkout.tasks.update_checkouts_search_vector_task_batch_process.delay"+)+def test_update_checkouts_search_vector_task_skips_clean_checkouts(+ mock_batch_process,+ checkouts_list,+):+ # given+ dirty_checkout = checkouts_list[0]+ dirty_checkout.search_index_dirty = True+ dirty_checkout.save(update_fields=["search_index_dirty"])++ clean_checkouts = checkouts_list[1:]+ for checkout in clean_checkouts:+ checkout.search_index_dirty = False++ Checkout.objects.bulk_update(clean_checkouts, ["search_index_dirty"])++ # when+ update_checkouts_search_vector_task()++ # then+ mock_batch_process.assert_called_once()+ called_pks = mock_batch_process.call_args[0][0]+ assert len(called_pks) == 1+ assert called_pks[0] == dirty_checkout.pk++[email protected]("saleor.checkout.tasks.update_checkouts_search_vector")+def test_update_checkouts_search_vector_task_batch_process_updates_checkouts(+ mock_update_search_vector,+ checkouts_list,+):+ # given+ dirty_checkouts = checkouts_list[:3]+ for checkout in dirty_checkouts:+ checkout.search_index_dirty = True+ Checkout.objects.bulk_update(dirty_checkouts, ["search_index_dirty"])++ pks = [c.pk for c in dirty_checkouts]++ # when+ update_checkouts_search_vector_task_batch_process(pks)++ # then+ mock_update_search_vector.assert_called_once()+ called_checkouts = mock_update_search_vector.call_args[0][0]+ assert len(called_checkouts) == 3+ assert {c.pk for c in called_checkouts} == set(pks)++[email protected]("saleor.checkout.tasks.update_checkouts_search_vector")+def test_update_checkouts_search_vector_task_batch_process_skips_clean_checkouts(+ mock_update_search_vector,+ checkouts_list,+):+ # given+ dirty_checkout = checkouts_list[0]+ dirty_checkout.search_index_dirty = True+ dirty_checkout.save(update_fields=["search_index_dirty"])++ clean_checkout = checkouts_list[1]+ clean_checkout.search_index_dirty = False+ clean_checkout.save(update_fields=["search_index_dirty"])++ pks = [dirty_checkout.pk, clean_checkout.pk]++ # when+ update_checkouts_search_vector_task_batch_process(pks)++ # then+ mock_update_search_vector.assert_called_once()+ called_checkouts = mock_update_search_vector.call_args[0][0]+ assert len(called_checkouts) == 1+ assert called_checkouts[0].pk == dirty_checkout.pk++[email protected]("saleor.checkout.tasks.update_checkouts_search_vector")+def test_update_checkouts_search_vector_task_batch_process_no_dirty_checkouts(+ mock_update_search_vector,+ checkouts_list,+):+ # given+ clean_checkouts = checkouts_list[:3]+ for checkout in clean_checkouts:+ checkout.search_index_dirty = False+ Checkout.objects.bulk_update(clean_checkouts, ["search_index_dirty"])++ pks = [c.pk for c in clean_checkouts]++ # when+ update_checkouts_search_vector_task_batch_process(pks)++ # then+ mock_update_search_vector.assert_not_called()++[email protected]("saleor.checkout.tasks.update_checkouts_search_vector")+def test_update_checkouts_search_vector_task_batch_process_empty_pks(+ mock_update_search_vector,+):+ # given+ pks = []++ # when+ update_checkouts_search_vector_task_batch_process(pks)++ # then+ mock_update_search_vector.assert_not_called()diff --git a/saleor/core/schedules.py b/saleor/core/schedules.pyindex 20d9c92f4e..c2a718a001 100644--- a/saleor/core/schedules.py+++ b/saleor/core/schedules.py@@ -295,6 +295,26 @@ class gift_card_search_update_schedule(TimeBaseSchedule):)+class checkout_search_update_schedule(TimeBaseSchedule):+ def __init__(self, initial_timedelta=60, nowfun=None, app=None):+ # initial_timedelta defaults to 60 seconds, as referencing settings.py variables+ # would require rebuilding the schedule. settings depends on this class instance,+ # leading to a circular import if accessed directly.+ import_path = "saleor.core.schedules.initiated_checkout_search_update_schedule"+ super().__init__(import_path, initial_timedelta, nowfun, app)++ def are_dirty(self) -> bool:+ from django.conf import settings++ from ..checkout.models import Checkout++ return (+ Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(search_index_dirty=True)+ .exists()+ )++initiated_promotion_webhook_schedule = promotion_webhook_schedule()initiated_checkout_automatic_completion_schedule = (checkout_automatic_completion_schedule()@@ -302,3 +322,4 @@ initiated_checkout_automatic_completion_schedule = (initiated_gift_card_search_update_schedule = gift_card_search_update_schedule()initiated_page_search_update_schedule = page_search_update_schedule()initiated_product_search_update_schedule = product_search_update_schedule()+initiated_checkout_search_update_schedule = checkout_search_update_schedule()diff --git a/saleor/core/tests/test_schedules.py b/saleor/core/tests/test_schedules.pyindex de52f8ea35..2cf97f18fb 100644--- a/saleor/core/tests/test_schedules.py+++ b/saleor/core/tests/test_schedules.py@@ -11,6 +11,7 @@ from ...checkout.models import Checkoutfrom ...discount.models import Promotionfrom ..schedules import (checkout_automatic_completion_schedule,+ checkout_search_update_schedule,gift_card_search_update_schedule,page_search_update_schedule,product_search_update_schedule,@@ -529,3 +530,56 @@ def test_automatic_completion_schedule_zero_total(checkout_with_prices, channel_# thenassert is_due is Falseassert next_run == schedule.initial_timedelta.total_seconds()+++def test_checkout_search_update_schedule_are_dirty(checkout):+ # given+ schedule = checkout_search_update_schedule()+ checkout.search_index_dirty = True+ checkout.save(update_fields=["search_index_dirty"])++ # when+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))++ # then+ assert is_due is True+ assert next_run == schedule.initial_timedelta.total_seconds()+++@freeze_time("2020-10-10 12:00:00")+def test_checkout_search_update_schedule_remaining_estimate_initial_state():+ # given+ schedule = checkout_search_update_schedule()++ # when+ remaining = schedule.remaining_estimate(last_run_at=timezone.now())++ # then+ assert remaining == schedule.initial_timedelta+++@freeze_time("2020-10-10 12:00:00")+def test_checkout_search_update_schedule_remaining_estimate():+ # given+ schedule = checkout_search_update_schedule()+ time_delta = datetime.timedelta(seconds=30)++ # when+ remaining = schedule.remaining_estimate(last_run_at=timezone.now() - time_delta)++ # then+ assert remaining == schedule.initial_timedelta - time_delta+++def test_checkout_search_update_schedule_not_dirty(checkout):+ # given+ schedule = checkout_search_update_schedule()+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])++ # when+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))++ # then+ assert is_due is False+ assert next_run == schedule.initial_timedelta.total_seconds()diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 2b40698e66..e730cb94f3 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -752,7 +752,7 @@ def create_transaction_with_events(if events_to_create:TransactionEvent.objects.bulk_create(events_to_create)recalculate_transaction_amounts(transaction=transaction_item)- update_order_with_transaction_details(transaction_item)+ update_order_with_transaction_details(order)return transaction_itemdiff --git a/saleor/graphql/checkout/filters.py b/saleor/graphql/checkout/filters.pyindex 20d24ced74..2709495842 100644--- a/saleor/graphql/checkout/filters.py+++ b/saleor/graphql/checkout/filters.py@@ -6,6 +6,7 @@ from django.db.models import Exists, OuterRef, Qfrom ...account.models import Userfrom ...checkout.models import Checkout+from ...checkout.search.indexing import search_checkoutsfrom ...payment.models import Paymentfrom ..channel.filters import get_currency_from_filter_datafrom ..channel.types import Channel@@ -98,30 +99,7 @@ def filter_channels(qs, _, values):def filter_checkout_search(qs, _, value):- if payment_id := get_payment_id_from_query(value):- return filter_checkout_by_payment(qs, payment_id)-- users = (- User.objects.using(qs.db)- .filter(- Q(email__ilike=value)- | Q(first_name__ilike=value)- | Q(last_name__ilike=value)- )- .values("pk")- )-- filter_option = Q(Exists(users.filter(id=OuterRef("user_id"))))-- possible_token = get_checkout_id_from_query(value) or value-- if checkout_id := get_checkout_token_from_query(possible_token):- filter_option |= Q(token=checkout_id)-- payments = Payment.objects.using(qs.db).filter(psp_reference=value).values("id")- filter_option |= Q(Exists(payments.filter(checkout_id=OuterRef("token"))))-- return qs.filter(filter_option)+ return search_checkouts(qs, value)def filter_checkout_metadata(qs, _, value):diff --git a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py b/saleor/graphql/checkout/mutations/checkout_billing_address_update.pyindex caad9bb47b..3bcdeaa9a5 100644--- a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py@@ -114,9 +114,11 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):recalculate_discount=False,save=False,)+ checkout.search_index_dirty = Truecheckout.save(update_fields=change_address_updated_fields+ invalidate_prices_updated_fields+ + ["search_index_dirty"])call_checkout_info_event(diff --git a/saleor/graphql/checkout/mutations/checkout_customer_attach.py b/saleor/graphql/checkout/mutations/checkout_customer_attach.pyindex 58cee0adc8..55e97cff05 100644--- a/saleor/graphql/checkout/mutations/checkout_customer_attach.py+++ b/saleor/graphql/checkout/mutations/checkout_customer_attach.py@@ -115,7 +115,10 @@ class CheckoutCustomerAttach(BaseMutation):checkout.user = customercheckout.email = customer.email- checkout.save(update_fields=["email", "user", "last_change"])+ checkout.search_index_dirty = True+ checkout.save(+ update_fields=["email", "user", "last_change", "search_index_dirty"]+ )manager = get_plugin_manager_promise(info.context).get()call_checkout_event(diff --git a/saleor/graphql/checkout/mutations/checkout_customer_detach.py b/saleor/graphql/checkout/mutations/checkout_customer_detach.pyindex 6a309c573f..610fc53ed9 100644--- a/saleor/graphql/checkout/mutations/checkout_customer_detach.py+++ b/saleor/graphql/checkout/mutations/checkout_customer_detach.py@@ -68,7 +68,8 @@ class CheckoutCustomerDetach(BaseMutation):)checkout.user = None- checkout.save(update_fields=["user", "last_change"])+ checkout.search_index_dirty = True+ checkout.save(update_fields=["user", "last_change", "search_index_dirty"])manager = get_plugin_manager_promise(info.context).get()call_checkout_event(diff --git a/saleor/graphql/checkout/mutations/checkout_email_update.py b/saleor/graphql/checkout/mutations/checkout_email_update.pyindex 5bcd4bb3b0..46001f789e 100644--- a/saleor/graphql/checkout/mutations/checkout_email_update.py+++ b/saleor/graphql/checkout/mutations/checkout_email_update.py@@ -79,7 +79,8 @@ class CheckoutEmailUpdate(BaseMutation):checkout.email = emailcls.clean_instance(info, checkout)- checkout.save(update_fields=["email", "last_change"])+ checkout.search_index_dirty = True+ checkout.save(update_fields=["email", "last_change", "search_index_dirty"])manager = get_plugin_manager_promise(info.context).get()call_checkout_event(manager,diff --git a/saleor/graphql/checkout/mutations/checkout_line_delete.py b/saleor/graphql/checkout/mutations/checkout_line_delete.pyindex ad67c005cd..10ce684dde 100644--- a/saleor/graphql/checkout/mutations/checkout_line_delete.py+++ b/saleor/graphql/checkout/mutations/checkout_line_delete.py@@ -91,7 +91,12 @@ class CheckoutLineDelete(BaseMutation):invalidate_update_fields = invalidate_checkout(checkout_info, lines, manager, save=False)- checkout.save(update_fields=shipping_update_fields + invalidate_update_fields)+ checkout.search_index_dirty = True+ checkout.save(+ update_fields=shipping_update_fields+ + invalidate_update_fields+ + ["search_index_dirty"]+ )call_checkout_info_event(manager,event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex 600810bd9b..301b3d8926 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -255,7 +255,9 @@ class CheckoutLinesAdd(BaseMutation):invalidate_update_fields = invalidate_checkout(checkout_info, lines, manager, save=False)- checkout.save(update_fields=shipping_update_fields + invalidate_update_fields)+ update_fields = shipping_update_fields + invalidate_update_fields+ cls.mark_search_vectors_as_dirty(checkout, update_fields)+ checkout.save(update_fields=update_fields)call_checkout_info_event(manager,event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,@@ -265,6 +267,11 @@ class CheckoutLinesAdd(BaseMutation):return CheckoutLinesAdd(checkout=SyncWebhookControlContext(node=checkout))+ @classmethod+ def mark_search_vectors_as_dirty(cls, checkout, update_fields):+ checkout.search_index_dirty = True+ update_fields.append("search_index_dirty")+@classmethoddef _get_variants_from_lines_input(cls, lines: list[dict]) -> list[ProductVariant]:"""Return list of ProductVariant objects.diff --git a/saleor/graphql/checkout/mutations/checkout_lines_delete.py b/saleor/graphql/checkout/mutations/checkout_lines_delete.pyindex 486ab70f21..9db7e3391d 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_delete.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_delete.py@@ -106,7 +106,12 @@ class CheckoutLinesDelete(BaseMutation):invalidate_update_fields = invalidate_checkout(checkout_info, lines, manager, save=False)- checkout.save(update_fields=shipping_update_fields + invalidate_update_fields)+ checkout.search_index_dirty = True+ checkout.save(+ update_fields=shipping_update_fields+ + invalidate_update_fields+ + ["search_index_dirty"]+ )call_checkout_info_event(manager,event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex 38063989b5..a9476d8d68 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -232,6 +232,12 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):id=id,)+ @classmethod+ def mark_search_vectors_as_dirty(cls, checkout, update_fields):+ # As any changes applied with `CheckoutLinesUpdate` do not influence the+ # checkout search vector, we don't mark it as dirty.+ pass+@classmethoddef _get_variants_from_lines_input(cls, lines: list[dict]) -> list[ProductVariant]:"""Return list of ProductVariant objects.diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.pyindex 97a4287988..622f38bc8f 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py@@ -208,10 +208,12 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixiinvalidate_prices_updated_fields = invalidate_checkout(checkout_info, lines, manager, save=False)+ checkout.search_index_dirty = Truecheckout.save(update_fields=shipping_address_updated_fields+ invalidate_prices_updated_fields+ shipping_update_fields+ + ["search_index_dirty"])call_checkout_info_event(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.pyindex 5673bef07e..5a300158d6 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py@@ -49,6 +49,8 @@ def test_checkout_billing_address_update_by_id():checkout = checkout_with_itemassert checkout.shipping_address is None+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])query = MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATEbilling_address = graphql_address_data@@ -65,6 +67,7 @@ def test_checkout_billing_address_update_by_id(checkout.refresh_from_db()assert_address_data(checkout.billing_address, billing_address)assert checkout.save_billing_address is True+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(@@ -150,6 +153,8 @@ def test_checkout_billing_address_update_by_id_without_street_address_2():checkout = checkout_with_itemassert checkout.shipping_address is None+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])query = MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE@@ -169,6 +174,7 @@ def test_checkout_billing_address_update_by_id_without_street_address_2(checkout.refresh_from_db()assert_address_data(checkout.billing_address, billing_address)assert checkout.save_billing_address is True+ assert checkout.search_index_dirty is True@mock.patch(@@ -184,6 +190,8 @@ def test_checkout_billing_address_update():checkout = checkout_with_itemassert checkout.shipping_address is None+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])previous_last_change = checkout.last_changequery = """@@ -217,6 +225,7 @@ def test_checkout_billing_address_update(assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1assert checkout.save_billing_address is True+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.pyindex e0cd4969a1..b780ea9215 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py@@ -37,7 +37,8 @@ def test_checkout_customer_attach():checkout = checkout_with_itemcheckout.email = "[email protected]"- checkout.save()+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty", "email"])assert checkout.user is Noneprevious_last_change = checkout.last_change@@ -57,6 +58,7 @@ def test_checkout_customer_attach(assert checkout.user == customer_user2assert checkout.email == customer_user2.emailassert checkout.last_change != previous_last_change+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.pyindex 2aaac76b4a..25e85da40e 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py@@ -31,7 +31,8 @@ MUTATION_CHECKOUT_CUSTOMER_DETACH = """def test_checkout_customer_detach(user_api_client, checkout_with_item, customer_user):checkout = checkout_with_itemcheckout.user = customer_user- checkout.save(update_fields=["user"])+ checkout.search_index_dirty = False+ checkout.save(update_fields=["user", "search_index_dirty"])previous_last_change = checkout.last_changevariables = {"id": to_global_id_or_none(checkout)}@@ -46,6 +47,7 @@ def test_checkout_customer_detach(user_api_client, checkout_with_item, customer_checkout.refresh_from_db()assert checkout.user is Noneassert checkout.last_change != previous_last_change+ assert checkout.search_index_dirty is True# Mutation should fail when user calling it doesn't own the checkout.other_user = User.objects.create_user("[email protected]", "password")diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.pyindex a868b44b46..bad1a76fe9 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py@@ -39,7 +39,8 @@ def test_anonymous_checkout_email_update(user_api_client, checkout_with_item):checkout = checkout_with_itemassert checkout.user is Nonecheckout.email = None- checkout.save(update_fields=["email"])+ checkout.search_index_dirty = False+ checkout.save(update_fields=["email", "search_index_dirty"])previous_last_change = checkout.last_changeemail = "[email protected]"@@ -56,6 +57,7 @@ def test_anonymous_checkout_email_update(user_api_client, checkout_with_item):checkout.refresh_from_db()assert checkout.email == emailassert checkout.last_change != previous_last_change+ assert checkout.search_index_dirty is Truedef test_authenticated_checkout_email_update(user_api_client, checkout_with_item):@@ -64,7 +66,8 @@ def test_authenticated_checkout_email_update(user_api_client, checkout_with_itemcheckout = checkout_with_itemcheckout.user = user_api_client.userassert checkout.email != expected_email- checkout.save(update_fields=["email"])+ checkout.search_index_dirty = False+ checkout.save(update_fields=["email", "search_index_dirty"])previous_last_change = checkout.last_changevariables = {"id": to_global_id_or_none(checkout), "email": expected_email}@@ -81,6 +84,7 @@ def test_authenticated_checkout_email_update(user_api_client, checkout_with_itemcheckout.refresh_from_db()assert checkout.email == expected_emailassert checkout.last_change != previous_last_change+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.pyindex 2f4f8061de..a9327018ee 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py@@ -72,6 +72,8 @@ def test_checkout_line_delete(assert checkout.lines.count() == 1line = checkout.lines.first()assert line.quantity == 3+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)@@ -96,6 +98,7 @@ def test_checkout_line_delete()assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex d6e2ffd24e..d48bad3d05 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -113,6 +113,8 @@ def test_checkout_lines_add(assert calculate_checkout_quantity(lines) == 3variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)previous_last_change = checkout.last_change+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])variables = {"id": to_global_id_or_none(checkout),@@ -143,6 +145,7 @@ def test_checkout_lines_add()assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.pyindex f8a4857b6f..7cfd5048d9 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py@@ -58,6 +58,9 @@ def test_checkout_lines_delete(checkout_with_items,):checkout = checkout_with_items+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])+checkout_lines_count = checkout.lines.count()previous_last_change = checkout.last_changeline = checkout.lines.first()@@ -86,6 +89,7 @@ def test_checkout_lines_delete()assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex fb3db4a1b5..86f551d9c0 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -104,6 +104,8 @@ def test_checkout_lines_update(line = checkout.lines.first()variant = line.variantassert line.quantity == 3+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])previous_last_change = checkout.last_changevariant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)@@ -126,13 +128,15 @@ def test_checkout_lines_update(assert calculate_checkout_quantity(lines) == 1manager = get_plugins_manager(allow_replica=False)- lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)mocked_mark_shipping_methods_as_stale.assert_called_once_with(checkout_info.checkout, lines)assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1+ # search index should not be marked as dirty as the mutation+ # do not allow changing anything that is used for searching+ assert checkout.search_index_dirty is False@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.pyindex 1b534c216a..f4f4182576 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py@@ -115,6 +115,8 @@ def test_checkout_shipping_address_with_metadata_update(checkout = checkout_with_itemassert checkout.shipping_address is Noneprevious_last_change = checkout.last_change+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])shipping_address = graphql_address_datavariables = {@@ -139,6 +141,7 @@ def test_checkout_shipping_address_with_metadata_update(assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1assert checkout.save_shipping_address is True+ assert checkout.search_index_dirty is True@pytest.mark.parametrize(@@ -175,6 +178,9 @@ def test_checkout_shipping_address_when_variant_without_listing(channel_id=checkout.channel_id, **{listing_filter_field: line.variant_id}).delete()+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])+assert checkout.shipping_address is Noneprevious_last_change = checkout.last_change@@ -204,6 +210,7 @@ def test_checkout_shipping_address_when_variant_without_listing(assert checkout.last_change != previous_last_changeassert mocked_invalidate_checkout.call_count == 1assert checkout.save_shipping_address is True+ assert checkout.search_index_dirty is True@mock.patch(@@ -255,6 +262,7 @@ def test_checkout_shipping_address_update_changes_checkout_country(assert checkout.country == shipping_address["country"]assert checkout.last_change != previous_last_changeassert checkout.save_shipping_address is True+ assert checkout.search_index_dirty is True@mock.patch(diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.pyindex c425d0a254..7310bf3364 100644--- a/saleor/graphql/checkout/tests/test_checkout_filters.py+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py@@ -11,6 +11,7 @@ from prices import Moneyfrom ....account.models import Userfrom ....checkout.models import Checkoutfrom ....checkout.payment_utils import update_checkout_payment_statuses+from ....checkout.search.indexing import update_checkouts_search_vectorfrom ....payment.models import ChargeStatus, Paymentfrom ...core.connection import where_filter_qsfrom ...tests.utils import get_graphql_content@@ -335,12 +336,13 @@ def test_query_checkout_with_sort(@pytest.mark.parametrize(("checkouts_filter", "count"),[- ({"search": "user_email"}, 2),+ ({"search": "User"}, 2),({"search": "[email protected]"}, 1),({"search": "Leslie"}, 1),({"search": "Wade"}, 1),({"search": ""}, 4),({"search": "ExternalID"}, 1),+ ({"search": "example.com"}, 3),],)def test_checkouts_query_with_filter_search(@@ -352,9 +354,15 @@ def test_checkouts_query_with_filter_search(channel_USD,):# given- user1 = User.objects.create(email="[email protected]")- user2 = User.objects.create(email="[email protected]")- user3 = User.objects.create(email="[email protected]")+ user1 = User.objects.create(+ first_name="User", last_name="One", email="[email protected]"+ )+ user2 = User.objects.create(+ first_name="User", last_name="Two", email="[email protected]"+ )+ user3 = User.objects.create(+ first_name="John", last_name="Wayne", email="[email protected]"+ )checkouts = Checkout.objects.bulk_create([@@ -380,12 +388,13 @@ def test_checkouts_query_with_filter_search(),])-checkout_with_payment = checkouts[1]payment = Payment.objects.create(checkout=checkout_with_payment, psp_reference="ExternalID")payment.transactions.create(gateway_response={}, is_success=True)+ update_checkouts_search_vector(checkouts)+variables = {"filter": checkouts_filter}staff_api_client.user.user_permissions.add(permission_manage_checkouts)@@ -422,8 +431,10 @@ def test_checkouts_query_with_filter_search_by_global_payment_id(checkout_with_payment = checkouts[0]payment = Payment.objects.create(checkout=checkout_with_payment)- global_id = graphene.Node.to_global_id("Payment", payment.pk)+ update_checkouts_search_vector(checkouts)++ global_id = graphene.Node.to_global_id("Payment", payment.pk)variables = {"filter": {"search": global_id}}staff_api_client.user.user_permissions.add(permission_manage_checkouts)@@ -435,10 +446,40 @@ def test_checkouts_query_with_filter_search_by_global_payment_id(assert content["data"]["checkouts"]["totalCount"] == 1+def test_filtering_checkout_discounted_object_by_transaction_psp_reference(+ checkout_with_item, staff_api_client, permission_manage_checkouts+):+ # given+ checkout = checkout_with_item+ transaction_psp_reference = "test_psp_reference"+ checkout.payment_transactions.create(+ currency=checkout.currency,+ psp_reference=transaction_psp_reference,+ )++ Checkout.objects.create(+ currency=checkout.currency,+ user=checkout.user,+ channel=checkout.channel,+ )+ update_checkouts_search_vector([checkout])++ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ variables = {"filter": {"search": transaction_psp_reference}}++ # when+ response = staff_api_client.post_graphql(CHECKOUT_QUERY_WITH_FILTER, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkouts"]["totalCount"] == 1++def test_checkouts_query_with_filter_search_by_token(checkout, staff_api_client, permission_manage_checkouts):# given+ update_checkouts_search_vector([checkout])variables = {"filter": {"search": checkout.pk}}staff_api_client.user.user_permissions.add(permission_manage_checkouts)diff --git a/saleor/graphql/payment/dataloaders.py b/saleor/graphql/payment/dataloaders.pyindex 7d04b81d4b..d8df5d95e4 100644--- a/saleor/graphql/payment/dataloaders.py+++ b/saleor/graphql/payment/dataloaders.py@@ -1,6 +1,6 @@from collections import defaultdict-from ...payment.models import Transaction, TransactionEvent, TransactionItem+from ...payment.models import Payment, Transaction, TransactionEvent, TransactionItemfrom ..core.dataloaders import DataLoader@@ -42,3 +42,16 @@ class TransactionByPaymentIdLoader(DataLoader[int, list[Transaction]]):transaction_group[transaction.payment_id].append(transaction)return [transaction_group.get(payment_id, []) for payment_id in keys]+++class PaymentsByCheckoutTokenLoader(DataLoader[str, list["Payment"]]):+ context_key = "payments_by_checkout_token"++ def batch_load(self, keys):+ payments = Payment.objects.using(self.database_connection_name).filter(+ checkout_id__in=keys+ )+ payment_map = defaultdict(list)+ for payment in payments:+ payment_map[str(payment.checkout_id)].append(payment)+ return [payment_map[str(checkout_id)] for checkout_id in keys]diff --git a/saleor/graphql/payment/mutations/payment/payment_capture.py b/saleor/graphql/payment/mutations/payment/payment_capture.pyindex ee296dae09..c6f1b436bc 100644--- a/saleor/graphql/payment/mutations/payment/payment_capture.py+++ b/saleor/graphql/payment/mutations/payment/payment_capture.py@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationErrorfrom .....payment import PaymentError, gatewayfrom .....payment.error_codes import PaymentErrorCode+from .....payment.utils import mark_checkout_search_index_dirtyfrom .....permission.enums import OrderPermissionsfrom ....core import ResolveInfofrom ....core.doc_category import DOC_CATEGORY_PAYMENTS@@ -50,4 +51,6 @@ class PaymentCapture(BaseMutation):raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value) from e+ if payment.checkout_id:+ mark_checkout_search_index_dirty(payment.checkout)return PaymentCapture(payment=payment)diff --git a/saleor/graphql/payment/mutations/payment/payment_void.py b/saleor/graphql/payment/mutations/payment/payment_void.pyindex c3a0c5fc7b..02793a5600 100644--- a/saleor/graphql/payment/mutations/payment/payment_void.py+++ b/saleor/graphql/payment/mutations/payment/payment_void.py@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationErrorfrom .....payment import PaymentError, gatewayfrom .....payment.error_codes import PaymentErrorCode+from .....payment.utils import mark_checkout_search_index_dirtyfrom .....permission.enums import OrderPermissionsfrom ....core import ResolveInfofrom ....core.doc_category import DOC_CATEGORY_PAYMENTS@@ -43,4 +44,6 @@ class PaymentVoid(BaseMutation):raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value) from e+ if payment.checkout_id:+ mark_checkout_search_index_dirty(payment.checkout)return PaymentVoid(payment=payment)diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.pyindex 3809914215..546e85b4b1 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py@@ -25,6 +25,7 @@ from .....payment.utils import (authorization_success_already_exists,create_failed_transaction_event,get_already_existing_event,+ get_source_object,get_transaction_event_amount,invalidate_cache_for_stored_payment_methods_if_needed,process_order_or_checkout_with_transaction,@@ -478,16 +479,9 @@ class TransactionEventReport(DeprecatedModelMutation):app_identifier = app_identifier or transaction.app_identifier- source_object: Checkout | order_models.Order | None = None- if transaction.checkout_id:- source_object = Checkout.objects.filter(pk=transaction.checkout_id).first()- if not source_object:- # Prevent race condition between TransactionEventReport and checkout completion- source_object = order_models.Order.objects.filter(- pk__in=payment_models.TransactionItem.objects.filter(- pk=transaction.pk- ).values_list("order_id", flat=True)- ).first()+ source_object: Checkout | order_models.Order | None = get_source_object(+ transaction+ )if app_identifier and source_object:invalidate_cache_for_stored_payment_methods_if_needed(diff --git a/saleor/graphql/payment/tests/mutations/test_payment_capture.py b/saleor/graphql/payment/tests/mutations/test_payment_capture.pyindex 478dea67a3..a29752b4e2 100644--- a/saleor/graphql/payment/tests/mutations/test_payment_capture.py+++ b/saleor/graphql/payment/tests/mutations/test_payment_capture.py@@ -225,3 +225,36 @@ def test_payment_capture_gateway_dummy_credit_card_error(txn = payment.transactions.last()assert txn.kind == TransactionKind.CAPTUREassert not txn.is_success+++def test_payment_capture_marks_checkout_search_index_dirty(+ staff_api_client,+ permission_group_manage_orders,+ payment_txn_preauth,+ checkout_with_item,+):+ # given+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ payment = payment_txn_preauth+ payment.checkout = checkout_with_item+ payment.order = None+ payment.save(update_fields=["checkout", "order"])++ checkout_with_item.search_index_dirty = False+ checkout_with_item.save(update_fields=["search_index_dirty"])++ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ variables = {"paymentId": payment_id, "amount": str(payment.total)}++ # when+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["paymentCapture"]+ assert not data["errors"]+ payment.refresh_from_db()+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.search_index_dirty is Truediff --git a/saleor/graphql/payment/tests/mutations/test_payment_void.py b/saleor/graphql/payment/tests/mutations/test_payment_void.pyindex a1a6fe7ce0..f720005e56 100644--- a/saleor/graphql/payment/tests/mutations/test_payment_void.py+++ b/saleor/graphql/payment/tests/mutations/test_payment_void.py@@ -117,3 +117,36 @@ def test_payment_void_gateway_error(txn = payment_txn_preauth.transactions.last()assert txn.kind == TransactionKind.VOIDassert not txn.is_success+++def test_payment_void_marks_checkout_search_index_dirty(+ staff_api_client,+ permission_group_manage_orders,+ payment_txn_preauth,+ checkout_with_item,+):+ # given+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ payment = payment_txn_preauth+ payment.checkout = checkout_with_item+ payment.order = None+ payment.save(update_fields=["checkout", "order"])++ checkout_with_item.search_index_dirty = False+ checkout_with_item.save(update_fields=["search_index_dirty"])++ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ variables = {"paymentId": payment_id}++ # when+ response = staff_api_client.post_graphql(VOID_QUERY, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["paymentVoid"]+ assert not data["errors"]+ payment.refresh_from_db()+ assert payment.is_active is False+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.search_index_dirty is Truediff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.pyindex 2b72c82f02..90d0fd5ee8 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py@@ -1389,6 +1389,67 @@ def test_transaction_event_updates_checkout_last_transaction_modified_at(assert checkout.last_transaction_modified_at == transaction.modified_at+ "current_search_index_dirty",+ [False, True],+)+@freeze_time("2018-05-31 12:00:01")+def test_transaction_event_updates_checkout_search_index_dirty_flag(+ current_search_index_dirty,+ transaction_item_generator,+ app_api_client,+ permission_manage_payments,+ checkout_with_items,+):+ # given+ checkout = checkout_with_items+ checkout.search_index_dirty = current_search_index_dirty+ checkout.save(update_fields=["search_index_dirty"])++ psp_reference = "111-abc"+ amount = Decimal("11.00")+ transaction = transaction_item_generator(+ app=app_api_client.app, checkout_id=checkout.pk+ )+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,+ "amount": amount,+ "pspReference": psp_reference,+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal!+ $pspReference: String!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ ) {+ ...TransactionEventData+ }+ }+ """+ )+ # when+ response = app_api_client.post_graphql(+ query, variables, permissions=[permission_manage_payments]+ )++ # then+ get_graphql_content(response)+ checkout.refresh_from_db()++ assert checkout.search_index_dirty is True++@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")def test_transaction_event_updates_checkout_full_paid_with_charged_amount(diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex 8ef7eac96d..1136bdd4be 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -2393,6 +2393,62 @@ def test_updates_checkout_last_transaction_modified_at()+ "current_search_index_dirty",+ [True, False],+)[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_updates_checkout_search_index_dirty(+ mocked_initialize,+ current_search_index_dirty,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ plugins_manager,+):+ # given+ checkout = checkout_with_prices+ checkout.search_index_dirty = current_search_index_dirty+ checkout.save(update_fields=["search_index_dirty"])++ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)+ checkout_info, _ = fetch_checkout_data(+ checkout_info,+ plugins_manager,+ lines,+ )+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ variables = {+ "action": None,+ "amount": None,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionInitialize"]["errors"]+ checkout.refresh_from_db()+ assert checkout.search_index_dirty is True++@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")def test_for_locked_checkout(mocked_initialize,diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.pyindex dfb04a7519..e33a4d880b 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py@@ -2713,6 +2713,9 @@ def test_transaction_update_for_checkout_fully_paid()checkout = checkout_with_prices+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])+lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)@@ -2736,6 +2739,7 @@ def test_transaction_update_for_checkout_fully_paid(checkout.refresh_from_db()assert checkout.charge_status == CheckoutChargeStatus.FULLassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL+ assert checkout.search_index_dirty is Truemocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())@@ -2766,6 +2770,9 @@ def test_transaction_update_for_checkout_fully_authorized()checkout = checkout_with_prices+ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])+lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)@@ -2789,6 +2796,7 @@ def test_transaction_update_for_checkout_fully_authorized(checkout.refresh_from_db()assert checkout.charge_status == CheckoutChargeStatus.PARTIALassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL+ assert checkout.search_index_dirty is Truemocked_checkout_fully_paid.assert_not_called()mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())diff --git a/saleor/payment/tests/test_tasks.py b/saleor/payment/tests/test_tasks.pyindex f064f1a8aa..c5350a991a 100644--- a/saleor/payment/tests/test_tasks.py+++ b/saleor/payment/tests/test_tasks.py@@ -34,7 +34,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_last_chancharged_value=Decimal(100),)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)with freeze_time(time_before_ttl):@@ -71,7 +71,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_not_refundable(charged_value=Decimal(100),)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Falsecheckout.save(update_fields=["automatically_refundable", "last_change"])@@ -107,7 +107,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_tr_modificharged_value=Decimal(100),)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)with freeze_time(time_after_ttl):@@ -144,7 +144,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_none_status(charged_value=0,)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Truecheckout.save(update_fields=["automatically_refundable", "last_change"])@@ -271,7 +271,7 @@ def test_transaction_release_funds_for_checkout_task_refund_already_requested(last_refund_success=False,)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Truecheckout.save(update_fields=["automatically_refundable", "last_change"])@@ -308,7 +308,7 @@ def test_transaction_release_funds_for_checkout_task_cancel_already_requested(last_refund_success=False,)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Truecheckout.save(update_fields=["automatically_refundable", "last_change"])@@ -344,7 +344,7 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_authorizatauthorized_value=Decimal(100),)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Truecheckout.save(update_fields=["automatically_refundable", "last_change"])@@ -392,7 +392,7 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_charge(charged_value=Decimal(100),)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Truecheckout.save(update_fields=["automatically_refundable", "last_change"])@@ -446,7 +446,7 @@ def test_transactions_to_release_funds_setting_toogle(currency=current_checkout.channel.currency_code,)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, current_checkout, plugins_manager, user=None, app=None)current_checkout.automatically_refundable = Truecurrent_checkout.save(@@ -480,7 +480,7 @@ def test_transactions_to_release_funds_after_year(charged_value=Decimal(100),)transaction_amounts_for_checkout_updated(- transaction_item, plugins_manager, user=None, app=None+ transaction_item, checkout, plugins_manager, user=None, app=None)checkout.automatically_refundable = Truecheckout.created_at = ttl_time - datetime.timedelta(days=366)diff --git a/saleor/payment/tests/test_utils/test_utils.py b/saleor/payment/tests/test_utils/test_utils.pyindex 3934dad2b5..21bfa1b50b 100644--- a/saleor/payment/tests/test_utils/test_utils.py+++ b/saleor/payment/tests/test_utils/test_utils.py@@ -318,6 +318,77 @@ def test_create_transaction_event_from_request_and_webhook_response_with_psp_refassert TransactionEvent.objects.count() == 1+def test_create_transaction_event_with_psp_reference_checkout_search_index_dirty_updated(+ transaction_item_generator,+ checkout,+ app,+):+ # given++ transaction = transaction_item_generator(checkout_id=checkout.pk)+ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=Decimal(11.00),+ currency="USD",+ transaction_id=transaction.id,+ )+ expected_psp_reference = "psp:122:222"+ response_data = {"pspReference": expected_psp_reference}++ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])++ # when+ create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ request_event.refresh_from_db()+ assert request_event.psp_reference == expected_psp_reference+ assert request_event.include_in_calculations is True+ assert TransactionEvent.objects.count() == 1+ checkout.refresh_from_db()+ assert checkout.search_index_dirty is True+++def test_create_transaction_event_with_missing_psp_reference_checkout_search_index_dirty_not_updated(+ transaction_item_generator,+ checkout,+ app,+):+ # given+ transaction = transaction_item_generator(checkout_id=checkout.pk)+ amount = Decimal(11.00)+ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=amount,+ currency="USD",+ transaction_id=transaction.id,+ )++ checkout.search_index_dirty = False+ checkout.save(update_fields=["search_index_dirty"])++ response_data = {+ "amount": amount,+ "result": TransactionEventType.CHARGE_FAILURE.upper(),+ }++ # when+ create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ request_event.refresh_from_db()+ assert request_event.psp_reference is None+ assert request_event.include_in_calculations is False+ assert TransactionEvent.objects.count() == 2+ checkout.refresh_from_db()+ assert checkout.search_index_dirty is False++@pytest.mark.parametrize(("event_type", "result_event_type"),[diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 1e96743691..a97ade8f49 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -1272,21 +1272,19 @@ def _get_parsed_transaction_data_for_action_webhook(return transaction_request_response, None-def update_order_with_transaction_details(transaction: TransactionItem):- if transaction.order_id:- order = cast(Order, transaction.order)- update_order_search_vector(order, save=False)- updates_amounts_for_order(order, save=False)- order.save(- update_fields=[- "total_charged_amount",- "charge_status",- "updated_at",- "total_authorized_amount",- "authorize_status",- "search_vector",- ]- )+def update_order_with_transaction_details(order: Order):+ update_order_search_vector(order, save=False)+ updates_amounts_for_order(order, save=False)+ order.save(+ update_fields=[+ "total_charged_amount",+ "charge_status",+ "updated_at",+ "total_authorized_amount",+ "authorize_status",+ "search_vector",+ ]+ )def update_transaction_item_with_payment_method_details(@@ -1399,6 +1397,8 @@ def process_order_or_checkout_with_transaction(transaction_amounts_for_checkout_updated_without_price_recalculation(transaction, locked_checkout, manager, user, app)+ locked_checkout.search_index_dirty = True+ locked_checkout.save(update_fields=["search_index_dirty"])else:checkout_deleted = True# If the checkout was deleted, we still want to update the order associated with the transaction.@@ -1616,15 +1616,22 @@ def create_transaction_event_from_request_and_webhook_response("modified_at",])-- if transaction_item.order_id:+ manager = get_plugins_manager(allow_replica=True)+ source_object = get_source_object(transaction_item)+ if isinstance(source_object, Checkout):+ recalculate_refundable_for_checkout(transaction_item, request_event, event)+ transaction_amounts_for_checkout_updated(+ transaction_item, source_object, manager, app=app, user=None+ )+ # for transaction event only psp reference is indexed+ if psp_reference:+ mark_checkout_search_index_dirty(source_object)+ elif isinstance(source_object, Order):# circular importfrom ..order.actions import order_transaction_updated- manager = get_plugins_manager(allow_replica=False)- order = cast(Order, transaction_item.order)- order_info = fetch_order_info(order)- update_order_with_transaction_details(transaction_item)+ order_info = fetch_order_info(source_object)+ update_order_with_transaction_details(source_object)order_transaction_updated(order_info=order_info,transaction_item=transaction_item,@@ -1641,13 +1648,6 @@ def create_transaction_event_from_request_and_webhook_response()calculate_order_granted_refund_status(granted_refund)- elif transaction_item.checkout_id:- manager = get_plugins_manager(allow_replica=True)- recalculate_refundable_for_checkout(transaction_item, request_event, event)- transaction_amounts_for_checkout_updated(- transaction_item, manager, app=app, user=None- )- source_object = transaction_item.checkout or transaction_item.orderif event and source_object and app:invalidate_cache_for_stored_payment_methods_if_needed(event, source_object, app.identifier@@ -1655,6 +1655,26 @@ def create_transaction_event_from_request_and_webhook_response(return event+def get_source_object(+ transaction_item: TransactionItem,+) -> Checkout | Order | None:+ source_object: Checkout | Order | None = None+ if transaction_item.checkout_id:+ source_object = Checkout.objects.filter(pk=transaction_item.checkout_id).first()+ if not source_object:+ source_object = Order.objects.filter(+ pk__in=TransactionItem.objects.filter(pk=transaction_item.pk).values_list(+ "order_id", flat=True+ )+ ).first()+ return source_object+++def mark_checkout_search_index_dirty(checkout: Checkout):+ checkout.search_index_dirty = True+ checkout.safe_update(update_fields=["search_index_dirty"])++def _prepare_manual_event(transaction: TransactionItem,transaction_amount: Decimal,@@ -1910,6 +1930,10 @@ def handle_transaction_initialize_session(source_object,app.identifier, # type: ignore[union-attr])+ if isinstance(source_object, Checkout):+ # new transaction created, so we need to mark the checkout search index as dirty+ source_object.search_index_dirty = True+ source_object.safe_update(update_fields=["search_index_dirty"])data_to_return = response_data.get("data") if response_data else Nonereturn created_event.transaction, created_event, data_to_return@@ -1949,6 +1973,9 @@ def handle_transaction_process_session(invalidate_cache_for_stored_payment_methods_if_needed(created_event, source_object, app.identifier)+ if isinstance(source_object, Checkout):+ source_object.search_index_dirty = True+ source_object.safe_update(update_fields=["search_index_dirty"])data_to_return = response_data.get("data") if response_data else Nonereturn created_event, data_to_returndiff --git a/saleor/settings.py b/saleor/settings.pyindex 13950a4d42..ecde78f7d2 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -35,6 +35,7 @@ from .core.languages import LANGUAGES as CORE_LANGUAGESfrom .core.rlimit import validate_and_set_rlimitfrom .core.schedules import (initiated_checkout_automatic_completion_schedule,+ initiated_checkout_search_update_schedule,initiated_gift_card_search_update_schedule,initiated_page_search_update_schedule,initiated_product_search_update_schedule,@@ -718,6 +719,12 @@ CELERY_BEAT_SCHEDULE = {# requiring a search index rebuild."schedule": initiated_page_search_update_schedule,},+ "update-checkouts-search-vectors": {+ "task": "saleor.checkout.tasks.update_checkouts_search_vector_task",+ # Scheduled task that runs every 60 seconds to check for checkouts+ # requiring a search index rebuild.+ "schedule": initiated_checkout_search_update_schedule,+ },"expire-orders": {"task": "saleor.order.tasks.expire_orders_task","schedule": BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA,@@ -969,7 +976,6 @@ AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED = datetime.timedelta())-# The maximum SearchVector expression count allowed per index SQL statement# If the count is exceeded, the expression list will be truncatedINDEX_MAXIMUM_EXPR_COUNT = 4000@@ -994,6 +1000,17 @@ PAGE_MAX_INDEXED_ATTRIBUTE_VALUES = 100# Maximum related objects that can be indexed in a gift cardGIFT_CARD_MAX_INDEXED_TAGS = 100+# Maximum related objects that can be indexed in a checkout+CHECKOUT_MAX_INDEXED_LINES = 100+CHECKOUT_MAX_INDEXED_TRANSACTIONS = 20+CHECKOUT_MAX_INDEXED_PAYMENTS = 20++# Number of parallel tasks to spawn for updating checkout search vectors.+# Each task processes a batch of checkouts concurrently to improve throughput.+CHECKOUT_SEARCH_UPDATE_PARALLEL_TASKS = int(+ os.environ.get("CHECKOUT_SEARCH_UPDATE_PARALLEL_TASKS", 5)+)+# Patch SubscriberExecutionContext class from `graphql-core-legacy` package# to fix bug causing not returning errors for subscription queries.