Skip to content

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

Fix order search (#8680)

Iga Karbowiakd908e8308a12
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index af3401aca7..0865a39667 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -32,6 +32,7 @@ from ..order import OrderLineData, OrderOrigin, OrderStatus
from ..order.actions import order_created
from ..order.models import Order, OrderLine
from ..order.notifications import send_order_confirmation
+from ..order.search import prepare_order_search_document_value
from ..payment import PaymentError, gateway
from ..payment.models import Payment, Transaction
from ..payment.utils import fetch_customer_id, store_customer_id
@@ -451,6 +452,7 @@ def _create_order(
order.redirect_url = checkout.redirect_url
order.private_metadata = checkout.private_metadata
order.update_total_paid()
+ order.search_document = prepare_order_search_document_value(order)
order.save()
if site_settings.automatically_fulfill_non_shippable_gift_card:
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 7254d410bb..23ce7919d7 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -56,6 +56,7 @@ from ...giftcard.models import GiftCard
from ...menu.models import Menu
from ...order import OrderStatus
from ...order.models import Fulfillment, Order, OrderLine
+from ...order.search import prepare_order_search_document_value
from ...order.utils import update_order_status
from ...page.models import Page, PageType
from ...payment import gateway
@@ -802,6 +803,7 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
for line in order.lines.all():
weight += line.variant.get_weight()
order.weight = weight
+ order.search_document = prepare_order_search_document_value(order)
order.save()
create_fake_payment(order=order)
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index 405aecc0b0..b272ddb9eb 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -264,6 +264,7 @@ def test_checkout_complete(
assert order.shipping_address == address
assert order.shipping_method == checkout.shipping_method
assert order.payments.exists()
+ assert order.search_document
order_payment = order.payments.first()
assert order_payment == payment
assert payment.transactions.count() == 1
diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.py
index 18ef6ae6b5..54c8b959f3 100644
--- a/saleor/graphql/order/filters.py
+++ b/saleor/graphql/order/filters.py
@@ -3,10 +3,8 @@ from django.db.models import Exists, OuterRef, Q, Sum
from django.utils import timezone
from graphene_django.filter import GlobalIDMultipleChoiceFilter
-from ...account.models import User
-from ...discount.models import OrderDiscount
from ...order.models import Order, OrderLine
-from ...payment.models import Payment
+from ...order.search import search_orders
from ...product.models import ProductVariant
from ..core.filters import ListObjectTypeFilter, MetadataFilterBase, ObjectTypeFilter
from ..core.types.common import DateRangeInput
@@ -30,12 +28,6 @@ def get_payment_id_from_query(value):
return None
-def get_order_id_from_query(value):
- if value.startswith("#"):
- value = value[1:]
- return value if value.isnumeric() else None
-
-
def filter_order_by_payment(qs, payment_id):
if payment_id:
qs = qs.filter(payments__pk=payment_id)
@@ -62,7 +54,7 @@ def filter_status(qs, _, value):
def filter_customer(qs, _, value):
qs = qs.filter(
- Q(user_email__trigram_similar=value)
+ Q(user_email__ilike=value)
| Q(user__email__trigram_similar=value)
| Q(user__first_name__trigram_similar=value)
| Q(user__last_name__trigram_similar=value)
@@ -75,33 +67,7 @@ def filter_created_range(qs, _, value):
def filter_order_search(qs, _, value):
- if payment_id := get_payment_id_from_query(value):
- return filter_order_by_payment(qs, payment_id)
-
- users = User.objects.filter(
- Q(email__trigram_similar=value)
- | Q(first_name__trigram_similar=value)
- | Q(last_name__trigram_similar=value)
- ).values("pk")
-
- filter_option = Q(user_email__trigram_similar=value) | Q(
- Exists(users.filter(pk=OuterRef("user_id")))
- )
-
- if order_id := get_order_id_from_query(value):
- filter_option |= Q(pk=order_id)
-
- payments = Payment.objects.filter(psp_reference=value).values("id")
- filter_option |= Q(Exists(payments.filter(order_id=OuterRef("id"))))
-
- discounts = OrderDiscount.objects.filter(
- Q(name__trigram_similar=value) | Q(translated_name__trigram_similar=value)
- ).values("id")
- filter_option |= Q(Exists(discounts.filter(order_id=OuterRef("id"))))
-
- lines = OrderLine.objects.filter(product_sku=value).values("id")
- filter_option |= Q(Exists(lines.filter(order_id=OuterRef("id"))))
- return qs.filter(filter_option)
+ return search_orders(qs, value)
def filter_channels(qs, _, values):
diff --git a/saleor/graphql/order/mutations/discount_order.py b/saleor/graphql/order/mutations/discount_order.py
index 1394236bf5..767cd30a9a 100644
--- a/saleor/graphql/order/mutations/discount_order.py
+++ b/saleor/graphql/order/mutations/discount_order.py
@@ -8,6 +8,7 @@ from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events, models
from ....order.error_codes import OrderErrorCode
+from ....order.search import update_order_search_document
from ....order.utils import (
create_order_discount_for_order,
get_order_discounts,
@@ -251,6 +252,7 @@ class OrderDiscountDelete(OrderDiscountCommon):
order.refresh_from_db()
cls.recalculate_order(order)
+ update_order_search_document(order)
return OrderDiscountDelete(order=order)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index eac6804142..46597b9d47 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -13,6 +13,10 @@ from ....core.utils.url import validate_storefront_url
from ....order import OrderLineData, OrderOrigin, OrderStatus, events, models
from ....order.actions import order_created
from ....order.error_codes import OrderErrorCode
+from ....order.search import (
+ prepare_order_search_document_value,
+ update_order_search_document,
+)
from ....order.utils import (
add_variant_to_order,
get_order_country,
@@ -333,6 +337,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
# Post-process the results
recalculate_order(instance)
+ update_order_search_document(instance)
class DraftOrderUpdate(DraftOrderCreate):
@@ -444,6 +449,7 @@ class DraftOrderComplete(BaseMutation):
order.shipping_address.delete()
order.shipping_address = None
+ order.search_document = prepare_order_search_document_value(order)
order.save()
for line in order.lines.all():
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 4c3eb30dfc..50364437bc 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -20,6 +20,10 @@ from ....order.actions import (
order_voided,
)
from ....order.error_codes import OrderErrorCode
+from ....order.search import (
+ prepare_order_search_document_value,
+ update_order_search_document,
+)
from ....order.utils import (
add_variant_to_order,
change_order_line_quantity,
@@ -230,6 +234,7 @@ class OrderUpdate(DraftOrderCreate):
if instance.user_email:
user = User.objects.filter(email=instance.user_email).first()
instance.user = user
+ instance.search_document = prepare_order_search_document_value(instance)
instance.save()
update_order_prices(
instance,
@@ -507,6 +512,9 @@ class OrderMarkAsPaid(BaseMutation):
mark_order_as_paid(
order, user, app, info.context.plugins, transaction_reference
)
+
+ update_order_search_document(order)
+
return OrderMarkAsPaid(order=order)
@@ -842,6 +850,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
)
recalculate_order(order)
+ update_order_search_document(order)
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
@@ -913,6 +922,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
)
recalculate_order(order)
+ update_order_search_document(order)
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
return OrderLineDelete(order=order, order_line=line)
diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.py
index 255b38b5f0..82a2d4f6cc 100644
--- a/saleor/graphql/order/tests/test_discount_order.py
+++ b/saleor/graphql/order/tests/test_discount_order.py
@@ -418,7 +418,14 @@ def test_delete_order_discount_from_order(
order = draft_order_with_fixed_discount_order
order.status = status
order.save(update_fields=["status"])
+
order_discount = draft_order_with_fixed_discount_order.discounts.get()
+ name = "discount translated"
+ translated_name = "discount translated name"
+ order_discount.name = name
+ order_discount.translated_name = translated_name
+ order_discount.save(update_fields=["name", "translated_name"])
+
current_undiscounted_total = order.undiscounted_total
variables = {
@@ -440,6 +447,10 @@ def test_delete_order_discount_from_order(
event = order.events.get()
assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
+ assert order.search_document
+ assert name not in order.search_document
+ assert translated_name not in order.search_document
+
def test_delete_order_discount_order_is_not_draft(
draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index c2695199e4..ee645d971b 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -30,6 +30,10 @@ from ....order.error_codes import OrderErrorCode
from ....order.events import order_replacement_created
from ....order.models import Order, OrderEvent, OrderLine
from ....order.notifications import get_default_order_payload
+from ....order.search import (
+ prepare_order_search_document_value,
+ update_order_search_document,
+)
from ....payment import ChargeStatus, PaymentError
from ....payment.models import Payment
from ....plugins.manager import PluginsManager
@@ -1710,6 +1714,7 @@ def test_draft_order_create(
assert order.shipping_method == shipping_method
assert order.billing_address
assert order.shipping_address
+ assert order.search_document
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
@@ -2644,6 +2649,7 @@ def test_draft_order_update(
order.refresh_from_db()
assert order.voucher
assert order.customer_note == customer_note
+ assert order.search_document
def test_draft_order_update_with_non_draft_order(
@@ -3223,6 +3229,7 @@ def test_draft_order_complete(
order.refresh_from_db()
assert data["status"] == order.status.upper()
assert data["origin"] == OrderOrigin.DRAFT.upper()
+ assert order.search_document
for line in order.lines.all():
allocation = line.allocations.get()
@@ -3895,6 +3902,9 @@ def test_order_lines_create(
assert data["errors"][0]["variants"] == [variant_id]
product_variant_out_of_stock_webhook_mock.assert_not_called()
+ order.refresh_from_db()
+ assert variant.sku.lower() in order.search_document
+
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@@ -4585,6 +4595,10 @@ def test_order_line_remove_with_back_in_stock_webhook(
) == 3
back_in_stock_webhook_mock.assert_called_once_with(Stock.objects.first())
+ order.refresh_from_db()
+ assert order.search_document
+ assert line.product_sku not in order.search_document
+
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@@ -4695,6 +4709,9 @@ def test_order_update(
assert order.user_email == email
assert order.user is None
assert order.status == OrderStatus.UNFULFILLED
+ assert graphql_address_data["firstName"].lower() in order.search_document
+ assert graphql_address_data["lastName"].lower() in order.search_document
+ assert email.lower() in order.search_document
order_updated_webhook_mock.assert_called_once_with(order)
@@ -5177,6 +5194,7 @@ def test_order_mark_as_paid_with_external_reference(
assert event_reference == transaction_reference
order_payments = order.payments.filter(psp_reference=transaction_reference)
assert order_payments.count() == 1
+ assert transaction_reference in order.search_document
def test_order_mark_as_paid(
@@ -5256,6 +5274,7 @@ def test_order_void(
event_payment_voided = order.events.last()
assert event_payment_voided.type == order_events.OrderEvents.PAYMENT_VOIDED
assert event_payment_voided.user == staff_user
+ order.refresh_from_db()
@patch.object(PluginsManager, "void_payment")
@@ -7219,6 +7238,10 @@ def test_orders_query_with_filter_search(
undiscounted_total_price=unit_price * 3,
tax_rate=Decimal("0.23"),
)
+ for order in orders:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(orders, ["search_document"])
+
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -7233,7 +7256,6 @@ def test_orders_query_with_filter_search_by_global_payment_id(
customer_user,
channel_USD,
):
-
orders = Order.objects.bulk_create(
[
Order(
@@ -7260,6 +7282,9 @@ def test_orders_query_with_filter_search_by_global_payment_id(
order_with_payment = orders[0]
payment = Payment.objects.create(order=order_with_payment)
global_id = graphene.Node.to_global_id("Payment", payment.pk)
+ for order in orders:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(orders, ["search_document"])
variables = {"filter": {"search": global_id}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -7269,8 +7294,12 @@ def test_orders_query_with_filter_search_by_global_payment_id(
def test_orders_query_with_filter_search_by_id(
- orders_query_with_filter, order, staff_api_client, permission_manage_orders
+ orders_query_with_filter,
+ order_with_search_document_value,
+ staff_api_client,
+ permission_manage_orders,
):
+ order = order_with_search_document_value
variables = {"filter": {"search": order.pk}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -7279,8 +7308,12 @@ def test_orders_query_with_filter_search_by_id(
def test_orders_query_with_filter_search_by_id_with_hash(
- orders_query_with_filter, order, staff_api_client, permission_manage_orders
+ orders_query_with_filter,
+ order_with_search_document_value,
+ staff_api_client,
+ permission_manage_orders,
):
+ order = order_with_search_document_value
variables = {"filter": {"search": f"#{order.pk}"}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -7317,6 +7350,9 @@ def test_order_query_with_filter_search_by_product_sku_order_line(
}
}
"""
+ order = order_line.order
+ order.refresh_from_db()
+ update_order_search_document(order)
variables = {"filter": {"search": order_line.product_sku}}
response = staff_api_client.post_graphql(
@@ -7447,6 +7483,9 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
),
]
)
+ order.refresh_from_db()
+ update_order_search_document(order)
+
variables = {"filter": {"search": lines[0].product_sku}}
response = staff_api_client.post_graphql(
orders_query_with_filter, variables, permissions=(permission_manage_orders,)
@@ -7464,6 +7503,7 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
({"search": "user_email"}, 2),
({"search": "[email protected]"}, 1),
({"search": "Leslie"}, 1),
+ ({"search": "leslie wade"}, 1),
({"search": "Wade"}, 1),
({"search": ""}, 3),
],
@@ -7518,7 +7558,12 @@ def test_draft_orders_query_with_filter_search(
),
]
)
+ for order in orders:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(orders, ["search_document"])
+
variables = {"filter": draft_orders_filter}
+
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
@@ -7531,6 +7576,7 @@ def test_draft_orders_query_with_filter_search_by_id(
staff_api_client,
permission_manage_orders,
):
+ update_order_search_document(draft_order)
variables = {"filter": {"search": draft_order.pk}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
@@ -7544,6 +7590,7 @@ def test_draft_orders_query_with_filter_search_by_id_with_hash(
staff_api_client,
permission_manage_orders,
):
+ update_order_search_document(draft_order)
variables = {"filter": {"search": f"#{draft_order.pk}"}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.py
index 1810761141..447c40fa2d 100644
--- a/saleor/graphql/order/tests/test_pagination.py
+++ b/saleor/graphql/order/tests/test_pagination.py
@@ -9,6 +9,10 @@ from prices import Money, TaxedMoney
from ....discount.models import OrderDiscount
from ....order.models import Order, OrderStatus
+from ....order.search import (
+ prepare_order_search_document_value,
+ update_order_search_document,
+)
from ....payment import ChargeStatus
from ...tests.utils import get_graphql_content
@@ -34,6 +38,11 @@ def orders_for_pagination(db, channel_USD):
),
]
)
+
+ for order in orders:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(orders, ["search_document"])
+
return orders
@@ -453,6 +462,11 @@ def test_orders_query_pagination_with_filter_search(
),
]
)
+
+ for order in orders:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(orders, ["search_document"])
+
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -531,6 +545,11 @@ def test_draft_orders_query_pagination_with_filter_search(
),
]
)
+
+ for order in orders:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(orders, ["search_document"])
+
page_size = 2
variables = {"first": page_size, "after": None, "filter": draft_orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -547,8 +566,9 @@ def test_draft_orders_query_pagination_with_filter_search(
def test_orders_query_pagination_with_filter_search_by_id(
- order, staff_api_client, permission_manage_orders
+ order_with_search_document_value, staff_api_client, permission_manage_orders
):
+ order = order_with_search_document_value
page_size = 2
variables = {"first": page_size, "after": None, "filter": {"search": order.pk}}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -562,6 +582,7 @@ def test_draft_orders_query_pagination_with_filter_search_by_id(
staff_api_client,
permission_manage_orders,
):
+ update_order_search_document(draft_order)
page_size = 2
variables = {
"first": page_size,
diff --git a/saleor/order/migrations/0121_order_search_document.py b/saleor/order/migrations/0121_order_search_document.py
new file mode 100644
index 0000000000..e84dea0ee3
--- /dev/null
+++ b/saleor/order/migrations/0121_order_search_document.py
@@ -0,0 +1,115 @@
+# Generated by Django 3.2.6 on 2021-11-19 10:12
+import django.contrib.postgres.indexes
+import graphene
+from django.db import migrations, models
+
+BATCH_SIZE = 10000
+ADDRESS_SEARCH_FIELDS = [
+ "first_name",
+ "last_name",
+ "street_address_1",
+ "street_address_2",
+ "city",
+ "postal_code",
+ "country",
+ "phone",
+]
+
+
+def set_search_document(apps, schema_editor):
+ Order = apps.get_model("order", "Order")
+
+ orders = []
+ for order in Order.objects.iterator():
+ order.search_document = prepare_search_document_value(order)
+ orders.append(order)
+
+ Order.objects.bulk_update(orders, ["search_document"], batch_size=BATCH_SIZE)
+
+
+def prepare_search_document_value(order):
+ search_document = f"#{str(order.id)}\n"
+
+ # attach user data
+ user_data = order.user_email + "\n"
+ if user := order.user:
+ user_data += "\n".join(
+ [
+ getattr(user, field)
+ for field in ["email", "first_name", "last_name"]
+ if getattr(user, field)
+ ]
+ )
+ user_data += "\n"
+ search_document += user_data
+
+ # attach addressess data
+ for address_field in ["billing_address", "shipping_address"]:
+ if address := getattr(order, address_field):
+ for field in ADDRESS_SEARCH_FIELDS:
+ if field == "country":
+ search_document += (
+ address.country.name + "\n" + address.country.code + "\n"
+ )
+ else:
+ search_document += str(getattr(address, field)) + "\n"
+
+ # attach payments data
+ payments_data = ""
+ for id, psp_reference in order.payments.values_list("id", "psp_reference"):
+ payments_data += graphene.Node.to_global_id("Payment", id) + "\n"
+ if psp_reference:
+ payments_data += psp_reference + "\n"
+
+ # attach discounts data
+ for data in order.discounts.values_list("name", "translated_name"):
+ for value in data:
+ if value:
+ search_document += value + "\n"
+
+ # attach order lines data
+ lines_data = "\n".join(
+ order.lines.exclude(product_sku__isnull=True).values_list(
+ "product_sku", flat=True
+ )
+ )
+ if lines_data:
+ search_document += lines_data + "\n"
+
+ return search_document.lower()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0120_orderline_optional_sku"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="search_document",
+ field=models.TextField(blank=True, default=""),
+ ),
+ migrations.RunPython(set_search_document, migrations.RunPython.noop),
+ migrations.RemoveIndex(
+ model_name="order",
+ name="order_order_user_em_bda05b_gin",
+ ),
+ migrations.AddIndex(
+ model_name="order",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["search_document"],
+ name="order_search_gin",
+ opclasses=["gin_trgm_ops"],
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="order",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["user_email"],
+ name="order_email_search_gin",
+ opclasses=["gin_trgm_ops"],
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index d011181f9c..a7798da5a8 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -247,13 +247,28 @@ class Order(ModelWithMetadata):
default=zero_weight,
)
redirect_url = models.URLField(blank=True, null=True)
+ search_document = models.TextField(blank=True, default="")
objects = models.Manager.from_queryset(OrderQueryset)()
class Meta:
ordering = ("-pk",)
permissions = ((OrderPermissions.MANAGE_ORDERS.codename, "Manage orders."),)
- indexes = [*ModelWithMetadata.Meta.indexes, GinIndex(fields=["user_email"])]
+ indexes = [
+ *ModelWithMetadata.Meta.indexes,
+ GinIndex(
+ name="order_search_gin",
+ # `opclasses` and `fields` should be the same length
+ fields=["search_document"],
+ opclasses=["gin_trgm_ops"],
+ ),
+ GinIndex(
+ name="order_email_search_gin",
+ # `opclasses` and `fields` should be the same length
+ fields=["user_email"],
+ opclasses=["gin_trgm_ops"],
+ ),
+ ]
def save(self, *args, **kwargs):
if not self.token:
diff --git a/saleor/order/search.py b/saleor/order/search.py
new file mode 100644
index 0000000000..742c621314
--- /dev/null
+++ b/saleor/order/search.py
@@ -0,0 +1,84 @@
+from typing import TYPE_CHECKING
+
+import graphene
+from django.db.models import Q, prefetch_related_objects
+
+from ..account.search import (
+ generate_address_search_document_value,
+ generate_user_fields_search_document_value,
+)
+
+if TYPE_CHECKING:
+ from .models import Order
+
+
+def update_order_search_document(order: "Order"):
+ order.search_document = prepare_order_search_document_value(order)
+ order.save(update_fields=["search_document"])
+
+
+def prepare_order_search_document_value(order: "Order"):
+ search_document = f"#{str(order.id)}\n"
+
+ prefetch_related_objects(
+ [order],
+ "user",
+ "billing_address",
+ "shipping_address",
+ "payments",
+ "discounts",
+ "lines",
+ )
+
+ user_data = order.user_email + "\n"
+ if user := order.user:
+ user_data += generate_user_fields_search_document_value(user)
+ search_document += user_data
+
+ for address_field in ["billing_address", "shipping_address"]:
+ if address := getattr(order, address_field):
+ search_document += generate_address_search_document_value(address)
+
+ search_document += generate_order_payments_search_document_value(order)
+
+ search_document += generate_order_discounts_search_document_value(order)
+
+ search_document += generate_order_lines_search_document_value(order)
+
+ return search_document.lower()
+
+
+def generate_order_payments_search_document_value(order: "Order"):
+ payments_data = ""
+ for payment in order.payments.all():
+ payments_data += graphene.Node.to_global_id("Payment", payment.id) + "\n"
+ if psp_reference := payment.psp_reference:
+ payments_data += psp_reference + "\n"
+ return payments_data
+
+
+def generate_order_discounts_search_document_value(order: "Order"):
+ discount_data = ""
+ for discount in order.discounts.all():
+ for field in ["name", "translated_name"]:
+ if value := getattr(discount, field):
+ discount_data += value + "\n"
+ return discount_data
+
+
+def generate_order_lines_search_document_value(order: "Order"):
+ lines_data = "\n".join(
+ [line.product_sku for line in order.lines.all() if line.product_sku]
+ )
+ if lines_data:
+ lines_data += "\n"
+ return lines_data
+
+
+def search_orders(qs, value):
+ if value:
+ lookup = Q()
+ for val in value.split():
+ lookup &= Q(search_document__ilike=val)
+ qs = qs.filter(lookup)
+ return qs
diff --git a/saleor/order/tests/test_order_search.py b/saleor/order/tests/test_order_search.py
new file mode 100644
index 0000000000..eee1ff7924
--- /dev/null
+++ b/saleor/order/tests/test_order_search.py
@@ -0,0 +1,121 @@
+from decimal import Decimal
+
+import graphene
+
+from ...discount import DiscountValueType
+from ..models import OrderLine
+from ..search import prepare_order_search_document_value, update_order_search_document
+
+
+def test_update_order_search_document(order):
+ # given
+ order.search_document = ""
+ order.save(update_fields=["search_document"])
+ assert not order.search_document
+
+ # when
+ update_order_search_document(order)
+
+ # then
+ assert f"{order.id}\n{order.user_email}\n".lower() in order.search_document
+
+
+def test_prepare_order_search_document_value(
+ order_with_lines, address_usa, payment_dummy
+):
+ # given
+ order = order_with_lines
+ order.shipping_address = address_usa
+ order.save(update_fields=["shipping_address"])
+ discount = order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ name="discount",
+ translated_name="discount translated",
+ value=Decimal("20"),
+ reason="Discount reason",
+ amount=(order.undiscounted_total - order.total).gross, # type: ignore
+ )
+
+ psp_reference = "TestABC"
+ payment_dummy.psp_reference = psp_reference
+ payment_dummy.save(update_fields=["psp_reference"])
+
+ # when
+ search_document_value = prepare_order_search_document_value(order)
+
+ # then
+ assert str(order.id) in search_document_value
+ user = order.user
+ assert (
+ f"{order.user_email}\n{user.email}\n{user.first_name}\n{user.last_name}".lower()
+ in search_document_value
+ )
+ for address in [order.billing_address, order.shipping_address]:
+ address_data = (
+ f"{address.first_name}\n{address.last_name}\n"
+ f"{address.street_address_1}\n{address.street_address_2}\n"
+ f"{address.city}\n{address.postal_code}\n{address.country.name}\n"
+ f"{address.country.code}\n{address.phone}\n"
+ )
+ assert address_data.lower() in search_document_value
+ assert psp_reference.lower() in search_document_value
+ assert discount.name in search_document_value
+ assert discount.translated_name in search_document_value
+ for line in order.lines.all():
+ assert line.product_sku.lower() in search_document_value
+
+
+def test_prepare_order_search_document_value_empty_relation_fields(
+ order_with_lines, payment_dummy
+):
+ # given
+ order = order_with_lines
+ order.billing_address = None
+ order.shipping_address = None
+ order.save(update_fields=["shipping_address", "billing_address"])
+ order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=Decimal("20"),
+ reason="Discount reason",
+ amount=(order.undiscounted_total - order.total).gross, # type: ignore
+ )
+
+ payment_dummy.psp_reference = None
+ payment_dummy.save(update_fields=["psp_reference"])
+ payment_id = graphene.Node.to_global_id("Payment", payment_dummy.pk)
+
+ lines = []
+ for line in order.lines.all():
+ line.product_sku = None
+ lines.append(line)
+ OrderLine.objects.bulk_update(lines, ["product_sku"])
+
+ # when
+ search_document_value = prepare_order_search_document_value(order)
+
+ # then
+ user = order.user
+ assert (
+ f"#{order.id}\n{order.user_email}\n{user.email}\n"
+ f"{user.first_name}\n{user.last_name}\n"
+ f"{payment_id}\n".lower() == search_document_value
+ )
+
+
+def test_prepare_order_search_document_value_no_relations_data(order, address_usa):
+ # given
+ order.shipping_address = address_usa
+ order.user = None
+ order.billing_address = None
+ order.shipping_address = None
+ order.save(update_fields=["shipping_address", "billing_address", "user"])
+
+ assert not order.lines.all()
+ assert not order.discounts.all()
+ assert not order.payments.all()
+
+ # when
+ search_document_value = prepare_order_search_document_value(order)
+
+ # then
+ assert f"#{order.id}\n{order.user_email}\n".lower() == search_document_value
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 9547997daa..df1cd81a67 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -73,6 +73,7 @@ from ..order.models import (
OrderEvent,
OrderLine,
)
+from ..order.search import prepare_order_search_document_value
from ..order.utils import recalculate_order
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
@@ -692,7 +693,7 @@ def user_checkouts(request, user_checkout_with_items, user_checkout_with_items_f
@pytest.fixture
def order(customer_user, channel_USD):
address = customer_user.default_billing_address.get_copy()
- return Order.objects.create(
+ order = Order.objects.create(
billing_address=address,
channel=channel_USD,
currency=channel_USD.currency_code,
@@ -701,6 +702,14 @@ def order(customer_user, channel_USD):
user=customer_user,
origin=OrderOrigin.CHECKOUT,
)
+ return order
+
+
+def order_with_search_document_value(order):
+ order.search_document = prepare_order_search_document_value(order)
+ order.save(update_fields=["search_document"])
+ return order
@pytest.fixture
@@ -5214,6 +5223,11 @@ def allocations(order_list, stock, channel_USD):
),
]
)
+
+ for order in order_list:
+ order.search_document = prepare_order_search_document_value(order)
+ Order.objects.bulk_update(order_list, ["search_document"])
+
return Allocation.objects.bulk_create(
[
Allocation(