Skip to content

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

Extend order search (#17840)

Iga Karbowiak4815c5498511
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c4cfb806e..a8eb477da7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,12 @@ All notable, unreleased changes to this project will be documented in this file.
- Filter by order by associated lines metadata.
- Filter by the product type of related order lines.
- Extend the `Page` type with an `attribute` field. Adds support for querying a specific attribute on a page by `slug`, returning the matching attribute and its assigned values, or null if no match is found.
+- Enhanced order search options. Orders can now be searched using:
+ - The order's ID
+ - IDs of invoices linked to the order
+ - Messages from related order events
+ - The content of customer note
+ - The order external reference
### Webhooks
diff --git a/saleor/account/search.py b/saleor/account/search.py
index 4599ffa2c3..55f5f237e7 100644
--- a/saleor/account/search.py
+++ b/saleor/account/search.py
@@ -72,36 +72,51 @@ def generate_address_search_vector_value(
Value(address.street_address_1),
Value(address.country.name),
Value(address.country.code),
+ config="simple",
weight=weight,
- )
+ ),
]
if address.company_name:
search_vectors.append(
- NoValidationSearchVector(Value(address.company_name), weight=weight)
+ NoValidationSearchVector(
+ Value(address.company_name), config="simple", weight=weight
+ )
)
if address.country_area:
search_vectors.append(
- NoValidationSearchVector(Value(address.country_area), weight=weight)
+ NoValidationSearchVector(
+ Value(address.country_area), config="simple", weight=weight
+ )
)
if address.city:
search_vectors.append(
- NoValidationSearchVector(Value(address.city), weight=weight)
+ NoValidationSearchVector(
+ Value(address.city), config="simple", weight=weight
+ )
)
if address.city_area:
search_vectors.append(
- NoValidationSearchVector(Value(address.city_area), weight=weight)
+ NoValidationSearchVector(
+ Value(address.city_area), config="simple", weight=weight
+ )
)
if address.street_address_2:
search_vectors.append(
- NoValidationSearchVector(Value(address.street_address_2), weight=weight)
+ NoValidationSearchVector(
+ Value(address.street_address_2), config="simple", weight=weight
+ )
)
if address.postal_code:
search_vectors.append(
- NoValidationSearchVector(Value(address.postal_code), weight=weight)
+ NoValidationSearchVector(
+ Value(address.postal_code), config="simple", weight=weight
+ )
)
if address.phone:
search_vectors.append(
- NoValidationSearchVector(Value(address.phone.as_e164), weight=weight)
+ NoValidationSearchVector(
+ Value(address.phone.as_e164), config="simple", weight=weight
+ )
)
return search_vectors
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index a38fa62892..d75bc58cfe 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -92,6 +92,7 @@ def test_create_order_captured_payment_creates_expected_events(
manager=manager,
)
+ order.refresh_from_db()
(
order_placed_event,
payment_captured_event,
@@ -256,6 +257,7 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(
manager=manager,
)
+ order.refresh_from_db()
(
order_placed_event,
payment_captured_event,
@@ -415,6 +417,7 @@ def test_create_order_preauth_payment_creates_expected_events(
manager=manager,
)
+ order.refresh_from_db()
(
order_placed_event,
payment_authorized_event,
@@ -531,6 +534,7 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
manager=manager,
)
+ order.refresh_from_db()
(
order_placed_event,
payment_captured_event,
@@ -1308,6 +1312,7 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(
app=app,
)
+ order.refresh_from_db()
(
order_marked_as_paid,
order_placed_event,
diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.py
index 6880c3cd66..cba7a47b15 100644
--- a/saleor/core/search_tasks.py
+++ b/saleor/core/search_tasks.py
@@ -1,5 +1,8 @@
+from typing import Any
+
from celery.utils.log import get_task_logger
from django.conf import settings
+from django.db import transaction
from ..account.models import User
from ..account.search import prepare_user_search_document_value
@@ -16,6 +19,8 @@ from .postgres import FlatConcatSearchVector
task_logger = get_task_logger(__name__)
+ORDER_BATCH_SIZE = 100
+
BATCH_SIZE = 500
# Based on local testing, 500 should be a good balance between performance
# total time and memory usage. Should be tested after some time and adjusted by
@@ -53,39 +58,64 @@ def set_user_search_document_values(updated_count: int = 0) -> None:
@app.task
-def set_order_search_document_values(updated_count: int = 0) -> None:
- orders = list(
- Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
- .filter(search_vector=None)
- .prefetch_related(
- "user",
- "billing_address",
- "shipping_address",
- "payments",
- "discounts",
- "lines",
- )
- .order_by("-number")[:BATCH_SIZE]
+def set_order_search_document_values(
+ update_all: bool = False,
+ database_connection_name: str = settings.DATABASE_CONNECTION_REPLICA_NAME,
+ updated_count: int = 0,
+ order_number: int = 0,
+) -> None:
+ """Update search document values for orders.
+
+ If `update_all` is False, it will update only orders with search_vector=None.
+ """
+ lookup: dict[str, Any] = {"number__gte": order_number}
+ if not update_all:
+ lookup["search_vector"] = None
+
+ orders_qs = (
+ Order.objects.using(database_connection_name)
+ .filter(**lookup)
+ .order_by("number")
)
- if not orders:
+ numbers = list(orders_qs.values_list("number", flat=True)[:ORDER_BATCH_SIZE])
+ if not numbers:
task_logger.info("No orders to update.")
return
with allow_writer():
- updated_count += set_search_vector_values(
- orders, prepare_order_search_vector_value
+ orders = (
+ Order.objects.filter(number__in=numbers)
+ .prefetch_related(
+ "user",
+ "billing_address",
+ "shipping_address",
+ "payments",
+ "discounts",
+ "lines",
+ "payment_transactions__events",
+ "invoices",
+ "events",
+ )
+ .order_by("pk")
)
+ with transaction.atomic():
+ _orders_lock = list(orders.select_for_update(of=(["self"])))
+ updated_count += set_search_vector_values(
+ list(orders), prepare_order_search_vector_value
+ )
task_logger.info("Updated %d orders", updated_count)
- if len(orders) < BATCH_SIZE:
+ if len(numbers) < ORDER_BATCH_SIZE:
task_logger.info("Setting order search document values finished.")
return
del orders
- set_order_search_document_values.delay(updated_count)
+ set_order_search_document_values.delay(
+ update_all, database_connection_name, updated_count, order_number=numbers[-1]
+ )
@app.task
diff --git a/saleor/graphql/invoice/mutations/invoice_create.py b/saleor/graphql/invoice/mutations/invoice_create.py
index 0b6e8dbe47..c37c324449 100644
--- a/saleor/graphql/invoice/mutations/invoice_create.py
+++ b/saleor/graphql/invoice/mutations/invoice_create.py
@@ -5,6 +5,7 @@ from ....core import JobStatus
from ....invoice import events, models
from ....invoice.error_codes import InvoiceErrorCode
from ....order import events as order_events
+from ....order.search import update_order_search_vector
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -134,4 +135,5 @@ class InvoiceCreate(DeprecatedModelMutation):
app=app,
invoice_number=cleaned_input["number"],
)
+ update_order_search_vector(order)
return InvoiceCreate(invoice=invoice)
diff --git a/saleor/graphql/invoice/mutations/invoice_delete.py b/saleor/graphql/invoice/mutations/invoice_delete.py
index b00e708a1c..a41bb7e930 100644
--- a/saleor/graphql/invoice/mutations/invoice_delete.py
+++ b/saleor/graphql/invoice/mutations/invoice_delete.py
@@ -1,6 +1,7 @@
import graphene
from ....invoice import events, models
+from ....order.search import update_order_search_vector
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -24,10 +25,12 @@ class InvoiceDelete(ModelDeleteMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
invoice = cls.get_instance(info, **data)
- cls.check_channel_permissions(info, [invoice.order.channel_id])
+ order = invoice.order
+ cls.check_channel_permissions(info, [order.channel_id])
response = super().perform_mutation(_root, info, **data)
app = get_app_promise(info.context).get()
events.invoice_deleted_event(
user=info.context.user, app=app, invoice_id=invoice.pk
)
+ update_order_search_vector(order)
return response
diff --git a/saleor/graphql/invoice/tests/test_invoice_create.py b/saleor/graphql/invoice/tests/test_invoice_create.py
index 044540478e..36a6e2a215 100644
--- a/saleor/graphql/invoice/tests/test_invoice_create.py
+++ b/saleor/graphql/invoice/tests/test_invoice_create.py
@@ -89,6 +89,8 @@ def test_create_invoice(staff_api_client, permission_group_manage_orders, order)
user=staff_api_client.user,
parameters__invoice_number=number,
).exists()
+ order.refresh_from_db()
+ assert order.search_vector
def test_create_invoice_by_user_no_channel_access(
@@ -161,6 +163,8 @@ def test_create_invoice_by_app(app_api_client, permission_manage_orders, order):
app=app_api_client.app,
parameters__invoice_number=number,
).exists()
+ order.refresh_from_db()
+ assert order.search_vector
def test_create_invoice_no_billing_address(
diff --git a/saleor/graphql/invoice/tests/test_invoice_delete.py b/saleor/graphql/invoice/tests/test_invoice_delete.py
index 10d75f5078..e31b450a39 100644
--- a/saleor/graphql/invoice/tests/test_invoice_delete.py
+++ b/saleor/graphql/invoice/tests/test_invoice_delete.py
@@ -38,6 +38,8 @@ def test_invoice_delete(staff_api_client, permission_group_manage_orders, order)
user=staff_api_client.user,
parameters__invoice_id=invoice.id,
).exists()
+ order.refresh_from_db()
+ assert order.search_vector
def test_invoice_delete_by_user_no_channel_access(
@@ -79,6 +81,8 @@ def test_invoice_delete_by_app(app_api_client, permission_manage_orders, order):
app=app_api_client.app,
parameters__invoice_id=invoice.id,
).exists()
+ order.refresh_from_db()
+ assert order.search_vector
@patch("saleor.plugins.manager.PluginsManager.invoice_delete")
diff --git a/saleor/graphql/order/mutations/order_note_add.py b/saleor/graphql/order/mutations/order_note_add.py
index 8f6def88ef..cddbd7e8b4 100644
--- a/saleor/graphql/order/mutations/order_note_add.py
+++ b/saleor/graphql/order/mutations/order_note_add.py
@@ -2,6 +2,7 @@ import graphene
from django.db import transaction
from ....order import error_codes, events
+from ....order.search import update_order_search_vector
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -58,6 +59,7 @@ class OrderNoteAdd(OrderNoteCommon):
message=cleaned_input["message"],
)
call_event_by_order_status(order, manager)
+ update_order_search_vector(order)
return OrderNoteAdd(
order=SyncWebhookControlContext(order),
event=SyncWebhookControlContext(event),
diff --git a/saleor/graphql/order/mutations/order_note_update.py b/saleor/graphql/order/mutations/order_note_update.py
index aa17e045c1..cd9a8ee760 100644
--- a/saleor/graphql/order/mutations/order_note_update.py
+++ b/saleor/graphql/order/mutations/order_note_update.py
@@ -2,6 +2,7 @@ import graphene
from django.db import transaction
from ....order import OrderEvents, error_codes, events, models
+from ....order.search import update_order_search_vector
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -64,6 +65,7 @@ class OrderNoteUpdate(OrderNoteCommon):
related_event=order_event_to_update,
)
call_event_by_order_status(order, manager)
+ update_order_search_vector(order)
return OrderNoteUpdate(
order=SyncWebhookControlContext(order),
event=SyncWebhookControlContext(event),
diff --git a/saleor/graphql/order/tests/mutations/test_order_note_add.py b/saleor/graphql/order/tests/mutations/test_order_note_add.py
index 0842dacc23..f2cbc511b8 100644
--- a/saleor/graphql/order/tests/mutations/test_order_note_add.py
+++ b/saleor/graphql/order/tests/mutations/test_order_note_add.py
@@ -68,6 +68,7 @@ def test_order_note_add_as_staff_user(
order.refresh_from_db()
assert order.status == OrderStatus.UNFULFILLED
+ assert order.search_vector
# Ensure the correct order event was created
event = order.events.get()
diff --git a/saleor/graphql/order/tests/mutations/test_order_note_update.py b/saleor/graphql/order/tests/mutations/test_order_note_update.py
index 731b382171..06aa58bc60 100644
--- a/saleor/graphql/order/tests/mutations/test_order_note_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_note_update.py
@@ -79,6 +79,7 @@ def test_order_note_update_as_staff_user(
order.refresh_from_db()
assert order.status == OrderStatus.UNFULFILLED
+ assert order.search_vector
assert OrderEvent.objects.filter(order=order).count() == 2
new_note = OrderEvent.objects.filter(order=order).exclude(pk=note.pk).get()
diff --git a/saleor/graphql/order/tests/queries/test_orders.py b/saleor/graphql/order/tests/queries/test_orders.py
index 4173664b6b..4664e84bc4 100644
--- a/saleor/graphql/order/tests/queries/test_orders.py
+++ b/saleor/graphql/order/tests/queries/test_orders.py
@@ -1,19 +1,12 @@
from decimal import Decimal
from unittest.mock import patch
-import pytest
-from prices import Money, TaxedMoney
-
-from .....core.postgres import FlatConcatSearchVector
-from .....discount.models import OrderDiscount
from .....order import OrderStatus
from .....order.events import (
draft_order_created_from_replace_event,
fulfillment_fulfilled_items_event,
order_added_products_event,
)
-from .....order.models import Order, Payment
-from .....order.search import prepare_order_search_vector_value
from .....plugins.manager import PluginsManager
from .....tax.calculations.order import update_order_prices_with_flat_rates
from ....tests.utils import get_graphql_content
@@ -260,126 +253,3 @@ def test_query_orders_with_active_filter_shipping_methods_webhook(
assert not order_with_lines.should_refresh_prices
assert order_with_lines.total_gross_amount != Decimal(0)
mocked_webhook_handler.assert_not_called()
-
-
-ORDERS_QUERY_WITH_SEARCH = """
- query ($search: String) {
- orders(first: 10, search:$search) {
- totalCount
- edges {
- node {
- id
- }
- }
- }
- }
-"""
-
-
- ("search_value", "count"),
- [
- ("discount name", 2),
- ("Some other", 1),
- ("translated", 1),
- ("Leslie", 1),
- ("Wade", 1),
- ("", 3),
- ("ExternalID", 1),
- ("SKU_A", 1),
- ],
-)
-def test_orders_query_with_search(
- search_value,
- count,
- staff_api_client,
- permission_group_manage_orders,
- customer_user,
- channel_USD,
- product,
- variant,
-):
- # given
- orders = Order.objects.bulk_create(
- [
- Order(
- user=customer_user,
- user_email="[email protected]",
- channel=channel_USD,
- lines_count=0,
- ),
- Order(
- user_email="[email protected]",
- channel=channel_USD,
- lines_count=0,
- ),
- Order(
- user_email="[email protected]",
- channel=channel_USD,
- lines_count=0,
- ),
- ]
- )
-
- OrderDiscount.objects.bulk_create(
- [
- OrderDiscount(
- order=orders[0],
- name="Some discount name",
- value=Decimal("1"),
- amount_value=Decimal("1"),
- translated_name="translated",
- ),
- OrderDiscount(
- order=orders[2],
- name="Some other discount name",
- value=Decimal("10"),
- amount_value=Decimal("10"),
- translated_name="PL_name",
- ),
- ]
- )
- order_with_payment = orders[1]
- payment = Payment.objects.create(
- order=order_with_payment, psp_reference="ExternalID"
- )
- payment.transactions.create(gateway_response={}, is_success=True)
-
- order_with_orderline = orders[2]
- channel = order_with_orderline.channel
- channel_listing = variant.channel_listings.get(channel=channel)
- net = variant.get_price(channel_listing)
- currency = net.currency
- gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
- unit_price = TaxedMoney(net=net, gross=gross)
- order_with_orderline.lines.create(
- product_name=str(product),
- variant_name=str(variant),
- product_sku=variant.sku,
- product_variant_id=variant.get_global_id(),
- is_shipping_required=variant.is_shipping_required(),
- is_gift_card=variant.is_gift_card(),
- quantity=3,
- variant=variant,
- unit_price=unit_price,
- total_price=unit_price * 3,
- undiscounted_unit_price=unit_price,
- undiscounted_total_price=unit_price * 3,
- tax_rate=Decimal("0.23"),
- )
- for order in orders:
- order.search_vector = FlatConcatSearchVector(
- *prepare_order_search_vector_value(order)
- )
- Order.objects.bulk_update(orders, ["search_vector"])
-
- variables = {"search": search_value}
- permission_group_manage_orders.user_set.add(staff_api_client.user)
-
- # when
- response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
-
- # then
- content = get_graphql_content(response)
- assert content["data"]["orders"]["totalCount"] == count
diff --git a/saleor/graphql/order/tests/queries/test_orders_search.py b/saleor/graphql/order/tests/queries/test_orders_search.py
new file mode 100644
index 0000000000..fccf9bcec7
--- /dev/null
+++ b/saleor/graphql/order/tests/queries/test_orders_search.py
@@ -0,0 +1,536 @@
+from decimal import Decimal
+
+import graphene
+import pytest
+from prices import Money, TaxedMoney
+
+from .....core.postgres import FlatConcatSearchVector
+from .....discount.models import OrderDiscount
+from .....invoice.models import Invoice
+from .....order import OrderEvents
+from .....order.models import Order, Payment
+from .....order.search import prepare_order_search_vector_value
+from ....tests.utils import get_graphql_content
+
+ORDERS_QUERY_WITH_SEARCH = """
+ query ($search: String) {
+ orders(first: 10, search:$search) {
+ totalCount
+ edges {
+ node {
+ id
+ number
+ }
+ }
+ }
+ }
+"""
+
+
+def update_orders_search_vector(orders):
+ for order in orders:
+ order.search_vector = FlatConcatSearchVector(
+ *prepare_order_search_vector_value(order)
+ )
+ Order.objects.bulk_update(orders, ["search_vector"])
+
+
+ ("search_value", "count"),
+ [
+ ("discount name", 2),
+ ("Some other", 1),
+ ("translated", 1),
+ ("Leslie", 1),
+ ("Wade", 1),
+ ("Leslie Wade", 1),
+ ("", 3),
+ ("ExternalID", 1),
+ ("SKU_A", 1),
+ ],
+)
+def test_orders_query_with_search(
+ search_value,
+ count,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ channel_USD,
+ product,
+ variant,
+):
+ # given
+ orders = Order.objects.bulk_create(
+ [
+ Order(
+ user=customer_user,
+ user_email="[email protected]",
+ channel=channel_USD,
+ lines_count=0,
+ ),
+ Order(
+ user_email="[email protected]",
+ channel=channel_USD,
+ lines_count=0,
+ ),
+ Order(
+ user_email="[email protected]",
+ channel=channel_USD,
+ lines_count=0,
+ ),
+ ]
+ )
+
+ OrderDiscount.objects.bulk_create(
+ [
+ OrderDiscount(
+ order=orders[0],
+ name="Some discount name",
+ value=Decimal("1"),
+ amount_value=Decimal("1"),
+ translated_name="translated",
+ ),
+ OrderDiscount(
+ order=orders[2],
+ name="Some other discount name",
+ value=Decimal("10"),
+ amount_value=Decimal("10"),
+ translated_name="PL_name",
+ ),
+ ]
+ )
+ order_with_payment = orders[1]
+ payment = Payment.objects.create(
+ order=order_with_payment, psp_reference="ExternalID"
+ )
+ payment.transactions.create(gateway_response={}, is_success=True)
+
+ order_with_orderline = orders[2]
+ channel = order_with_orderline.channel
+ channel_listing = variant.channel_listings.get(channel=channel)
+ net = variant.get_price(channel_listing)
+ currency = net.currency
+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
+ unit_price = TaxedMoney(net=net, gross=gross)
+ order_with_orderline.lines.create(
+ product_name=str(product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=3,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * 3,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * 3,
+ tax_rate=Decimal("0.23"),
+ )
+
+ update_orders_search_vector(orders)
+
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == count
+
+
+def test_orders_query_with_search_by_order_id(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+):
+ # given
+ update_orders_search_vector(order_list)
+
+ search_value = graphene.Node.to_global_id("Order", order_list[1].pk)
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+ assert content["data"]["orders"]["edges"][0]["node"]["id"] == search_value
+
+
+def test_orders_query_with_search_by_invoice_id(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+):
+ # given
+ invoices = Invoice.objects.bulk_create(
+ [Invoice(order=order, number=f"INV-{order.pk}") for order in order_list]
+ )
+ update_orders_search_vector(order_list)
+
+ search_value = graphene.Node.to_global_id("Invoice", invoices[2].pk)
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+ assert content["data"]["orders"]["edges"][0]["node"][
+ "id"
+ ] == graphene.Node.to_global_id("Order", order_list[2].pk)
+
+
+def test_orders_query_with_search_by_order_event_message(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+):
+ # given
+ event_message = "Special event message for search"
+ order = order_list[0]
+ order.events.create(
+ type=OrderEvents.NOTE_ADDED,
+ user=None,
+ parameters={"message": event_message},
+ )
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": "Special event message"}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+ assert content["data"]["orders"]["edges"][0]["node"][
+ "id"
+ ] == graphene.Node.to_global_id("Order", order_list[0].pk)
+
+
+ ("search_value", "expected_count"),
+ [
+ ("match in", 1),
+ ("note", 2),
+ ("partial", 1),
+ ("unrelated", 0),
+ ],
+)
+def test_orders_query_with_search_by_partial_customer_note(
+ search_value,
+ expected_count,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+):
+ # given
+ notes = [
+ "This is a match in the customer note",
+ "This note has a partial match",
+ "",
+ ]
+ for order, note in zip(order_list, notes, strict=True):
+ order.customer_note = note
+
+ Order.objects.bulk_update(order_list, ["customer_note"])
+ update_orders_search_vector(order_list)
+
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == expected_count
+
+
+def test_orders_query_with_search_by_product_name(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ product,
+ variant,
+):
+ # given
+ order = order_list[0]
+ channel = order.channel
+ channel_listing = variant.channel_listings.get(channel=channel)
+ net = variant.get_price(channel_listing)
+ currency = net.currency
+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
+ unit_price = TaxedMoney(net=net, gross=gross)
+ product_name = str(product)
+ order.lines.create(
+ product_name=product_name,
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=2,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * 2,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * 2,
+ tax_rate=Decimal("0.23"),
+ )
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": product_name}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+ assert content["data"]["orders"]["edges"][0]["node"][
+ "id"
+ ] == graphene.Node.to_global_id("Order", order.pk)
+
+
+def test_orders_query_with_search_by_variant_name(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ product,
+ variant,
+):
+ # given
+ order = order_list[1]
+ channel = order.channel
+ channel_listing = variant.channel_listings.get(channel=channel)
+ net = variant.get_price(channel_listing)
+ currency = net.currency
+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
+ unit_price = TaxedMoney(net=net, gross=gross)
+ variant_name = str(variant)
+ order.lines.create(
+ product_name=str(product),
+ variant_name=variant_name,
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=1,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price,
+ tax_rate=Decimal("0.23"),
+ )
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": variant_name}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+ assert content["data"]["orders"]["edges"][0]["node"][
+ "id"
+ ] == graphene.Node.to_global_id("Order", order.pk)
+
+
+def test_orders_query_with_search_by_product_sku(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ product,
+ variant,
+):
+ # given
+ order = order_list[2]
+ channel = order.channel
+ channel_listing = variant.channel_listings.get(channel=channel)
+ net = variant.get_price(channel_listing)
+ currency = net.currency
+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
+ unit_price = TaxedMoney(net=net, gross=gross)
+ sku = variant.sku
+ order.lines.create(
+ product_name=str(product),
+ variant_name=str(variant),
+ product_sku=sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=4,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * 4,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * 4,
+ tax_rate=Decimal("0.23"),
+ )
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": sku}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+ assert content["data"]["orders"]["edges"][0]["node"][
+ "id"
+ ] == graphene.Node.to_global_id("Order", order.pk)
+
+
+ ("search_value", "expected_count"),
+ [
+ ("First", 1),
+ ("Last", 1),
+ ("First Last", 1),
+ ("Billing Street", 1),
+ ("PL", 1),
+ ("US", 2),
+ ("Nonexistent", 0),
+ ],
+)
+def test_orders_query_with_search_by_billing_address_fields(
+ search_value,
+ expected_count,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ address,
+ address_usa,
+):
+ # given
+ order = order_list[0]
+ address.first_name = "First"
+ address.last_name = "Last"
+ address.street_address_1 = "Billing Street"
+ address.country = "PL"
+ address.save()
+
+ order.billing_address = address
+ for order in order_list[1:]:
+ order.billing_address = address_usa
+ Order.objects.bulk_update(order_list, ["billing_address"])
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == expected_count
+
+
+ ("search_value", "expected_count"),
+ [
+ ("First", 1),
+ ("Last", 1),
+ ("First Last", 1),
+ ("Shipping Street", 1),
+ ("JP", 1),
+ ("US", 2),
+ ("Nonexistent", 0),
+ ],
+)
+def test_orders_query_with_search_by_shipping_address_fields(
+ search_value,
+ expected_count,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ address,
+ address_usa,
+):
+ # given
+ order = order_list[0]
+ address.first_name = "First"
+ address.last_name = "Last"
+ address.street_address_1 = "Shipping Street"
+ address.country = "JP"
+ address.save()
+
+ order.shipping_address = address
+ for order in order_list[1:]:
+ order.shipping_address = address_usa
+ Order.objects.bulk_update(order_list, ["shipping_address"])
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == expected_count
+
+
+ ("search_value", "expected_order_idxes"),
+ [
+ ("EXT-REF-12345", [0]),
+ ("REF", [0, 1]),
+ ("ANOTHER-REF-67890", [1]),
+ ("nonexistent-ref", []),
+ ],
+)
+def test_orders_query_with_search_by_external_reference(
+ search_value,
+ expected_order_idxes,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+):
+ # given
+ external_references = ["EXT-REF-12345", "ANOTHER-REF-67890", ""]
+ for order, ext_ref in zip(order_list, external_references, strict=True):
+ order.external_reference = ext_ref
+ Order.objects.bulk_update(order_list, ["external_reference"])
+
+ update_orders_search_vector(order_list)
+
+ variables = {"search": search_value}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_SEARCH, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == len(expected_order_idxes)
+ returned_numbers = [
+ edge["node"]["number"] for edge in content["data"]["orders"]["edges"]
+ ]
+ expected_numbers = [str(order_list[idx].number) for idx in expected_order_idxes]
+ assert set(returned_numbers) == set(expected_numbers)
diff --git a/saleor/order/migrations/0213_auto_20250618_1246.py b/saleor/order/migrations/0213_auto_20250618_1246.py
new file mode 100644
index 0000000000..6b1706f611
--- /dev/null
+++ b/saleor/order/migrations/0213_auto_20250618_1246.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.1 on 2025-06-18 12:46
+
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from ...core.search_tasks import set_order_search_document_values
+
+
+def update_order_search_vector(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ set_order_search_document_values.delay()
+
+ sender = registry.get_app_config("order")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0212_orderline_product_type_id_btree_idx"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ update_order_search_vector,
+ reverse_code=migrations.RunPython.noop,
+ )
+ ]
diff --git a/saleor/order/search.py b/saleor/order/search.py
index 35a0873078..8f5cb90b9f 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -7,6 +7,7 @@ from django.db.models import F, Q, Value, prefetch_related_objects
from ..account.search import generate_address_search_vector_value
from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector
+from . import OrderEvents
if TYPE_CHECKING:
from django.db.models import QuerySet
@@ -35,9 +36,16 @@ def prepare_order_search_vector_value(
"discounts",
"lines",
"payment_transactions__events",
+ "invoices",
+ "events",
)
search_vectors = [
- NoValidationSearchVector(Value(str(order.number)), config="simple", weight="A")
+ NoValidationSearchVector(Value(str(order.number)), config="simple", weight="A"),
+ NoValidationSearchVector(
+ Value(graphene.Node.to_global_id("Order", order.id)),
+ config="simple",
+ weight="A",
+ ),
]
if order.user_email:
search_vectors.append(
@@ -64,6 +72,13 @@ def prepare_order_search_vector_value(
)
)
+ if order.customer_note:
+ search_vectors.append(
+ NoValidationSearchVector(
+ Value(order.customer_note), config="simple", weight="B"
+ )
+ )
+
if order.billing_address:
search_vectors += generate_address_search_vector_value(
order.billing_address, weight="B"
@@ -72,11 +87,19 @@ def prepare_order_search_vector_value(
search_vectors += generate_address_search_vector_value(
order.shipping_address, weight="B"
)
+ if order.external_reference:
+ search_vectors.append(
+ NoValidationSearchVector(
+ Value(order.external_reference), config="simple", weight="B"
+ )
+ )
search_vectors += generate_order_payments_search_vector_value(order)
search_vectors += generate_order_discounts_search_vector_value(order)
search_vectors += generate_order_lines_search_vector_value(order)
search_vectors += generate_order_transactions_search_vector_value(order)
+ search_vectors += generate_order_invoices_search_vector_value(order)
+ search_vectors += generate_order_events_search_vector_value(order)
return search_vectors
@@ -213,6 +236,42 @@ def generate_order_lines_search_vector_value(
return line_vectors
+def generate_order_invoices_search_vector_value(
+ order: "Order",
+) -> list[NoValidationSearchVector]:
+ invoice_vectors = []
+ for invoice in order.invoices.all().order_by("-created_at")[
+ : settings.SEARCH_ORDERS_MAX_INDEXED_INVOICES
+ ]:
+ invoice_vectors.append(
+ NoValidationSearchVector(
+ Value(graphene.Node.to_global_id("Invoice", invoice.id)),
+ config="simple",
+ weight="D",
+ )
+ )
+ return invoice_vectors
+
+
+def generate_order_events_search_vector_value(
+ order: "Order",
+) -> list[NoValidationSearchVector]:
+ event_vectors = []
+ events = order.events.filter(
+ type__in=[OrderEvents.NOTE_ADDED, OrderEvents.NOTE_UPDATED]
+ ).order_by("-date")
+ for event in events[: settings.SEARCH_ORDERS_MAX_INDEXED_EVENTS]:
+ if message := event.parameters.get("message"):
+ event_vectors.append(
+ NoValidationSearchVector(
+ Value(message),
+ config="simple",
+ weight="D",
+ )
+ )
+ return event_vectors
+
+
def search_orders(qs: "QuerySet[Order]", value) -> "QuerySet[Order]":
if value:
query = SearchQuery(value, search_type="websearch", config="simple")
diff --git a/saleor/settings.py b/saleor/settings.py
index 2681e8d31e..75698bcbdd 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -928,6 +928,8 @@ SEARCH_ORDERS_MAX_INDEXED_TRANSACTIONS = 20
SEARCH_ORDERS_MAX_INDEXED_PAYMENTS = 20
SEARCH_ORDERS_MAX_INDEXED_DISCOUNTS = 20
SEARCH_ORDERS_MAX_INDEXED_LINES = 100
+SEARCH_ORDERS_MAX_INDEXED_INVOICES = 20
+SEARCH_ORDERS_MAX_INDEXED_EVENTS = 50
# Maximum related objects that can be indexed in a product
PRODUCT_MAX_INDEXED_ATTRIBUTES = 1000