Skip to content

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

Fix incorrect cursor returned when making a query with search input (#17222)

Maciej Korycinski5f8b1cc4db2d
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index 21f1213b10..14a91b46f0 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -1,13 +1,7 @@
import json
from collections.abc import Iterable
from decimal import Decimal, InvalidOperation
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Optional,
- Union,
-)
+from typing import TYPE_CHECKING, Any, Callable, Optional, Union
import graphene
from django.conf import settings
@@ -80,10 +74,10 @@ def _prepare_filter_by_rank_expression(
# making equal comparisons impossible. Instead we compare rank against small
# range of values, constructed using epsilon.
if sorting_direction == "gt":
- return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__lt=id) | Q(
+ return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__gt=id) | Q(
search_rank__gt=rank + EPSILON
)
- return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__gt=id) | Q(
+ return Q(search_rank__range=(rank - EPSILON, rank + EPSILON), id__lt=id) | Q(
search_rank__lt=rank - EPSILON
)
diff --git a/saleor/graphql/order/tests/queries/test_pagination.py b/saleor/graphql/order/tests/queries/test_pagination.py
index c0ca1aa38a..269e4423cd 100644
--- a/saleor/graphql/order/tests/queries/test_pagination.py
+++ b/saleor/graphql/order/tests/queries/test_pagination.py
@@ -758,3 +758,93 @@ def test_query_orders_pagination_with_sort(
assert orders[order]["node"]["number"] == str(
created_orders[order_number].number
)
+
+
+ ("sort_order", "reversed"),
+ [
+ (
+ "ASC",
+ False,
+ ),
+ ("DESC", True),
+ ],
+)
+def test_orders_with_filter_search_returns_correct_cursor(
+ sort_order,
+ reversed,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ channel_USD,
+):
+ # given
+ search_query = "[email protected]"
+ orders = Order.objects.bulk_create(
+ [
+ Order(
+ user=customer_user,
+ user_email=search_query,
+ status=OrderStatus.DRAFT,
+ channel=channel_USD,
+ should_refresh_prices=False,
+ ),
+ Order(
+ user_email=search_query,
+ status=OrderStatus.DRAFT,
+ channel=channel_USD,
+ should_refresh_prices=False,
+ ),
+ Order(
+ user_email=search_query,
+ status=OrderStatus.DRAFT,
+ channel=channel_USD,
+ should_refresh_prices=False,
+ ),
+ ]
+ )
+
+ for order in orders:
+ order.search_vector = FlatConcatSearchVector(
+ *prepare_order_search_vector_value(order)
+ )
+ Order.objects.bulk_update(orders, ["search_vector"])
+
+ orders_sorted_by_id = sorted(orders, key=lambda order: order.id, reverse=reversed)
+
+ page_size = 1
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": {"search": search_query},
+ "sortBy": {"field": "RANK", "direction": sort_order},
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_DRAFT_ORDERS_WITH_PAGINATION, variables
+ )
+ content = get_graphql_content(response)
+ orders = content["data"]["draftOrders"]["edges"]
+ assert len(orders) == 1
+ assert orders[0]["node"]["number"] == str(orders_sorted_by_id[0].number)
+
+ cursor = content["data"]["draftOrders"]["pageInfo"]["endCursor"]
+ variables = {
+ "first": 2,
+ "after": cursor,
+ "filter": {"search": search_query},
+ "sortBy": {"field": "RANK", "direction": sort_order},
+ }
+ response = staff_api_client.post_graphql(
+ QUERY_DRAFT_ORDERS_WITH_PAGINATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ orders = content["data"]["draftOrders"]["edges"]
+
+ assert len(orders) == 2
+ assert orders[0]["node"]["number"] == str(orders_sorted_by_id[1].number)
+ assert orders[1]["node"]["number"] == str(orders_sorted_by_id[2].number)
diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.py
index 2241b67887..23ac33d8e0 100644
--- a/saleor/graphql/product/tests/queries/test_products_query.py
+++ b/saleor/graphql/product/tests/queries/test_products_query.py
@@ -14,6 +14,7 @@ from .....product.models import (
ProductVariantChannelListing,
)
from .....product.search import prepare_product_search_vector_value
+from ....core.connection import from_global_cursor
from ....tests.utils import get_graphql_content
QUERY_FETCH_ALL_PRODUCTS = """
@@ -1213,9 +1214,19 @@ def test_products_with_variants_query_as_app(
PRODUCT_SEARCH_QUERY = """
- query($search: String, $channel: String) {
- products(first: 10, search: $search, channel: $channel) {
+ query($search: String, $channel: String, $first: Int, $after: String, $sortBy: ProductOrder) {
+ products(
+ first: $first,
+ search: $search,
+ channel: $channel,
+ after: $after,
+ sortBy: $sortBy
+ ) {
+ pageInfo{
+ endCursor
+ }
edges {
+ cursor
node {
name
slug
@@ -1241,7 +1252,7 @@ def test_search_products_on_root_level(
search, indexes, api_client, product_list, channel_USD
):
# given
- variables = {"search": search, "channel": channel_USD.slug}
+ variables = {"search": search, "channel": channel_USD.slug, "first": 10}
# when
response = api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)
@@ -1278,6 +1289,7 @@ def test_search_product_using_search_argument_with_sort_by(
variables = {
"search": "new",
"sortBy": {"field": "RANK", "direction": "DESC"},
+ "first": 10,
"channel": channel_USD.slug,
}
response = user_api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)
@@ -1290,3 +1302,112 @@ def test_search_product_using_search_argument_with_sort_by(
product_1.name,
product_2.name,
}
+
+
+ (
+ "sort_order",
+ "reversed",
+ ),
+ [
+ (
+ "ASC",
+ False,
+ ),
+ ("DESC", True),
+ ],
+)
+def test_search_product_with_similar_search_rank_and_cursor_usage(
+ sort_order, reversed, user_api_client, product_list, channel_USD
+):
+ # given
+ sorted_products = sorted(
+ product_list, key=lambda product: product.id, reverse=reversed
+ )
+ product_1 = sorted_products[0]
+ product_1.description_plaintext = "Orange"
+ product_2 = sorted_products[1]
+ product_2.description_plaintext = "Orange"
+ product_3 = sorted_products[2]
+ product_3.description_plaintext = "Orange"
+
+ for product in product_list:
+ product.search_vector = FlatConcatSearchVector(
+ *prepare_product_search_vector_value(product)
+ )
+
+ Product.objects.bulk_update(
+ product_list,
+ ["search_vector", "description_plaintext"],
+ )
+
+ variables = {
+ "search": "Orange",
+ "sortBy": {"field": "RANK", "direction": sort_order},
+ "first": 1,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["products"]["edges"]
+
+ assert len(data) == 1
+ assert data[0]["node"]["name"] == product_1.name
+
+ cursor = content["data"]["products"]["pageInfo"]["endCursor"]
+
+ variables = {
+ "search": "Orange",
+ "sortBy": {"field": "RANK", "direction": sort_order},
+ "first": 2,
+ "channel": channel_USD.slug,
+ "after": cursor,
+ }
+ response = user_api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["products"]["edges"]
+ assert len(data) == 2
+ assert data[0]["node"]["name"] == product_2.name
+ assert data[1]["node"]["name"] == product_3.name
+
+
+def test_search_product_sort_by_attribute_returns_correct_cursor(
+ user_api_client, product, channel_USD
+):
+ # given
+ attribute = product.product_type.product_attributes.first()
+ attr_value = attribute.values.first()
+
+ product.description_plaintext = "Orange"
+
+ product.search_vector = FlatConcatSearchVector(
+ *prepare_product_search_vector_value(product)
+ )
+ product.save()
+
+ variables = {
+ "search": "Orange",
+ "sortBy": {
+ "attributeId": graphene.Node.to_global_id("Attribute", attribute.id),
+ "direction": "ASC",
+ },
+ "first": 1,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ cursor = content["data"]["products"]["pageInfo"]["endCursor"]
+ cursor_data = from_global_cursor(cursor)
+
+ # Ref saleor.product.managers.ProductsQueryset.sort_by_attribute
+ # First field stores the flag to determine if product has assigned attribute values
+ # Second is the list of attribute values as string
+ assert ["0", attr_value.name, product.name] == cursor_data
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index e39af6a57a..a218ea44f5 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -158,7 +158,8 @@ def search_string_in_kwargs(kwargs: dict) -> bool:
def sort_field_from_kwargs(kwargs: dict) -> Optional[list[str]]:
- return kwargs.get("sort_by", {}).get("field") or None
+ sort_by = kwargs.get("sort_by", {}) or {}
+ return sort_by.get("field") or sort_by.get("attribute_id")
def check_for_sorting_by_rank(info, kwargs: dict):