Skip to content

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

Abstract the reordering logic

NyanKiyoshi3bf42c1d44a2
diff --git a/saleor/graphql/core/interfaces.py b/saleor/graphql/core/interfaces.py
new file mode 100644
index 0000000000..ca6d40b73d
--- /dev/null
+++ b/saleor/graphql/core/interfaces.py
@@ -0,0 +1,9 @@
+from dataclasses import dataclass
+
+from ...core.models import SortableModel
+
+
+@dataclass
+class MoveOperation:
+ node: SortableModel
+ sort_order: int
diff --git a/saleor/graphql/core/utils.py b/saleor/graphql/core/utils.py
index 2b5c22b675..1b98a16407 100644
--- a/saleor/graphql/core/utils.py
+++ b/saleor/graphql/core/utils.py
@@ -1,7 +1,11 @@
+from typing import List
+
import graphene
import graphene_django_optimizer as gql_optimizer
from django.core.exceptions import ValidationError
+from .interfaces import MoveOperation
+
def clean_seo_fields(data):
"""Extract and assign seo fields to given dictionary."""
@@ -43,3 +47,62 @@ def get_node_optimized(qs, lookup, info):
qs = qs.filter(**lookup)
qs = gql_optimizer.query(qs, info)
return qs[0] if qs else None
+
+
+def _prepare_reordering_operations(moves: List[MoveOperation]):
+ """Updates the 'moves' relative sort orders to an absolute sorting."""
+
+ current_rel_pos = None
+
+ for move in moves:
+ node = move.node
+
+ if current_rel_pos is None:
+ # This case happens when products created using a bulk_creation
+ # e.g., bulk_create or collections.add
+ if node.sort_order is None:
+ current_rel_pos = (
+ node.get_max_sort_order(node.get_ordering_queryset()) or 0
+ )
+ else:
+ current_rel_pos = node.sort_order
+ else:
+ current_rel_pos += 1
+
+ new_position = max(0, current_rel_pos + move.sort_order)
+ move.sort_order = new_position
+
+
+def perform_reordering(moves: List[MoveOperation], field: str = "sort_order"):
+ """This utility takes a set of operations containing a node
+ and a relative sort order. It then converts the relative sorting
+ to an absolute sorting.
+
+ This will then commit the changes onto the nodes.
+
+ Example usage:
+ >>> from typing import Dict, Tuple
+ >>>
+ >>> from graphene import Node
+ >>>
+ >>> from saleor.graphql.core.interfaces import MoveOperation
+ >>>
+ >>>
+ >>> # operations => [(node_id, relative_sort_order), ...]
+ >>>
+ >>> def reorder_my_models(info, operations: List[Tuple[int, int]]):
+ ...
+ ... # moves => [OP(node, sort_order), ...]
+ ... moves = [
+ ... MoveOperation(Node.from_global_id(node=op[0]), sort_order=op[1])
+ ... for op in operations
+ ... ]
+ ...
+ ... perform_reordering(moves)
+ ...
+ """
+ _prepare_reordering_operations(moves)
+
+ for move in moves:
+ move.node.sort_order = move.sort_order
+ move.node.save(update_fields=[field])
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 67192f398c..d28e38e121 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Tuple
+from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -15,6 +15,7 @@ from ....product.thumbnails import (
)
from ....product.utils.attributes import get_name_from_attributes
from ...core.enums import TaxRateType
+from ...core.interfaces import MoveOperation
from ...core.mutations import (
BaseMutation,
ClearMetaBaseMutation,
@@ -27,6 +28,7 @@ from ...core.types import SeoInput, Upload
from ...core.utils import (
clean_seo_fields,
from_global_id_strict_type,
+ perform_reordering,
validate_image_file,
)
from ...product.types import AttributeValue
@@ -225,11 +227,11 @@ class CollectionReorderProducts(BaseMutation):
)
@classmethod
- def get_operations(
- cls, info, collection_id: int, moves: List[MoveProductInput]
- ) -> List[Tuple[models.CollectionProduct, int]]:
+ def perform_mutation(cls, _root, info, collection_id, moves):
+ collection = cls.get_node_or_error(
+ info, collection_id, field="collection_id", only_type=Collection
+ )
operations = []
- current_rel_pos = None
for move_info in moves:
product_id = from_global_id_strict_type(
@@ -238,40 +240,16 @@ class CollectionReorderProducts(BaseMutation):
try:
node = models.CollectionProduct.objects.get(
- product_id=product_id, collection_id=collection_id
+ product_id=product_id, collection_id=collection.id
)
except models.CollectionProduct.DoesNotExist:
raise ValidationError(
{"moves": "Couldn't resolve to a product: %s" % product_id}
)
- if current_rel_pos is None:
- # This case happens when products created using a bulk_creation
- # e.g., bulk_create or collections.add
- if node.sort_order is None:
- current_rel_pos = (
- node.get_max_sort_order(node.get_ordering_queryset()) or 0
- )
- else:
- current_rel_pos = node.sort_order
- else:
- current_rel_pos += 1
-
- sort_position = max(0, current_rel_pos + move_info.sort_order)
- operations.append((node, sort_position))
-
- return operations
-
- @classmethod
- def perform_mutation(cls, _root, info, collection_id, moves):
- collection = cls.get_node_or_error(
- info, collection_id, field="collection_id", only_type=Collection
- )
-
- for node, new_position in cls.get_operations(info, collection.id, moves):
- node.sort_order = new_position
- node.save(update_fields=["sort_order"])
+ operations.append(MoveOperation(node=node, sort_order=move_info.sort_order))
+ perform_reordering(operations)
return CollectionReorderProducts(collection=collection)