Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add support for sort order shifting
NyanKiyoshi00123e4e7051
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 60bf8f4c74..c28ad0a65f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,6 @@ All notable, unreleased changes to this project will be documented in this file.- The `SelectedAttribute` type now returns multiple values and will always return all the attributes assigned to the product type. - #4394 by @NyanKiyoshi- Add attribute visibility config - #4449 by @dominik-zeglen- Add slug generation = #4488 by @dominik-zeglen-- Dropped `null` in `sort_order` fields to make it easier to reorder in API - #4481 by @NyanKiyoshi- Add drag'n'drop attribute reordering in product type view - #4492 by @dominik-zeglen- Fix attribute picker = #4501 by @dominik-zeglen- Rework adding attribute values - #4504 by @dominik-zeglendiff --git a/saleor/core/models.py b/saleor/core/models.pyindex 0e8ab7c2c7..cc349d16ff 100644--- a/saleor/core/models.py+++ b/saleor/core/models.py@@ -8,7 +8,7 @@ from .utils.json_serializer import CustomJsonEncoderclass SortableModel(models.Model):- sort_order = models.PositiveIntegerField(editable=False, db_index=True, default=0)+ sort_order = models.IntegerField(editable=False, db_index=True, null=True)class Meta:abstract = True@@ -29,8 +29,11 @@ class SortableModel(models.Model):super().save(*args, **kwargs)def delete(self, *args, **kwargs):- qs = self.get_ordering_queryset()- qs.filter(sort_order__gt=self.sort_order).update(sort_order=F("sort_order") - 1)+ if self.sort_order is not None:+ qs = self.get_ordering_queryset()+ qs.filter(sort_order__gt=self.sort_order).update(+ sort_order=F("sort_order") - 1+ )super().delete(*args, **kwargs)diff --git a/saleor/graphql/core/interfaces.py b/saleor/graphql/core/interfaces.pydeleted file mode 100644index ca6d40b73d..0000000000--- a/saleor/graphql/core/interfaces.py+++ /dev/null@@ -1,9 +0,0 @@-from dataclasses import dataclass--from ...core.models import SortableModel---@dataclass-class MoveOperation:- node: SortableModel- sort_order: intdiff --git a/saleor/graphql/core/utils.py b/saleor/graphql/core/utils.pydeleted file mode 100644index 1b98a16407..0000000000--- a/saleor/graphql/core/utils.py+++ /dev/null@@ -1,108 +0,0 @@-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."""- seo_fields = data.pop("seo", None)- if seo_fields:- data["seo_title"] = seo_fields.get("title")- data["seo_description"] = seo_fields.get("description")---def snake_to_camel_case(name):- """Convert snake_case variable name to camelCase."""- if isinstance(name, str):- split_name = name.split("_")- return split_name[0] + "".join(map(str.capitalize, split_name[1:]))- return name---def str_to_enum(name):- """Create an enum value from a string."""- return name.replace(" ", "_").replace("-", "_").upper()---def validate_image_file(file, field_name):- """Validate if the file is an image."""- if not file.content_type.startswith("image/"):- raise ValidationError({field_name: "Invalid file type"})---def from_global_id_strict_type(info, global_id, only_type, field="id"):- """Resolve a node global id with a strict given type required."""- _type, _id = graphene.Node.from_global_id(global_id)- graphene_type = info.schema.get_type(_type).graphene_type- if graphene_type != only_type:- raise ValidationError({field: "Couldn't resolve to a node: %s" % global_id})- return _id---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/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pynew file mode 100644index 0000000000..2b5c22b675--- /dev/null+++ b/saleor/graphql/core/utils/__init__.py@@ -0,0 +1,45 @@+import graphene+import graphene_django_optimizer as gql_optimizer+from django.core.exceptions import ValidationError+++def clean_seo_fields(data):+ """Extract and assign seo fields to given dictionary."""+ seo_fields = data.pop("seo", None)+ if seo_fields:+ data["seo_title"] = seo_fields.get("title")+ data["seo_description"] = seo_fields.get("description")+++def snake_to_camel_case(name):+ """Convert snake_case variable name to camelCase."""+ if isinstance(name, str):+ split_name = name.split("_")+ return split_name[0] + "".join(map(str.capitalize, split_name[1:]))+ return name+++def str_to_enum(name):+ """Create an enum value from a string."""+ return name.replace(" ", "_").replace("-", "_").upper()+++def validate_image_file(file, field_name):+ """Validate if the file is an image."""+ if not file.content_type.startswith("image/"):+ raise ValidationError({field_name: "Invalid file type"})+++def from_global_id_strict_type(info, global_id, only_type, field="id"):+ """Resolve a node global id with a strict given type required."""+ _type, _id = graphene.Node.from_global_id(global_id)+ graphene_type = info.schema.get_type(_type).graphene_type+ if graphene_type != only_type:+ raise ValidationError({field: "Couldn't resolve to a node: %s" % global_id})+ return _id+++def get_node_optimized(qs, lookup, info):+ qs = qs.filter(**lookup)+ qs = gql_optimizer.query(qs, info)+ return qs[0] if qs else Nonediff --git a/saleor/graphql/core/utils/reordering.py b/saleor/graphql/core/utils/reordering.pynew file mode 100644index 0000000000..e3a8d56770--- /dev/null+++ b/saleor/graphql/core/utils/reordering.py@@ -0,0 +1,172 @@+import warnings+from collections import OrderedDict+from dataclasses import dataclass+from typing import Dict, Tuple++from django.db import transaction+from django.db.models import F, QuerySet+from django.utils.functional import cached_property++__all__ = ["perform_reordering"]+++@dataclass(frozen=True)+class FinalSortOrder:+ """Describes a final sort order value for a given PK. This is needed to tell django+ which objects and values to associate and update."""++ pk: int+ sort_order: int+++class Reordering:+ def __init__(self, qs: QuerySet, operations: Dict[int, int], 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+ # actually were changed+ self.old_sort_map = {}++ # Will contain the list of keys kept+ # in correct order in accordance to their sort order+ self.ordered_pks = []++ @cached_property+ def ordered_node_map(self):+ ordering_map = OrderedDict(+ self.qs.select_for_update()+ .values_list("pk", "sort_order")+ .order_by(F("sort_order").asc(nulls_last=True), "id")+ )+ self.old_sort_map = ordering_map.copy()+ self.ordered_pks = list(ordering_map.keys())++ previous_sort_order = 0++ # Add sort order to null values+ for pk, sort_order in ordering_map.items():+ if sort_order is not None:+ previous_sort_order = sort_order+ continue++ previous_sort_order += 1+ ordering_map[pk] = previous_sort_order++ return ordering_map++ def calculate_new_sort_order(self, pk, move) -> Tuple[int, int, int]:+ """Returns the proper sort order for the current operation to properly+ move the node in a given direction with by amount.++ This ensures the new sort order is not biased from gaps between+ the sort orders."""++ # Retrieve the position of the node to move+ node_pos = self.ordered_pks.index(pk)++ # Set the target position from the current position+ # of the node + the relative position to move from+ target_pos = node_pos + move++ # Make sure we are not getting out of bounds+ target_pos = max(0, target_pos)+ target_pos = min(len(self.ordered_pks) - 1, target_pos)++ # Retrieve the target node and its sort order+ target_pk = self.ordered_pks[target_pos]+ target_position = self.ordered_node_map[target_pk]++ # Return the new position+ return node_pos, target_pos, target_position++ def process_move_operation(self, pk, move):+ old_sort_order = self.ordered_node_map[pk]++ # Skip if noting to do+ if move == 0:+ warnings.warn(+ f"Ignored node's reordering, did not find: {pk} "+ f"(from {self.qs.model.__name__})"+ )+ return++ node_pos, target_pos, new_sort_order = self.calculate_new_sort_order(pk, move)++ # Determine how we should shift for this operation+ if move > 0:+ shift = -1+ range_ = old_sort_order + 1, new_sort_order+ else:+ shift = +1+ range_ = new_sort_order, old_sort_order - 1++ # Shift the sort orders within the moving range+ self.add_to_sort_value_if_in_range(shift, *range_)++ # Update the sort order of the node to move+ self.ordered_node_map[pk] = new_sort_order++ # Reorder the pk list+ self.ordered_pks.remove(pk)+ self.ordered_pks.insert(target_pos, pk)++ def add_to_sort_value_if_in_range(self, value_to_add, start, end):+ for pk, sort_order in self.ordered_node_map.items():+ if not start <= sort_order <= end:+ continue++ self.ordered_node_map[pk] += value_to_add++ def commit(self):+ # Do nothing if nothing was done+ if not self.old_sort_map:+ return++ # Create the bulk update to run+ # But only if data was changed+ batch = [+ FinalSortOrder(pk, sort_order)+ for pk, sort_order in self.ordered_node_map.items()+ if sort_order != self.old_sort_map[pk]+ ]++ # Do not update if nothing changed+ if not batch:+ return++ # Update everything that was changed+ self.qs.model.objects.bulk_update(batch, ["sort_order"])++ def run(self):++ for pk, move in self.operations.items():+ # Skip operation if it was deleted in concurrence+ if pk not in self.ordered_node_map:+ continue++ self.process_move_operation(pk, move)++ self.commit()+++def perform_reordering(qs: QuerySet, operations: Dict[int, int], field: str = "moves"):+ """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.++ :param qs: The query set on which we want to retrieve and reorder the node.+ :param operations: The operations to make: {pk_to_move: +/- 123}.+ :param field: The field from which nodes are resolved.++ :raises RuntimeError: If the bulk operation is not run inside an atomic transaction.+ """++ if not transaction.get_connection().in_atomic_block:+ raise RuntimeError("Needs to be run inside an atomic transaction")++ Reordering(qs, operations, field).run()diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex e64c11c87b..d252a1fec1 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -7,7 +7,6 @@ from django.db.models import Qfrom django.template.defaultfilters import slugifyfrom ....product import AttributeInputType, models-from ...core.interfaces import MoveOperationfrom ...core.mutations import (BaseMutation,ClearMetaBaseMutation,@@ -15,11 +14,12 @@ from ...core.mutations import (ModelMutation,UpdateMetaBaseMutation,)-from ...core.utils import from_global_id_strict_type, perform_reordering+from ...core.utils import from_global_id_strict_type+from ...core.utils.reordering import perform_reorderingfrom ...product.types import ProductTypefrom ..descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom ..enums import AttributeInputTypeEnum, AttributeTypeEnum-from ..types import Attribute+from ..types import Attribute, AttributeValueclass AttributeValueCreateInput(graphene.InputObjectType):@@ -96,12 +96,11 @@ class AttributeAssignInput(graphene.InputObjectType):)-class AttributeReorderInput(graphene.InputObjectType):- id = graphene.ID(required=True, description="The ID of the attribute to move")+class ReorderInput(graphene.InputObjectType):+ id = graphene.ID(required=True, description="The ID of the item to move")sort_order = graphene.Int(description=(- "The relative sorting position of the attribute (from -inf to +inf) "- "starting from the first given attribute's actual position."+ "The new relative sorting position of the item (from -inf to +inf)"))@@ -598,14 +597,14 @@ class ProductTypeReorderAttributes(BaseMutation):required=True, description="The attribute type to reorder.")moves = graphene.List(- AttributeReorderInput,+ ReorderInput,required=True,description="The list of attribute reordering operations.",)@classmethoddef perform_mutation(cls, _root, info, product_type_id, type, moves):- product_type_id = from_global_id_strict_type(+ pk = from_global_id_strict_type(info, product_type_id, only_type=ProductType, field="product_type_id")@@ -614,26 +613,91 @@ class ProductTypeReorderAttributes(BaseMutation):else:m2m_field = "attributevariant"- product_type = models.ProductType.objects.prefetch_related(m2m_field).get(- pk=product_type_id- )+ try:+ product_type = models.ProductType.objects.prefetch_related(m2m_field).get(+ pk=pk+ )+ except ObjectDoesNotExist:+ raise ValidationError(+ {+ "product_type_id": (+ f"Couldn't resolve to a product type: {product_type_id}"+ )+ }+ )attributes_m2m = getattr(product_type, m2m_field)- operations = []+ operations = {}+ # Resolve the attributesfor move_info in moves:- attribute_id = from_global_id_strict_type(+ attribute_pk = from_global_id_strict_type(info, move_info.id, only_type=Attribute, field="moves")try:- node = attributes_m2m.get(attribute_id=attribute_id)+ m2m_info = attributes_m2m.get(attribute_id=int(attribute_pk))except ObjectDoesNotExist:raise ValidationError(- {"moves": "Couldn't resolve to an attribute: %s" % move_info.id}+ {"moves": f"Couldn't resolve to an attribute: {move_info.id}"})+ operations[m2m_info.pk] = move_info.sort_order- operations.append(MoveOperation(node=node, sort_order=move_info.sort_order))-- perform_reordering(operations)+ with transaction.atomic():+ perform_reordering(attributes_m2m, operations)return ProductTypeReorderAttributes(product_type=product_type)+++class AttributeReorderValues(BaseMutation):+ attribute = graphene.Field(+ Attribute, description="Attribute from which values are reordered."+ )++ class Meta:+ description = "Reorder the values of an attribute"+ permissions = ("product.manage_products",)++ class Arguments:+ attribute_id = graphene.Argument(+ graphene.ID, required=True, description="ID of an attribute."+ )+ moves = graphene.List(+ ReorderInput,+ required=True,+ description="The list of reordering operations for given attribute values.",+ )++ @classmethod+ def perform_mutation(cls, _root, info, attribute_id, moves):+ pk = from_global_id_strict_type(+ info, attribute_id, only_type=Attribute, field="attribute_id"+ )++ try:+ attribute = models.Attribute.objects.prefetch_related("values").get(pk=pk)+ except ObjectDoesNotExist:+ raise ValidationError(+ {"attribute_id": (f"Couldn't resolve to an attribute: {attribute_id}")}+ )++ values_m2m = attribute.values+ operations = {}++ # Resolve the values+ for move_info in moves:+ value_pk = from_global_id_strict_type(+ info, move_info.id, only_type=AttributeValue, field="moves"+ )++ try:+ m2m_info = values_m2m.get(pk=int(value_pk))+ except ObjectDoesNotExist:+ raise ValidationError(+ {"moves": f"Couldn't resolve to an attribute value: {move_info.id}"}+ )+ operations[m2m_info.pk] = move_info.sort_order++ with transaction.atomic():+ perform_reordering(values_m2m, operations)+ attribute.refresh_from_db(fields=["values"])+ return AttributeReorderValues(attribute=attribute)diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 6c6667f353..de128e8b54 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -1,7 +1,7 @@from typing import Dict, Listimport graphene-from django.core.exceptions import ValidationError+from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transactionfrom django.template.defaultfilters import slugifyfrom graphene.types import InputObjectType@@ -15,7 +15,6 @@ from ....product.thumbnails import ()from ....product.utils.attributes import get_name_from_attributesfrom ...core.enums import TaxRateType-from ...core.interfaces import MoveOperationfrom ...core.mutations import (BaseMutation,ClearMetaBaseMutation,@@ -28,9 +27,9 @@ from ...core.types import SeoInput, Uploadfrom ...core.utils import (clean_seo_fields,from_global_id_strict_type,- perform_reordering,validate_image_file,)+from ...core.utils.reordering import perform_reorderingfrom ..types import (Attribute,Category,@@ -228,28 +227,39 @@ class CollectionReorderProducts(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, collection_id, moves):- collection = cls.get_node_or_error(- info, collection_id, field="collection_id", only_type=Collection+ pk = from_global_id_strict_type(+ info, collection_id, only_type=Collection, field="collection_id")- operations = []+ try:+ collection = models.Collection.objects.prefetch_related(+ "collectionproduct"+ ).get(pk=pk)+ except ObjectDoesNotExist:+ raise ValidationError(+ {"collection_id": f"Couldn't resolve to a collection: {collection_id}"}+ )++ m2m_related_field = collection.collectionproduct++ operations = {}++ # Resolve the productsfor move_info in moves:- product_id = from_global_id_strict_type(+ product_pk = from_global_id_strict_type(info, move_info.product_id, only_type=Product, field="moves")try:- node = models.CollectionProduct.objects.get(- product_id=product_id, collection_id=collection.id- )- except models.CollectionProduct.DoesNotExist:+ m2m_info = m2m_related_field.get(product_id=int(product_pk))+ except ObjectDoesNotExist:raise ValidationError(- {"moves": "Couldn't resolve to a product: %s" % product_id}+ {"moves": f"Couldn't resolve to a product: {move_info.product_id}"})+ operations[m2m_info.pk] = move_info.sort_order- operations.append(MoveOperation(node=node, sort_order=move_info.sort_order))-- perform_reordering(operations)+ with transaction.atomic():+ perform_reordering(m2m_related_field, operations)return CollectionReorderProducts(collection=collection)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 55b06a66c6..686163e328 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -32,6 +32,7 @@ from .mutations.attributes import (AttributeClearPrivateMeta,AttributeCreate,AttributeDelete,+ AttributeReorderValues,AttributeUnassign,AttributeUpdate,AttributeUpdateMeta,@@ -318,6 +319,7 @@ class ProductMutations(graphene.ObjectType):attribute_value_bulk_delete = AttributeValueBulkDelete.Field()attribute_value_update = AttributeValueUpdate.Field()attribute_value_translate = AttributeValueTranslate.Field()+ attribute_reorder_values = AttributeReorderValues.Field()category_create = CategoryCreate.Field()category_delete = CategoryDelete.Field()diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/product/types/attributes.pyindex 10cb48aa32..1ec0e4a44c 100644--- a/saleor/graphql/product/types/attributes.py+++ b/saleor/graphql/product/types/attributes.py@@ -72,7 +72,7 @@ class AttributeValue(CountableDjangoObjectType):class Meta:description = "Represents a value of an attribute."- only_fields = ["id", "sort_order"]+ only_fields = ["id"]interfaces = [relay.Node]model = models.AttributeValuediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1b96039f1b..905ef27989 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -240,6 +240,11 @@ enum AttributeInputTypeEnum {MULTISELECT}+type AttributeReorderValues {+ errors: [Error!]+ attribute: Attribute+}+scalar AttributeScalarenum AttributeSortField {@@ -312,7 +317,6 @@ type AttributeUpdatePrivateMeta {}type AttributeValue implements Node {- sortOrder: Int!id: ID!name: Stringslug: String@@ -1613,7 +1617,7 @@ input MenuInput {type MenuItem implements Node {id: ID!- sortOrder: Int!+ sortOrder: Intmenu: Menu!name: String!parent: MenuItem@@ -1780,6 +1784,7 @@ type Mutations {attributeValueBulkDelete(ids: [ID]!): AttributeValueBulkDeleteattributeValueUpdate(id: ID!, input: AttributeValueCreateInput!): AttributeValueUpdateattributeValueTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): AttributeValueTranslate+ attributeReorderValues(attributeId: ID!, moves: [ReorderInput]!): AttributeReorderValuescategoryCreate(input: CategoryInput!, parent: ID): CategoryCreatecategoryDelete(id: ID!): CategoryDeletecategoryBulkDelete(ids: [ID]!): CategoryBulkDelete@@ -1821,6 +1826,7 @@ type Mutations {productTypeDelete(id: ID!): ProductTypeDeleteproductTypeBulkDelete(ids: [ID]!): ProductTypeBulkDeleteproductTypeUpdate(id: ID!, input: ProductTypeInput!): ProductTypeUpdate+ productTypeReorderAttributes(moves: [ReorderInput]!, productTypeId: ID!, type: AttributeTypeEnum!): ProductTypeReorderAttributesproductTypeUpdateMetadata(id: ID!, input: MetaInput!): ProductTypeUpdateMetaproductTypeClearMetadata(id: ID!, input: MetaPath!): ProductTypeClearMetaproductTypeUpdatePrivateMetadata(id: ID!, input: MetaInput!): ProductTypeUpdatePrivateMeta@@ -2527,7 +2533,7 @@ input ProductFilterInput {}type ProductImage implements Node {- sortOrder: Int!+ sortOrder: Intid: ID!alt: String!url(size: Int): String!@@ -2709,6 +2715,11 @@ input ProductTypeInput {taxCode: String}+type ProductTypeReorderAttributes {+ errors: [Error!]+ productType: ProductType+}+type ProductTypeUpdate {errors: [Error!]productType: ProductType@@ -2913,6 +2924,11 @@ type Refresh {payload: GenericScalar}+input ReorderInput {+ id: ID!+ sortOrder: Int+}+enum ReportingPeriod {TODAYTHIS_MONTHdiff --git a/saleor/menu/migrations/0015_auto_20190725_0811.py b/saleor/menu/migrations/0015_auto_20190725_0811.pynew file mode 100644index 0000000000..080380986d--- /dev/null+++ b/saleor/menu/migrations/0015_auto_20190725_0811.py@@ -0,0 +1,16 @@+# Generated by Django 2.2.3 on 2019-07-25 13:11++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [("menu", "0014_auto_20190523_0759")]++ operations = [+ migrations.AlterField(+ model_name="menuitem",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ )+ ]diff --git a/saleor/menu/migrations/0015_remove_null_sort_order.py b/saleor/menu/migrations/0015_remove_null_sort_order.pydeleted file mode 100644index fd86fe8331..0000000000--- a/saleor/menu/migrations/0015_remove_null_sort_order.py+++ /dev/null@@ -1,33 +0,0 @@-# Generated by Django 2.2.3 on 2019-07-17 11:26--from django.db import migrations, models-from django.db.models import Max---def set_default_position_menu_item(apps, schema_editor):- MenuItem = apps.get_model("menu", "MenuItem")-- existing_max = MenuItem.objects.aggregate(Max("sort_order"))- existing_max = existing_max.get("sort_order__max") or 0-- for sort_order, item in enumerate(- MenuItem.objects.filter(sort_order=None), existing_max + 1- ):- item.sort_order = sort_order- item.save(update_fields=["sort_order"])---class Migration(migrations.Migration):-- dependencies = [("menu", "0014_auto_20190523_0759")]-- operations = [- migrations.RunPython(set_default_position_menu_item),- migrations.AlterField(- model_name="menuitem",- name="sort_order",- field=models.PositiveIntegerField(- db_index=True, default=0, editable=False, null=False- ),- ),- ]diff --git a/saleor/product/migrations/0100_auto_20190626_0815.py b/saleor/product/migrations/0100_auto_20190626_0815.pydeleted file mode 100644index fd139d1269..0000000000--- a/saleor/product/migrations/0100_auto_20190626_0815.py+++ /dev/null@@ -1,21 +0,0 @@-# Generated by Django 2.2.2 on 2019-06-26 13:15--from django.db import migrations, models---class Migration(migrations.Migration):-- dependencies = [("product", "0099_attribute_input_type_multiple_values")]-- operations = [- migrations.AddField(- model_name="attributeproduct",- name="sort_order",- field=models.PositiveIntegerField(db_index=True, editable=False, null=True),- ),- migrations.AddField(- model_name="attributevariant",- name="sort_order",- field=models.PositiveIntegerField(db_index=True, editable=False, null=True),- ),- ]diff --git a/saleor/product/migrations/0101_remove_null_sort_order.py b/saleor/product/migrations/0101_remove_null_sort_order.pydeleted file mode 100644index 830240915c..0000000000--- a/saleor/product/migrations/0101_remove_null_sort_order.py+++ /dev/null@@ -1,89 +0,0 @@-# Generated by Django 2.2.3 on 2019-07-17 11:26--from django.db import migrations, models-from django.db.models import Max---def _set_default_position(qs):- existing_max = qs.aggregate(Max("sort_order"))- existing_max = existing_max.get("sort_order__max") or 0-- for sort_order, item in enumerate(qs.filter(sort_order=None), existing_max + 1):- item.sort_order = sort_order- item.save(update_fields=["sort_order"])---def set_default_position_m2m(model_name, fk_name):- def _wrapped(apps, schema_editor):- attribute_m2m = apps.get_model("product", model_name)- foreigners = attribute_m2m.objects.distinct().values_list(fk_name, flat=True)-- for pk in foreigners:- _set_default_position(attribute_m2m.objects.filter(**{fk_name: pk}))-- return _wrapped---def set_default_position_m2o(model_name):- def _wrapped(apps, schema_editor):- attribute_m2m = apps.get_model("product", model_name)- _set_default_position(attribute_m2m.objects)-- return _wrapped---class Migration(migrations.Migration):-- dependencies = [("product", "0100_auto_20190626_0815")]-- operations = [- # m2m models- migrations.RunPython(- set_default_position_m2m("AttributeProduct", "product_type_id")- ),- migrations.RunPython(- set_default_position_m2m("AttributeVariant", "product_type_id")- ),- migrations.RunPython(- set_default_position_m2m("CollectionProduct", "collection_id")- ),- # m2o models- migrations.RunPython(set_default_position_m2o("AttributeValue")),- migrations.RunPython(set_default_position_m2o("ProductImage")),- # drop nulls- migrations.AlterField(- model_name="attributeproduct",- name="sort_order",- field=models.PositiveIntegerField(- db_index=True, editable=False, default=0, null=False- ),- ),- migrations.AlterField(- model_name="attributevariant",- name="sort_order",- field=models.PositiveIntegerField(- db_index=True, editable=False, default=0, null=False- ),- ),- migrations.AlterField(- model_name="collectionproduct",- name="sort_order",- field=models.PositiveIntegerField(- db_index=True, editable=False, default=0, null=False- ),- ),- migrations.AlterField(- model_name="attributevalue",- name="sort_order",- field=models.PositiveIntegerField(- db_index=True, editable=False, default=0, null=False- ),- ),- migrations.AlterField(- model_name="productimage",- name="sort_order",- field=models.PositiveIntegerField(- db_index=True, editable=False, default=0, null=False- ),- ),- ]diff --git a/saleor/product/migrations/0097_auto_20190611_0952.py b/saleor/product/migrations/0102_unique_slug_attributes.pysimilarity index 93%rename from saleor/product/migrations/0097_auto_20190611_0952.pyrename to saleor/product/migrations/0102_unique_slug_attributes.pyindex 445dedcaff..8abeeb1ea7 100644--- a/saleor/product/migrations/0097_auto_20190611_0952.py+++ b/saleor/product/migrations/0102_unique_slug_attributes.py@@ -19,7 +19,7 @@ def ensure_attribute_slugs_are_unique_or_fix(apps, schema_editor):class Migration(migrations.Migration):- dependencies = [("product", "0096_raw_html_to_json")]+ dependencies = [("product", "0101_auto_20190719_0839")]operations = [migrations.RunPython(ensure_attribute_slugs_are_unique_or_fix),diff --git a/saleor/product/migrations/0102_attribute_available_in_grid.py b/saleor/product/migrations/0103_attribute_available_in_grid.pysimilarity index 84%rename from saleor/product/migrations/0102_attribute_available_in_grid.pyrename to saleor/product/migrations/0103_attribute_available_in_grid.pyindex 2e59f12705..7065dfa1bc 100644--- a/saleor/product/migrations/0102_attribute_available_in_grid.py+++ b/saleor/product/migrations/0103_attribute_available_in_grid.py@@ -5,7 +5,7 @@ from django.db import migrations, modelsclass Migration(migrations.Migration):- dependencies = [("product", "0101_remove_null_sort_order")]+ dependencies = [("product", "0102_unique_slug_attributes")]operations = [migrations.AddField(diff --git a/saleor/product/migrations/0098_migrate_attrs_to_m2m.py b/saleor/product/migrations/0103_migrate_attrs_to_m2m.pysimilarity index 98%rename from saleor/product/migrations/0098_migrate_attrs_to_m2m.pyrename to saleor/product/migrations/0103_migrate_attrs_to_m2m.pyindex 0c5573fc39..0a2f00ffb5 100644--- a/saleor/product/migrations/0098_migrate_attrs_to_m2m.py+++ b/saleor/product/migrations/0103_migrate_attrs_to_m2m.py@@ -21,7 +21,7 @@ def migrate_fk_to_m2m(product_type_related_field):class Migration(migrations.Migration):- dependencies = [("product", "0097_auto_20190611_0952")]+ dependencies = [("product", "0103_attribute_available_in_grid")]operations = [migrations.AddField(diff --git a/saleor/product/migrations/0099_attribute_input_type_multiple_values.py b/saleor/product/migrations/0104_attribute_input_type_multiple_values.pysimilarity index 96%rename from saleor/product/migrations/0099_attribute_input_type_multiple_values.pyrename to saleor/product/migrations/0104_attribute_input_type_multiple_values.pyindex 6f43422f92..9713c830e5 100644--- a/saleor/product/migrations/0099_attribute_input_type_multiple_values.py+++ b/saleor/product/migrations/0104_attribute_input_type_multiple_values.py@@ -27,7 +27,7 @@ def migrate_attributes_to_list(model_name):class Migration(migrations.Migration):- dependencies = [("product", "0098_migrate_attrs_to_m2m")]+ dependencies = [("product", "0103_migrate_attrs_to_m2m")]operations = [migrations.AddField(diff --git a/saleor/product/migrations/0103_remove_dups.py b/saleor/product/migrations/0105_remove_dups.pysimilarity index 95%rename from saleor/product/migrations/0103_remove_dups.pyrename to saleor/product/migrations/0105_remove_dups.pyindex 505c81bb57..f192a49f70 100644--- a/saleor/product/migrations/0103_remove_dups.py+++ b/saleor/product/migrations/0105_remove_dups.py@@ -42,7 +42,7 @@ def remove_duplicates(apps, schema_editor):class Migration(migrations.Migration):- dependencies = [("product", "0102_attribute_available_in_grid")]+ dependencies = [("product", "0104_attribute_input_type_multiple_values")]operations = [migrations.RunPython(remove_duplicates),diff --git a/saleor/product/migrations/0106_nullable_sort_logic.py b/saleor/product/migrations/0106_nullable_sort_logic.pynew file mode 100644index 0000000000..7e49db3488--- /dev/null+++ b/saleor/product/migrations/0106_nullable_sort_logic.py@@ -0,0 +1,63 @@+# Generated by Django 2.2.3 on 2019-07-25 13:11++from dataclasses import dataclass++from django.db import migrations, models+from django.db.models import F, Window+from django.db.models.functions import RowNumber+++@dataclass(frozen=True)+class NewCollectionProductSortOrder:+ pk: int+ sort_order: int+++def reorder_collection_products(apps, schema_editor):+ CollectionProduct = apps.get_model("product", "CollectionProduct")+ new_values = CollectionProduct.objects.values("id").annotate(+ sort_order=Window(+ expression=RowNumber(),+ order_by=(F("sort_order").asc(nulls_last=True), "id"),+ )+ )++ batch = [NewCollectionProductSortOrder(*row.values()) for row in new_values]+ CollectionProduct.objects.bulk_update(batch, ["sort_order"])+++class Migration(migrations.Migration):++ dependencies = [("product", "0105_remove_dups")]++ operations = [+ migrations.RunPython(reorder_collection_products),+ migrations.AddField(+ model_name="attributeproduct",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ migrations.AddField(+ model_name="attributevariant",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ migrations.AlterField(+ model_name="attributevalue",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ migrations.AlterField(+ model_name="collectionproduct",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ migrations.AlterField(+ model_name="productimage",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ migrations.AlterModelOptions(+ name="attributevalue", options={"ordering": ("sort_order", "id")}+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 188f2d58b0..9e5e713e42 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -7,7 +7,7 @@ from django.contrib.postgres.fields import JSONFieldfrom django.core import exceptionsfrom django.core.validators import MinValueValidatorfrom django.db import models-from django.db.models import Q+from django.db.models import F, Qfrom django.urls import reversefrom django.utils.encoding import smart_textfrom django.utils.html import strip_tags@@ -145,7 +145,10 @@ class ProductsQueryset(PublishedQuerySet):qs = self.visible_to_user(user).prefetch_related("collections__products__collectionproduct")- qs = qs.order_by("collectionproduct__sort_order")+ qs = qs.order_by(+ F("collectionproduct__sort_order").asc(nulls_last=True),+ F("collectionproduct__id"),+ )return qs@@ -508,13 +511,23 @@ class AttributeQuerySet(models.QuerySet):return self.all()return self.get_public_attributes()+ def _get_sorted_m2m_field(self, m2m_field_name: str, asc: bool):+ sort_order_field = F(f"{m2m_field_name}__sort_order")+ id_field = F(f"{m2m_field_name}__id")+ if asc:+ sort_method = sort_order_field.asc(nulls_last=True)+ id_sort = id_field+ else:+ sort_method = sort_order_field.desc(nulls_first=True)+ id_sort = id_field.desc()++ return self.order_by(sort_method, id_sort)+def product_attributes_sorted_for_dashboard(self, asc=True):- direction = "" if asc else "-"- return self.order_by(f"{direction}attributeproduct__sort_order")+ return self._get_sorted_m2m_field("attributeproduct", asc)def variant_attributes_sorted_for_dashboard(self, asc=True):- direction = "" if asc else "-"- return self.order_by(f"{direction}attributevariant__sort_order")+ return self._get_sorted_m2m_field("attributevariant", asc)class Attribute(ModelWithMetadata):@@ -602,7 +615,7 @@ class AttributeValue(SortableModel):translated = TranslationProxy()class Meta:- ordering = ("sort_order",)+ ordering = ("sort_order", "id")unique_together = ("name", "attribute")def __str__(self):diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex 21a5edae32..db5d2cb141 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -6,6 +6,7 @@ from django.db.models import Qfrom django.template.defaultfilters import slugifyfrom graphene.utils.str_converters import to_camel_case+from saleor.graphql.core.utils import snake_to_camel_casefrom saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueTypefrom saleor.graphql.product.types.attributes import resolve_attribute_value_typefrom saleor.graphql.product.types.products import resolve_attribute_list@@ -1396,7 +1397,7 @@ def test_retrieving_the_restricted_attributes_restricted(ATTRIBUTES_RESORT_QUERY = """mutation ProductTypeReorderAttributes($productTypeId: ID!- $moves: [AttributeReorderInput]!+ $moves: [ReorderInput]!$type: AttributeTypeEnum!) {productTypeReorderAttributes(@@ -1405,6 +1406,7 @@ ATTRIBUTES_RESORT_QUERY = """type: $type) {productType {+ idvariantAttributes {idslug@@ -1423,6 +1425,34 @@ ATTRIBUTES_RESORT_QUERY = """"""+def test_sort_attributes_within_product_type_invalid_product_type(+ staff_api_client, permission_manage_products+):+ """Try to reorder an invalid product type (invalid ID)."""++ product_type_id = graphene.Node.to_global_id("ProductType", -1)+ attribute_id = graphene.Node.to_global_id("Attribute", -1)++ variables = {+ "type": "VARIANT",+ "productTypeId": product_type_id,+ "moves": [{"id": attribute_id, "sortOrder": 1}],+ }++ content = get_graphql_content(+ staff_api_client.post_graphql(+ ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products]+ )+ )["data"]["productTypeReorderAttributes"]++ assert content["errors"] == [+ {+ "field": "productTypeId",+ "message": f"Couldn't resolve to a product type: {product_type_id}",+ }+ ]++def test_sort_attributes_within_product_type_invalid_id(staff_api_client, permission_manage_products, color_attribute):@@ -1460,7 +1490,7 @@ def test_sort_attributes_within_product_type_invalid_id(("PRODUCT", "product_attributes", "attributeproduct"),),)-def test_sort_variant_attributes_within_product_type(+def test_sort_attributes_within_product_type(staff_api_client,attribute_list,permission_manage_products,@@ -1468,35 +1498,186 @@ def test_sort_variant_attributes_within_product_type(relation_field,backref_field,):+ attributes = attribute_list+ assert len(attributes) == 3+staff_api_client.user.user_permissions.add(permission_manage_products)product_type = ProductType.objects.create(name="Dummy Type")product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)- getattr(product_type, relation_field).set(attribute_list)+ m2m_attributes = getattr(product_type, relation_field)+ m2m_attributes.set(attributes)++ sort_method = getattr(m2m_attributes, f"{relation_field}_sorted_for_dashboard")+ attributes = list(sort_method())++ assert len(attributes) == 3variables = {"type": attribute_type,"productTypeId": product_type_id,"moves": [- {"id": graphene.Node.to_global_id("Attribute", attr.id), "sortOrder": 0}- for attr in attribute_list+ {+ "id": graphene.Node.to_global_id("Attribute", attributes[0].pk),+ "sortOrder": +1,+ },+ {+ "id": graphene.Node.to_global_id("Attribute", attributes[2].pk),+ "sortOrder": -1,+ },],}+ expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk]+content = get_graphql_content(staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables))["data"]["productTypeReorderAttributes"]assert not content["errors"]- gql_attributes = content["productType"]["variantAttributes"]- current_sort_pos = 0- for gql_attr, db_attr in zip(gql_attributes, attribute_list):- assert getattr(db_attr, backref_field).last().sort_order == current_sort_pos+ assert (+ content["productType"]["id"] == product_type_id+ ), "Did not return the correct product type"++ gql_attributes = content["productType"][snake_to_camel_case(relation_field)]+ assert len(gql_attributes) == len(expected_order)++ for attr, expected_pk in zip(gql_attributes, expected_order):+ gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])+ assert gql_type == "Attribute"+ assert int(gql_attr_id) == expected_pk+++ATTRIBUTE_VALUES_RESORT_QUERY = """+ mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) {+ attributeReorderValues(attributeId: $attributeId, moves: $moves) {+ attribute {+ id+ values {+ id+ }+ }++ errors {+ field+ message+ }+ }+ }+"""+++def test_sort_values_within_attribute_invalid_product_type(+ staff_api_client, permission_manage_products+):+ """Try to reorder an invalid attribute (invalid ID)."""++ attribute_id = graphene.Node.to_global_id("Attribute", -1)+ value_id = graphene.Node.to_global_id("AttributeValue", -1)++ variables = {+ "attributeId": attribute_id,+ "moves": [{"id": value_id, "sortOrder": 1}],+ }++ content = get_graphql_content(+ staff_api_client.post_graphql(+ ATTRIBUTE_VALUES_RESORT_QUERY,+ variables,+ permissions=[permission_manage_products],+ )+ )["data"]["attributeReorderValues"]++ assert content["errors"] == [+ {+ "field": "attributeId",+ "message": f"Couldn't resolve to an attribute: {attribute_id}",+ }+ ]+++def test_sort_values_within_attribute_invalid_id(+ staff_api_client, permission_manage_products, color_attribute+):+ """Try to reorder a value not associated to the given attribute."""++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)+ value_id = graphene.Node.to_global_id("AttributeValue", -1)++ variables = {+ "type": "VARIANT",+ "attributeId": attribute_id,+ "moves": [{"id": value_id, "sortOrder": 1}],+ }++ content = get_graphql_content(+ staff_api_client.post_graphql(+ ATTRIBUTE_VALUES_RESORT_QUERY,+ variables,+ permissions=[permission_manage_products],+ )+ )["data"]["attributeReorderValues"]++ assert content["errors"] == [+ {+ "field": "moves",+ "message": f"Couldn't resolve to an attribute value: {value_id}",+ }+ ]+++def test_sort_values_within_attribute(+ staff_api_client, color_attribute, permission_manage_products+):+ attribute = color_attribute+ AttributeValue.objects.create(attribute=attribute, name="Green", slug="green")+ values = list(attribute.values.all())+ assert len(values) == 3++ staff_api_client.user.user_permissions.add(permission_manage_products)++ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)+ m2m_values = attribute.values+ m2m_values.set(values)++ assert values == sorted(+ values, key=lambda o: o.sort_order if o.sort_order is not None else o.pk+ ), "The values are not properly ordered"++ variables = {+ "attributeId": attribute_id,+ "moves": [+ {+ "id": graphene.Node.to_global_id("AttributeValue", values[0].pk),+ "sortOrder": +1,+ },+ {+ "id": graphene.Node.to_global_id("AttributeValue", values[2].pk),+ "sortOrder": -1,+ },+ ],+ }++ expected_order = [values[1].pk, values[2].pk, values[0].pk]++ content = get_graphql_content(+ staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables)+ )["data"]["attributeReorderValues"]+ assert not content["errors"]++ assert content["attribute"]["id"] == attribute_id++ gql_values = content["attribute"]["values"]+ assert len(gql_values) == len(expected_order)++ actual_order = []- _, gql_attr_id = graphene.Node.from_global_id(gql_attr["id"])- assert gql_attr_id == str(db_attr.pk)+ for attr, expected_pk in zip(gql_values, expected_order):+ gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])+ assert gql_type == "AttributeValue"+ actual_order.append(int(gql_attr_id))- current_sort_pos += 1+ assert actual_order == expected_orderATTRIBUTES_FILTER_QUERY = """diff --git a/tests/api/test_core_reordering.py b/tests/api/test_core_reordering.pynew file mode 100644index 0000000000..775c8c01ed--- /dev/null+++ b/tests/api/test_core_reordering.py@@ -0,0 +1,327 @@+from unittest.mock import patch++import pytest++from saleor.graphql.core.utils.reordering import perform_reordering+from saleor.product import models++SortedModel = models.AttributeValue+++def _sorted_by_order(items):+ return sorted(items, key=lambda o: o[1])+++def _get_sorted_map():+ return list(+ SortedModel.objects.values_list("pk", "sort_order").order_by("sort_order")+ )+++def dummy_attribute():+ return models.Attribute.objects.create(name="Dummy")+++def sorted_entries_seq(dummy_attribute):+ attribute = dummy_attribute+ values = SortedModel.objects.bulk_create(+ [+ SortedModel(+ attribute=attribute, slug=f"value-{i}", name=f"Value-{i}", sort_order=i+ )+ for i in range(6)+ ]+ )+ return list(values)+++def sorted_entries_gaps(dummy_attribute):+ attribute = dummy_attribute+ values = SortedModel.objects.bulk_create(+ [+ SortedModel(+ attribute=attribute, slug=f"value-{i}", name=f"Value-{i}", sort_order=i+ )+ for i in range(0, 12, 2)+ ]+ )+ return list(values)+++def test_reordering_sequential(sorted_entries_seq):+ """+ Ensures the reordering logic works as expected. This test simply provides+ sequential sort order values and try to reorder them.+ """+ qs = SortedModel.objects+ nodes = sorted_entries_seq++ operations = {nodes[5].pk: -1, nodes[2].pk: +3}++ expected = _sorted_by_order(+ [+ (nodes[0].pk, 0),+ (nodes[1].pk, 1),+ (nodes[2].pk, 2 + 3),+ (nodes[3].pk, 3 - 1),+ (nodes[4].pk, 4 + 1 - 1),+ (nodes[5].pk, 5 - 1 - 1),+ ]+ )++ perform_reordering(qs, operations)++ actual = _get_sorted_map()+ assert actual == expected+++def test_reordering_non_sequential(sorted_entries_gaps):+ """+ Ensures that reordering non-sequential sort order values is properly+ handled. This case happens when an item gets deleted, creating gaps between values.+ """+ qs = SortedModel.objects+ nodes = sorted_entries_gaps++ operations = {nodes[5].pk: -1, nodes[2].pk: +3}++ expected = _sorted_by_order(+ [+ (nodes[0].pk, 0),+ (nodes[1].pk, 2),+ (nodes[2].pk, 4 + (3 * 2) - 1),+ (nodes[3].pk, 6 - 1),+ (nodes[4].pk, 8 + 1 - 1),+ (nodes[5].pk, 10 - (1 * 2) - 1),+ ]+ )++ perform_reordering(qs, operations)++ actual = _get_sorted_map()+ assert actual == expected+++ "operation, expected_operations",+ [((0, +5), (+5, -1, -1, -1, -1, -1)), ((5, -5), (+1, +1, +1, +1, +1, -5))],+)+def test_inserting_at_the_edges(sorted_entries_seq, operation, expected_operations):+ """+ Ensures it is possible to move an item at the top and bottom of the list.+ """+ qs = SortedModel.objects+ nodes = sorted_entries_seq++ target_node_pos, new_rel_sort_order = operation++ operations = {nodes[target_node_pos].pk: new_rel_sort_order}++ expected = _sorted_by_order(+ [+ (node.pk, node.sort_order + op)+ for node, op in zip(nodes, expected_operations)+ ]+ )++ perform_reordering(qs, operations)++ actual = _get_sorted_map()+ assert actual == expected+++def test_reordering_out_of_bound(sorted_entries_seq):+ """+ Ensures it is not possible to manually create gaps or for the users+ to insert anywhere they want, e.g. -1000, which could create a mess+ into the database.+ """+ qs = SortedModel.objects+ nodes = sorted_entries_seq++ operations = {nodes[5].pk: -100, nodes[0].pk: +100}++ expected = _sorted_by_order(+ [+ (nodes[0].pk, 0 + 5),+ (nodes[1].pk, 1),+ (nodes[2].pk, 2),+ (nodes[3].pk, 3),+ (nodes[4].pk, 4),+ (nodes[5].pk, 5 - 5),+ ]+ )++ perform_reordering(qs, operations)++ actual = _get_sorted_map()+ assert actual == expected+++def test_reordering_null_sort_orders(dummy_attribute):+ """+ Ensures null sort orders values are getting properly ordered (by ID sorting).+ """+ attribute = dummy_attribute+ qs = SortedModel.objects++ non_null_sorted_entries = list(+ qs.bulk_create(+ [+ SortedModel(+ pk=1, attribute=attribute, slug="1", name="1", sort_order=1+ ),+ SortedModel(+ pk=2, attribute=attribute, slug="2", name="2", sort_order=0+ ),+ ]+ )+ )++ null_sorted_entries = list(+ qs.bulk_create(+ [+ SortedModel(+ pk=5, attribute=attribute, slug="5", name="5", sort_order=None+ ),+ SortedModel(+ pk=4, attribute=attribute, slug="4", name="4", sort_order=None+ ),+ SortedModel(+ pk=3, attribute=attribute, slug="3", name="3", sort_order=None+ ),+ ]+ )+ )++ operations = {null_sorted_entries[0].pk: -2}++ expected = [+ (non_null_sorted_entries[1].pk, 0),+ (non_null_sorted_entries[0].pk, 1),+ (null_sorted_entries[0].pk, 2),+ (null_sorted_entries[2].pk, 3),+ (null_sorted_entries[1].pk, 4),+ ]++ perform_reordering(qs, operations)++ actual = _get_sorted_map()+ assert actual == expected+++@patch("saleor.graphql.core.utils.reordering.warnings.warn")+def test_reordering_nothing(mocked_warn, sorted_entries_seq, django_assert_num_queries):+ """+ Ensures giving operations that does nothing, are skipped. Thus only one query should+ have been made: fetching the nodes.+ """+ qs = SortedModel.objects+ pk = sorted_entries_seq[0].pk+ operations = {pk: 0}++ with django_assert_num_queries(1) as ctx:+ perform_reordering(qs, operations)++ mocked_warn.assert_called_with(+ f"Ignored node's reordering, did not find: {pk} (from AttributeValue)"+ )+ assert ctx[0]["sql"].startswith("SELECT "), "Should only have done a SELECT"+++def test_giving_no_operation_does_no_query(+ sorted_entries_seq, django_assert_num_queries+):+ """Ensures giving no operations runs no queries at all."""++ qs = SortedModel.objects++ with django_assert_num_queries(0):+ perform_reordering(qs, {})+++def test_reordering_concurrently(dummy_attribute, django_assert_num_queries):+ """+ Ensures users cannot concurrently reorder, they need to wait for the other one+ to achieve.++ This must be the first thing done before doing anything. For that, we ensure+ the first SQL query is acquiring the lock.+ """++ qs = SortedModel.objects+ attribute = dummy_attribute++ entries = list(+ qs.bulk_create(+ [+ SortedModel(+ pk=1, attribute=attribute, slug="1", name="1", sort_order=0+ ),+ SortedModel(+ pk=2, attribute=attribute, slug="2", name="2", sort_order=1+ ),+ ]+ )+ )++ operations = {entries[0].pk: +1}++ with django_assert_num_queries(2) as ctx:+ perform_reordering(qs, operations)++ assert ctx[0]["sql"] == (+ 'SELECT "product_attributevalue"."id", "product_attributevalue"."sort_order" '+ 'FROM "product_attributevalue" '+ "ORDER BY "+ '"product_attributevalue"."sort_order" ASC NULLS LAST, '+ '"product_attributevalue"."id" ASC FOR UPDATE'+ )+ assert ctx[1]["sql"] == (+ 'UPDATE "product_attributevalue" '+ 'SET "sort_order" = (CASE WHEN ("product_attributevalue"."id" = 1) '+ 'THEN 1 WHEN ("product_attributevalue"."id" = 2) '+ "THEN 0 ELSE NULL END)::integer "+ 'WHERE "product_attributevalue"."id" IN (1, 2)'+ )+++def test_reordering_deleted_node_from_concurrent(+ dummy_attribute, django_assert_num_queries+):+ """+ Ensures if a node was deleted before locking, it just skip it instead of+ raising an error.+ """++ qs = SortedModel.objects+ attribute = dummy_attribute++ entries = list(+ qs.bulk_create(+ [+ SortedModel(+ pk=1, attribute=attribute, slug="1", name="1", sort_order=0+ ),+ SortedModel(+ pk=2, attribute=attribute, slug="2", name="2", sort_order=1+ ),+ ]+ )+ )++ operations = {-1: +1, entries[0].pk: +1}++ with django_assert_num_queries(2) as ctx:+ perform_reordering(qs, operations)++ assert ctx[1]["sql"] == (+ 'UPDATE "product_attributevalue" '+ 'SET "sort_order" = (CASE WHEN ("product_attributevalue"."id" = 1) '+ 'THEN 1 WHEN ("product_attributevalue"."id" = 2) '+ "THEN 0 ELSE NULL END)::integer "+ 'WHERE "product_attributevalue"."id" IN (1, 2)'+ )diff --git a/tests/api/test_product_sorting.py b/tests/api/test_product_sorting.pyindex a872a967a2..8b13b9f0d2 100644--- a/tests/api/test_product_sorting.py+++ b/tests/api/test_product_sorting.py@@ -1,9 +1,5 @@-from typing import Dict, List-import graphene-import pytest-from saleor.product.models import Productfrom tests.api.utils import get_graphql_contentGET_SORTED_PRODUCTS_COLLECTION_QUERY = """@@ -23,7 +19,8 @@ query CollectionProducts($id: ID!) {COLLECTION_RESORT_QUERY = """mutation ReorderCollectionProducts($collectionId: ID!, $moves: [MoveProductInput]!) {collectionReorderProducts(collectionId: $collectionId, moves: $moves) {- collection {+ collection {+ idproducts(first: 10) {edges {node {@@ -42,62 +39,51 @@ mutation ReorderCollectionProducts($collectionId: ID!, $moves: [MoveProductInput"""-def _assert_product_are_correctly_ordered(expected: List[Product], nodes: List[Dict]):- assert len(nodes) == len(expected), "Size differs"- expected_ids = [p.pk for p in expected]- nodes_ids = [int(graphene.Node.from_global_id(p["node"]["id"])[1]) for p in nodes]- assert nodes_ids == expected_ids+def test_sort_products_within_collection_invalid_collection_id(+ staff_api_client, collection, product, permission_manage_products+):+ collection_id = graphene.Node.to_global_id("Collection", -1)+ product_id = graphene.Node.to_global_id("Product", product.pk)+ moves = [{"productId": product_id, "sortOrder": 1}][email protected]("wanted_pos, expected_pos", ((-100, 0), (+100, 100)))-def test_sort_products_within_collection_with_out_of_bound_value(- staff_api_client,- collection,- product,- permission_manage_products,- wanted_pos,- expected_pos,-):- product.collections.add(collection)- moves = [- {- "productId": graphene.Node.to_global_id("Product", product.pk),- "sortOrder": wanted_pos,- }- ]- get_graphql_content(+ content = get_graphql_content(staff_api_client.post_graphql(COLLECTION_RESORT_QUERY,- {- "collectionId": graphene.Node.to_global_id("Collection", collection.pk),- "moves": moves,- },+ {"collectionId": collection_id, "moves": moves},permissions=[permission_manage_products],)- )+ )["data"]["collectionReorderProducts"]- # Look if the order is as expected- assert product.collectionproduct.first().sort_order == expected_pos+ assert content["errors"] == [+ {+ "field": "collectionId",+ "message": f"Couldn't resolve to a collection: {collection_id}",+ }+ ]-def test_sort_products_within_collection_invalid_id(+def test_sort_products_within_collection_invalid_product_id(staff_api_client, collection, product, permission_manage_products):- product_id = graphene.Node.to_global_id("Collection", product.pk)+ # Remove the products from the collection to make the product invalid+ collection.products.clear()+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)++ # The move should be targeting an invalid product+ product_id = graphene.Node.to_global_id("Product", product.pk)moves = [{"productId": product_id, "sortOrder": 1}]+content = get_graphql_content(staff_api_client.post_graphql(COLLECTION_RESORT_QUERY,- {- "collectionId": graphene.Node.to_global_id("Collection", collection.pk),- "moves": moves,- },+ {"collectionId": collection_id, "moves": moves},permissions=[permission_manage_products],))["data"]["collectionReorderProducts"]assert content["errors"] == [- {"field": "moves", "message": f"Couldn't resolve to a node: {product_id}"}+ {"field": "moves", "message": f"Couldn't resolve to a product: {product_id}"}]@@ -108,43 +94,44 @@ def test_sort_products_within_collection(collection_with_products,permission_manage_products,):- expected_product_order = list(Product.objects.collection_sorted(user=staff_user))- assert Product.objects.count() == len(expected_product_order)+ staff_api_client.user.user_permissions.add(permission_manage_products)collection_id = graphene.Node.to_global_id("Collection", collection.pk)- products = get_graphql_content(- staff_api_client.post_graphql(- GET_SORTED_PRODUCTS_COLLECTION_QUERY, {"id": collection_id}- )- )["data"]["collection"]["products"]["edges"]- # Ensure the default the order is in place and well returned by default- _assert_product_are_correctly_ordered(expected_product_order, products)+ products = collection_with_products+ assert len(products) == 3- # Reorder the items- product_move_1 = expected_product_order.pop(2)- product_move_2 = expected_product_order.pop(0)+ # Sort the products per sort_order+ products = list(collection.products.collection_sorted(staff_user))+ assert len(products) == 3- expected_product_order.insert(2, product_move_2)- expected_product_order.insert(1, product_move_1)+ variables = {+ "collectionId": collection_id,+ "moves": [+ {+ "productId": graphene.Node.to_global_id("Product", products[0].pk),+ "sortOrder": +1,+ },+ {+ "productId": graphene.Node.to_global_id("Product", products[2].pk),+ "sortOrder": -1,+ },+ ],+ }- moves = [- {- "productId": graphene.Node.to_global_id("Product", product_move_1.pk),- "sortOrder": -2,- },- {- "productId": graphene.Node.to_global_id("Product", product_move_2.pk),- "sortOrder": +2,- },- ]- products = get_graphql_content(- staff_api_client.post_graphql(- COLLECTION_RESORT_QUERY,- {"collectionId": collection_id, "moves": moves},- permissions=[permission_manage_products],- )- )["data"]["collectionReorderProducts"]["collection"]["products"]["edges"]+ expected_order = [products[1].pk, products[2].pk, products[0].pk]++ content = get_graphql_content(+ staff_api_client.post_graphql(COLLECTION_RESORT_QUERY, variables)+ )["data"]["collectionReorderProducts"]+ assert not content["errors"]++ assert content["collection"]["id"] == collection_id++ gql_products = content["collection"]["products"]["edges"]+ assert len(gql_products) == len(expected_order)- # Look if the order is right- _assert_product_are_correctly_ordered(expected_product_order, products)+ for attr, expected_pk in zip(gql_products, expected_order):+ gql_type, gql_attr_id = graphene.Node.from_global_id(attr["node"]["id"])+ assert gql_type == "Product"+ assert int(gql_attr_id) == expected_pkdiff --git a/tests/conftest.py b/tests/conftest.pyindex d14c10cd88..fe80d9f059 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -40,7 +40,6 @@ from saleor.product.models import (AttributeValue,Category,Collection,- CollectionProduct,DigitalContent,DigitalContentUrl,Product,@@ -1056,10 +1055,7 @@ def collection(db):@pytest.fixturedef collection_with_products(db, collection, product_list_published):- for sort_order, product in enumerate(product_list_published):- CollectionProduct(- collection=collection, product=product, sort_order=sort_order- ).save()+ collection.products.set(list(product_list_published))return product_list_publisheddiff --git a/tests/test_core.py b/tests/test_core.pyindex 1c6ac4462f..76bb1cbc80 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -311,6 +311,15 @@ def test_build_absolute_uri(site_settings, settings):assert logo_url == logo_location+def test_delete_sort_order_with_null_value(menu_item):+ """Ensures there is no error when trying to delete a sortable item,+ which triggers a shifting of the sort orders--which can be null."""++ menu_item.sort_order = None+ menu_item.save(update_fields=["sort_order"])+ menu_item.delete()++def test_csrf_middleware_is_enabled():csrf_client = Client(enforce_csrf_checks=True)checkout_url = reverse("checkout:index")