Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add sorting capabilities to attributes
NyanKiyoshiadc98c0c87ed
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 280453e831..1ae1837bb2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ All notable, unreleased changes to this project will be documented in this file.- Attributes can now be flagged as required. - #4340 by @NyanKiyoshi.- Added a search position field for the storefront navigation to the attributes. - #4343 by @NyanKiyoshi- Deprecate the slug field for value input in attributes, and pass by ID instead. - #4348 by @NyanKiyoshi-- Add filtering capabilities to the top-level attributes' field. - #4386 by @NyanKiyoshi+- Add filtering and sorting capabilities to the top-level attributes' field. - #4387 by @NyanKiyoshi## [Unreleased]diff --git a/saleor/graphql/product/enums.py b/saleor/graphql/product/enums.pyindex bd95a72eab..ea890a6d64 100644--- a/saleor/graphql/product/enums.py+++ b/saleor/graphql/product/enums.py@@ -65,3 +65,41 @@ class ProductTypeConfigurable(graphene.Enum):class ProductTypeEnum(graphene.Enum):DIGITAL = "digital"SHIPPABLE = "shippable"+++class AttributeSortField(graphene.Enum):+ NAME = "name"+ SLUG = "slug"+ VALUE_REQUIRED = "value_required"+ IS_VARIANT_ONLY = "is_variant_only"+ VISIBLE_IN_STOREFRONT = "visible_in_storefront"+ FILTERABLE_IN_STOREFRONT = "filterable_in_storefront"+ FILTERABLE_IN_DASHBOARD = "filterable_in_dashboard"++ DASHBOARD_VARIANT_POSITION = "dashboard_variant_position"+ DASHBOARD_PRODUCT_POSITION = "dashboard_product_position"+ STOREFRONT_SEARCH_POSITION = "storefront_search_position"++ @property+ def description(self):+ if self == AttributeSortField.NAME:+ return "Sort attributes by name."+ if self == AttributeSortField.SLUG:+ return "Sort attributes by slug."+ if self == AttributeSortField.VALUE_REQUIRED:+ return "Sort attributes by the value required flag."+ if self == AttributeSortField.IS_VARIANT_ONLY:+ return "Sort attributes by the variant only flag."+ if self == AttributeSortField.VISIBLE_IN_STOREFRONT:+ return "Sort attributes by visibility in the storefront."+ if self == AttributeSortField.FILTERABLE_IN_STOREFRONT:+ return "Sort attributes by the filterable in storefront flag."+ if self == AttributeSortField.FILTERABLE_IN_DASHBOARD:+ return "Sort attributes by the filterable in dashboard flag."+ if self == AttributeSortField.DASHBOARD_VARIANT_POSITION:+ return "Sort variant attributes by their position in dashboard."+ if self == AttributeSortField.DASHBOARD_PRODUCT_POSITION:+ return "Sort product attributes by their position in dashboard."+ if self == AttributeSortField.STOREFRONT_SEARCH_POSITION:+ return "Sort attributes by their position in storefront."+ raise ValueError("Unsupported enum value: %s" % self.value)diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex fc4b7d9351..b956fc03b0 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -74,11 +74,9 @@ def filter_products_by_collections(qs, collections):return qs.filter(collections__in=collections)-def sort_qs(qs, sort_by_product_order):- if sort_by_product_order:- qs = qs.order_by(- sort_by_product_order["direction"] + sort_by_product_order["field"]- )+def sort_qs(qs, sort_by):+ if sort_by:+ qs = qs.order_by(sort_by["direction"] + sort_by["field"])return qsdiff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex fec1b83e3f..75673624ba 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -6,6 +6,7 @@ from ...order import OrderStatusfrom ...product import modelsfrom ...search.backends import pickerfrom ..utils import filter_by_period, filter_by_query_param, get_database_id, get_nodes+from .enums import AttributeSortField, OrderDirectionfrom .filters import (filter_products_by_attributes,filter_products_by_categories,@@ -29,7 +30,9 @@ def _filter_attributes_by_product_types(attribute_qs, product_qs):)-def resolve_attributes(info, category_id=None, collection_id=None, query=None):+def resolve_attributes(+ info, category_id=None, collection_id=None, query=None, sort_by=None, **_kwargs+):qs = models.Attribute.objects.get_visible_to_user(info.context.user)qs = filter_by_query_param(qs, query, ATTRIBUTES_SEARCH_FIELDS)@@ -54,7 +57,17 @@ def resolve_attributes(info, category_id=None, collection_id=None, query=None):else:qs = qs.none()- qs = qs.order_by("name")+ if sort_by:+ is_asc = sort_by["direction"] == OrderDirection.ASC.value+ if sort_by["field"] == AttributeSortField.DASHBOARD_VARIANT_POSITION.value:+ qs = qs.variant_attributes_sorted_for_dashboard(is_asc)+ elif sort_by["field"] == AttributeSortField.DASHBOARD_PRODUCT_POSITION.value:+ qs = qs.product_attributes_sorted_for_dashboard(is_asc)+ else:+ qs = sort_qs(qs, sort_by)+ else:+ qs = qs.order_by("name")+qs = qs.distinct()return gql_optimizer.query(qs, info)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 6c10cb3a7c..55b06a66c6 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -114,6 +114,7 @@ from .types import (ProductType,ProductVariant,)+from .types.attributes import AttributeSortingInputclass ProductFilterInput(FilterInputObjectType):@@ -161,6 +162,9 @@ class ProductQueries(graphene.ObjectType):belonging to the given collection.""",),filter=AttributeFilterInput(),+ sort_by=graphene.Argument(+ AttributeSortingInput, description="Sort attributes."+ ),)attribute = graphene.Field(Attribute,@@ -247,10 +251,8 @@ class ProductQueries(graphene.ObjectType):description="List of top selling products.",)- def resolve_attributes(- self, info, in_category=None, in_collection=None, query=None, **_kwargs- ):- return resolve_attributes(info, in_category, in_collection, query)+ def resolve_attributes(self, info, **kwargs):+ return resolve_attributes(info, **kwargs)def resolve_attribute(self, info, id):return graphene.Node.get_node_from_global_id(info, id, Attribute)diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/product/types/attributes.pyindex fccbd5e668..27e15f0904 100644--- a/saleor/graphql/product/types/attributes.py+++ b/saleor/graphql/product/types/attributes.py@@ -13,7 +13,12 @@ from ...translations.enums import LanguageCodeEnumfrom ...translations.resolvers import resolve_translationfrom ...translations.types import AttributeTranslation, AttributeValueTranslationfrom ..descriptions import AttributeDescriptions, AttributeValueDescriptions-from ..enums import AttributeInputTypeEnum, AttributeValueType+from ..enums import (+ AttributeInputTypeEnum,+ AttributeSortField,+ AttributeValueType,+ OrderDirection,+)COLOR_PATTERN = r"^(#[0-9a-fA-F]{3}|#(?:[0-9a-fA-F]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))$" # noqacolor_pattern = re.compile(COLOR_PATTERN)@@ -29,6 +34,19 @@ def resolve_attribute_value_type(attribute_value):return AttributeValueType.STRING+class AttributeSortingInput(graphene.InputObjectType):+ field = graphene.Argument(+ AttributeSortField,+ required=True,+ description="Sort attributes by the selected field.",+ )+ direction = graphene.Argument(+ OrderDirection,+ required=True,+ description="Specifies the direction in which to sort the attributes",+ )++class AttributeValue(CountableDjangoObjectType):name = graphene.String(description=AttributeValueDescriptions.NAME)slug = graphene.String(description=AttributeValueDescriptions.SLUG)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex f7da74b78b..b7742e76e5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -239,6 +239,24 @@ enum AttributeInputTypeEnum {scalar AttributeScalar+enum AttributeSortField {+ NAME+ SLUG+ VALUE_REQUIRED+ IS_VARIANT_ONLY+ VISIBLE_IN_STOREFRONT+ FILTERABLE_IN_STOREFRONT+ FILTERABLE_IN_DASHBOARD+ DASHBOARD_VARIANT_POSITION+ DASHBOARD_PRODUCT_POSITION+ STOREFRONT_SEARCH_POSITION+}++input AttributeSortingInput {+ field: AttributeSortField!+ direction: OrderDirection!+}+type AttributeTranslate {errors: [Error!]attribute: Attribute@@ -2833,7 +2851,7 @@ type Query {shippingZones(before: String, after: String, first: Int, last: Int): ShippingZoneCountableConnectiondigitalContent(id: ID!): DigitalContentdigitalContents(query: String, level: Int, before: String, after: String, first: Int, last: Int): DigitalContentCountableConnection- attributes(query: String, inCategory: ID, inCollection: ID, filter: AttributeFilterInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection+ attributes(query: String, inCategory: ID, inCollection: ID, filter: AttributeFilterInput, sortBy: AttributeSortingInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnectionattribute(id: ID!): Attributecategories(query: String, level: Int, before: String, after: String, first: Int, last: Int): CategoryCountableConnectioncategory(id: ID!): Categorydiff --git a/saleor/product/models.py b/saleor/product/models.pyindex 1427752159..b4e2f4f27a 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -502,11 +502,15 @@ 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))+ def product_attributes_sorted_for_dashboard(self, asc=True):+ field = F("attributeproduct__sort_order")+ sort_meth = getattr(field, "asc" if asc else "desc")+ return self.order_by(sort_meth(nulls_last=True))++ def variant_attributes_sorted_for_dashboard(self, asc=True):+ field = F("attributevariant__sort_order")+ sort_meth = getattr(field, "asc" if asc else "desc")+ return self.order_by(sort_meth(nulls_last=True))class Attribute(ModelWithMetadata):diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex 2fe741ea99..eb663ee4e1 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -1,3 +1,5 @@+from typing import Union+import grapheneimport pytestfrom django.db.models import Q@@ -9,7 +11,14 @@ from saleor.graphql.product.types.attributes import resolve_attribute_value_typefrom saleor.graphql.product.types.products import resolve_attribute_listfrom saleor.graphql.product.utils import attributes_to_jsonfrom saleor.product import AttributeInputType-from saleor.product.models import Attribute, AttributeValue, Category, ProductType+from saleor.product.models import (+ Attribute,+ AttributeProduct,+ AttributeValue,+ AttributeVariant,+ Category,+ ProductType,+)from tests.api.utils import get_graphql_content@@ -1450,3 +1459,85 @@ def test_filter_attributes_if_filterable_in_dashboard(assert len(attributes) == 1assert attributes[0]["node"]["slug"] == "size"+++ATTRIBUTES_SORT_QUERY = """+ query($sortBy: AttributeSortingInput) {+ attributes(first: 10, sortBy: $sortBy) {+ edges {+ node {+ slug+ }+ }+ }+ }+"""+++def test_sort_attributes_by_slug(api_client):+ Attribute.objects.bulk_create(+ [+ Attribute(name="MyAttribute", slug="b"),+ Attribute(name="MyAttribute", slug="a"),+ ]+ )++ variables = {"sortBy": {"field": "SLUG", "direction": "ASC"}}++ attributes = get_graphql_content(+ api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables)+ )["data"]["attributes"]["edges"]++ assert len(attributes) == 2+ assert attributes[0]["node"]["slug"] == "a"+ assert attributes[1]["node"]["slug"] == "b"+++ "sort_field, m2m_model",+ (+ ("DASHBOARD_VARIANT_POSITION", AttributeVariant),+ ("DASHBOARD_PRODUCT_POSITION", AttributeProduct),+ ),+)+def test_sort_attributes_by_position_in_product_type(+ api_client,+ color_attribute,+ size_attribute,+ sort_field: str,+ m2m_model: Union[AttributeVariant, AttributeProduct],+):+ """Sorts attributes for dashboard custom ordering inside a given product type."""++ product_type = ProductType.objects.create(name="My Product Type")+ m2m_model.objects.create(+ product_type=product_type, attribute=color_attribute, sort_order=0+ )+ m2m_model.objects.create(+ product_type=product_type, attribute=size_attribute, sort_order=1+ )++ variables = {"sortBy": {"field": sort_field, "direction": "DESC"}}++ attributes = get_graphql_content(+ api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables)+ )["data"]["attributes"]["edges"]++ assert len(attributes) == 2+ assert attributes[0]["node"]["slug"] == "size"+ assert attributes[1]["node"]["slug"] == "color"+++def test_sort_attributes_by_default_sorting(api_client):+ """Don't provide any sorting, this should sort by name by default."""+ Attribute.objects.bulk_create(+ [Attribute(name="A", slug="b"), Attribute(name="B", slug="a")]+ )++ attributes = get_graphql_content(+ api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {})+ )["data"]["attributes"]["edges"]++ assert len(attributes) == 2+ assert attributes[0]["node"]["slug"] == "b"+ assert attributes[1]["node"]["slug"] == "a"