Skip to content

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

Fix incorrect order for reordering collection products when sort_order is null (#17276)

Maciej Korycinski6d3dc6d17caf
diff --git a/saleor/graphql/core/utils/reordering.py b/saleor/graphql/core/utils/reordering.py
index ffb27fd0bb..5161256104 100644
--- a/saleor/graphql/core/utils/reordering.py
+++ b/saleor/graphql/core/utils/reordering.py
@@ -23,10 +23,11 @@ class FinalSortOrder:
class Reordering:
- def __init__(self, qs: QuerySet, operations: dict[int, int], field: str):
+ def __init__(
+ self, qs: QuerySet, operations: dict[int, int], second_sort_field: str
+ ):
self.qs = qs
self.operations = operations
- self.field = field
# Will contain the original data, before sorting
# This will be useful to look for the sort orders that
@@ -36,13 +37,19 @@ class Reordering:
# Will contain the list of keys kept
# in correct order in accordance to their sort order
self.ordered_pks: list[int] = []
+ self.second_sort_field = second_sort_field
@cached_property
def ordered_node_map(self):
+ additional_sorters = [self.second_sort_field]
+ if self.second_sort_field != "id":
+ # add `id` to make sure that last sorting field is unique
+ additional_sorters.append("id")
+
ordering_map = OrderedDict(
self.qs.select_for_update()
.values_list("pk", "sort_order")
- .order_by(F("sort_order").asc(nulls_last=True), "id")
+ .order_by(F("sort_order").asc(nulls_last=True), *additional_sorters)
)
self.old_sort_map = ordering_map.copy()
self.ordered_pks = list(ordering_map.keys())
@@ -153,7 +160,9 @@ class Reordering:
self.commit()
-def perform_reordering(qs: QuerySet, operations: dict[int, int], field: str = "moves"):
+def perform_reordering(
+ qs: QuerySet, operations: dict[int, int], second_sort_field="id"
+):
"""Perform reordering over given operations on a queryset.
This utility takes a set of operations containing a node
@@ -172,4 +181,4 @@ def perform_reordering(qs: QuerySet, operations: dict[int, int], field: str = "m
if not transaction.get_connection().in_atomic_block:
raise RuntimeError("Needs to be run inside an atomic transaction")
- Reordering(qs, operations, field).run()
+ Reordering(qs, operations, second_sort_field).run()
diff --git a/saleor/graphql/product/mutations/collection/collection_reorder_products.py b/saleor/graphql/product/mutations/collection/collection_reorder_products.py
index aa42f8dead..f4f7bd18ae 100644
--- a/saleor/graphql/product/mutations/collection/collection_reorder_products.py
+++ b/saleor/graphql/product/mutations/collection/collection_reorder_products.py
@@ -99,6 +99,8 @@ class CollectionReorderProducts(BaseMutation):
operations[m2m_info.pk] = move_info.sort_order
with traced_atomic_transaction():
- perform_reordering(m2m_related_field.all(), operations)
+ perform_reordering(
+ m2m_related_field.all(), operations, second_sort_field="product_id"
+ )
context = ChannelContext(node=collection, channel_slug=None)
return CollectionReorderProducts(collection=context)
diff --git a/saleor/graphql/product/tests/test_product_sorting.py b/saleor/graphql/product/tests/test_product_sorting.py
index 41687dd9c9..0787a8dfee 100644
--- a/saleor/graphql/product/tests/test_product_sorting.py
+++ b/saleor/graphql/product/tests/test_product_sorting.py
@@ -144,6 +144,59 @@ def test_sort_products_within_collection(
assert products[2]["node"]["id"] == product
+def test_sort_products_within_collection_when_null_as_sort_order(
+ staff_api_client,
+ published_collection,
+ collection_with_products,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+
+ products = collection_with_products
+
+ collection = products[0].collections.first()
+
+ collection_products = collection.collectionproduct.all()
+ for c_p in collection_products:
+ c_p.sort_order = None
+ CollectionProduct.objects.bulk_update(collection_products, ["sort_order"])
+
+ collection_products = sorted(
+ collection.collectionproduct.all(), key=lambda c: c.product_id
+ )
+
+ collection_prod_1 = collection_products[0]
+ collection_prod_2 = collection_products[1]
+ collection_prod_3 = collection_products[2]
+
+ product = graphene.Node.to_global_id("Product", collection_prod_1.product_id)
+ second_product = graphene.Node.to_global_id("Product", collection_prod_2.product_id)
+ third_product = graphene.Node.to_global_id("Product", collection_prod_3.product_id)
+
+ variables = {
+ "collectionId": collection_id,
+ "moves": [{"productId": third_product, "sortOrder": -2}],
+ }
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(COLLECTION_RESORT_QUERY, variables)
+ )["data"]["collectionReorderProducts"]
+
+ # then
+ assert not content["errors"]
+
+ assert content["collection"]["id"] == collection_id
+
+ products = content["collection"]["products"]["edges"]
+ assert products[0]["node"]["id"] == third_product
+ assert products[1]["node"]["id"] == product
+ assert products[2]["node"]["id"] == second_product
+
+
GET_SORTED_PRODUCTS_QUERY = """
query Products($sortBy: ProductOrder, $channel: String) {
products(first: 10, sortBy: $sortBy, channel: $channel) {