Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add sorting of attributes per product type
NyanKiyoshif0eddc53f7e7
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 2ebe7d8abf..6646262190 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -1,11 +1,12 @@from typing import Listimport graphene-from django.core.exceptions import ValidationError+from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db.models import Qfrom django.template.defaultfilters import slugifyfrom ....product import AttributeInputType, models+from ...core.interfaces import MoveOperationfrom ...core.mutations import (BaseMutation,ClearMetaBaseMutation,@@ -13,7 +14,7 @@ from ...core.mutations import (ModelMutation,UpdateMetaBaseMutation,)-from ...core.utils import from_global_id_strict_type+from ...core.utils import from_global_id_strict_type, perform_reorderingfrom ...product.types import ProductTypefrom ..descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom ..enums import AttributeInputTypeEnum, AttributeTypeEnum@@ -88,6 +89,16 @@ class AttributeAssignInput(graphene.InputObjectType):)+class AttributeReorderInput(graphene.InputObjectType):+ id = graphene.ID(required=True, description="The ID of the attribute 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."+ )+ )++class AttributeMixin:@classmethoddef check_values_are_unique(cls, values_input, attribute):@@ -558,3 +569,61 @@ class AttributeValueDelete(ModelDeleteMutation):response = super().success_response(instance)response.attribute = instance.attributereturn response+++class ProductTypeReorderAttributes(BaseMutation):+ product_type = graphene.Field(+ ProductType, description="Product type from which attributes are reordered."+ )++ class Meta:+ description = "Reorder the attributes of a product type"+ permissions = ("product.manage_products",)++ class Arguments:+ product_type_id = graphene.Argument(+ graphene.ID, required=True, description="ID of a product type."+ )+ type = AttributeTypeEnum(+ required=True, description="The attribute type to reorder."+ )+ moves = graphene.List(+ AttributeReorderInput,+ required=True,+ description="The list of attribute reordering operations.",+ )++ @classmethod+ def perform_mutation(cls, _root, info, product_type_id, type, moves):+ product_type_id = from_global_id_strict_type(+ info, product_type_id, only_type=ProductType, field="product_type_id"+ )++ if type == AttributeTypeEnum.PRODUCT:+ m2m_field = "attributeproduct"+ else:+ m2m_field = "attributevariant"++ product_type = models.ProductType.objects.prefetch_related(m2m_field).get(+ pk=product_type_id+ )++ attributes_m2m = getattr(product_type, m2m_field)+ operations = []++ for move_info in moves:+ attribute_id = from_global_id_strict_type(+ info, move_info.id, only_type=Attribute, field="moves"+ )++ try:+ node = attributes_m2m.get(attribute_id=attribute_id)+ except ObjectDoesNotExist:+ raise ValidationError(+ {"moves": "Couldn't resolve to an attribute: %s" % move_info.id}+ )++ operations.append(MoveOperation(node=node, sort_order=move_info.sort_order))++ perform_reordering(operations)+ return ProductTypeReorderAttributes(product_type=product_type)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 7a5c6b56d0..404aa49d05 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -39,6 +39,7 @@ from .mutations.attributes import (AttributeValueCreate,AttributeValueDelete,AttributeValueUpdate,+ ProductTypeReorderAttributes,)from .mutations.digital_contents import (DigitalContentCreate,@@ -355,6 +356,8 @@ class ProductMutations(graphene.ObjectType):product_type_delete = ProductTypeDelete.Field()product_type_bulk_delete = ProductTypeBulkDelete.Field()product_type_update = ProductTypeUpdate.Field()+ product_type_reorder_attributes = ProductTypeReorderAttributes.Field()+product_type_update_metadata = ProductTypeUpdateMeta.Field()product_type_clear_metadata = ProductTypeClearMeta.Field()product_type_update_private_metadata = ProductTypeUpdatePrivateMeta.Field()diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex f2bd35efcf..e34796ec48 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -677,14 +677,18 @@ class ProductType(CountableDjangoObjectType, MetadataObjectType):return tax.get("code")@staticmethod- @gql_optimizer.resolver_hints(prefetch_related="product_attributes")+ @gql_optimizer.resolver_hints(+ prefetch_related="product_attributes__attributeproduct"+ )def resolve_product_attributes(root: models.ProductType, *_args, **_kwargs):- return root.product_attributes.all()+ return root.product_attributes.product_attributes_sorted_for_dashboard().all()@staticmethod- @gql_optimizer.resolver_hints(prefetch_related="variant_attributes")+ @gql_optimizer.resolver_hints(+ prefetch_related="variant_attributes__attributevariant"+ )def resolve_variant_attributes(root: models.ProductType, *_args, **_kwargs):- return root.variant_attributes.all()+ return root.variant_attributes.variant_attributes_sorted_for_dashboard().all()@staticmethoddef resolve_products(root: models.ProductType, info, **_kwargs):diff --git a/saleor/product/migrations/0098_auto_20190626_0815.py b/saleor/product/migrations/0098_auto_20190626_0815.pynew file mode 100644index 0000000000..3dd0c27276--- /dev/null+++ b/saleor/product/migrations/0098_auto_20190626_0815.py@@ -0,0 +1,21 @@+# Generated by Django 2.2.2 on 2019-06-26 13:15++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [("product", "0097_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/models.py b/saleor/product/models.pyindex 9a07d8e154..1427752159 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -453,7 +453,7 @@ class DigitalContentUrl(models.Model):return build_absolute_uri(url)-class AttributeProduct(models.Model):+class AttributeProduct(SortableModel):attribute = models.ForeignKey("Attribute", related_name="attributeproduct", on_delete=models.CASCADE)@@ -461,8 +461,11 @@ class AttributeProduct(models.Model):ProductType, related_name="attributeproduct", on_delete=models.CASCADE)+ def get_ordering_queryset(self):+ return self.product_type.attributeproduct.all()+-class AttributeVariant(models.Model):+class AttributeVariant(SortableModel):attribute = models.ForeignKey("Attribute", related_name="attributevariant", on_delete=models.CASCADE)@@ -470,6 +473,9 @@ class AttributeVariant(models.Model):ProductType, related_name="attributevariant", on_delete=models.CASCADE)+ def get_ordering_queryset(self):+ return self.product_type.attributevariant.all()+class AttributeQuerySet(models.QuerySet):def get_unassigned_attributes(self, product_type_pk: int):@@ -496,6 +502,12 @@ class AttributeQuerySet(models.QuerySet):return self.all()return self.get_public_attributes()+ def product_attributes_sorted_for_dashboard(self):+ return self.order_by(F("attributeproduct__sort_order").asc(nulls_last=True))++ def variant_attributes_sorted_for_dashboard(self):+ return self.order_by(F("attributevariant__sort_order").asc(nulls_last=True))+class Attribute(ModelWithMetadata):slug = models.SlugField(max_length=50, unique=True)diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex e3ddc82567..23f9c3dd23 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -1303,3 +1303,109 @@ def test_retrieving_the_restricted_attributes_restricted(assert len(found_attributes) == 1assert found_attributes[0]["node"][attribute] == expected_value+++ATTRIBUTES_RESORT_QUERY = """+ mutation ProductTypeReorderAttributes(+ $productTypeId: ID!+ $moves: [AttributeReorderInput]!+ $type: AttributeTypeEnum!+ ) {+ productTypeReorderAttributes(+ productTypeId: $productTypeId+ moves: $moves+ type: $type+ ) {+ productType {+ variantAttributes {+ id+ slug+ }+ productAttributes {+ id+ }+ }++ errors {+ field+ message+ }+ }+ }+"""+++def test_sort_attributes_within_product_type_invalid_id(+ staff_api_client, permission_manage_products, color_attribute+):+ """Try to reorder an attribute not associated to the given product type."""++ product_type = ProductType.objects.create(name="Dummy Type")+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)++ 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": "moves",+ "message": f"Couldn't resolve to an attribute: {attribute_id}",+ }+ ]+++ "attribute_type, relation_field, backref_field",+ (+ ("VARIANT", "variant_attributes", "attributevariant"),+ ("PRODUCT", "product_attributes", "attributeproduct"),+ ),+)+def test_sort_variant_attributes_within_product_type(+ staff_api_client,+ attribute_list,+ permission_manage_products,+ attribute_type,+ relation_field,+ backref_field,+):+ 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)++ variables = {+ "type": attribute_type,+ "productTypeId": product_type_id,+ "moves": [+ {"id": graphene.Node.to_global_id("Attribute", attr.id), "sortOrder": 0}+ for attr in attribute_list+ ],+ }++ 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++ _, gql_attr_id = graphene.Node.from_global_id(gql_attr["id"])+ assert gql_attr_id == str(db_attr.pk)++ current_sort_pos += 1diff --git a/tests/conftest.py b/tests/conftest.pyindex cd3b17baa3..d14c10cd88 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,6 +1,7 @@import uuidfrom decimal import Decimalfrom io import BytesIO+from typing import Listfrom unittest.mock import MagicMock, Mockimport pytest@@ -346,7 +347,7 @@ def size_attribute(db): # pylint: disable=W0613@pytest.fixture-def attribute_list():+def attribute_list() -> List[Attribute]:return list(Attribute.objects.bulk_create([