Skip to content

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

Add sort by to collections query

fowczarek976d9c853eea
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index cbce3b480f..7d20929a2c 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -12,4 +12,5 @@ from .common import (
from .filter_input import FilterInputObjectType
from .meta import MetadataObjectType, MetaInput, MetaPath
from .money import VAT, Money, MoneyRange, ReducedRate, TaxedMoney, TaxedMoneyRange
+from .sort_input import SortInputObjectType
from .upload import Upload
diff --git a/saleor/graphql/core/types/sort_input.py b/saleor/graphql/core/types/sort_input.py
new file mode 100644
index 0000000000..0abe06f847
--- /dev/null
+++ b/saleor/graphql/core/types/sort_input.py
@@ -0,0 +1,21 @@
+import graphene
+
+from ..enums import OrderDirection
+
+
+class SortInputObjectType(graphene.InputObjectType):
+ direction = graphene.Argument(
+ OrderDirection,
+ required=True,
+ description="Specifies the direction in which to sort products.",
+ )
+
+ @classmethod
+ def __init_subclass_with_meta__(
+ cls, container=None, _meta=None, sort_enum=None, type_name=None, **options
+ ):
+ super().__init_subclass_with_meta__(container, _meta, **options)
+ field = graphene.Argument(
+ sort_enum, description=f"Sort {type_name} by the selected field."
+ )
+ cls._meta.fields.update({"field": field})
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 60470d3ef0..078ede7393 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -9,7 +9,13 @@ from ...order import OrderStatus
from ...product import models
from ...search.backends import picker
from ..core.enums import OrderDirection
-from ..utils import filter_by_period, filter_by_query_param, get_database_id, get_nodes
+from ..utils import (
+ filter_by_period,
+ filter_by_query_param,
+ get_database_id,
+ get_nodes,
+ sort_queryset,
+)
from .enums import AttributeSortField
from .filters import (
filter_attributes_by_product_types,
@@ -75,11 +81,11 @@ def resolve_categories(info, query, level=None):
return gql_optimizer.query(qs, info)
-def resolve_collections(info, query):
+def resolve_collections(info, query, sort_by=None, **_kwargs):
user = info.context.user
qs = models.Collection.objects.visible_to_user(user)
qs = filter_by_query_param(qs, query, COLLECTION_SEARCH_FIELDS)
- qs = qs.order_by("name")
+ qs = sort_queryset(qs, sort_by)
return gql_optimizer.query(qs, info)
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 5865d12ba7..3d939f12d0 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -111,6 +111,7 @@ from .resolvers import (
resolve_report_product_sales,
)
from .scalars import AttributeScalar
+from .sorters import CollectionSortInput
from .types import (
Attribute,
Category,
@@ -194,6 +195,7 @@ class ProductQueries(graphene.ObjectType):
collections = FilterInputConnectionField(
Collection,
filter=CollectionFilterInput(description="Filtering options for collections."),
+ sort_by=CollectionSortInput(description="Sort collections."),
query=graphene.String(description=DESCRIPTIONS["collection"]),
description="List of the shop's collections.",
)
@@ -288,7 +290,7 @@ class ProductQueries(graphene.ObjectType):
return graphene.Node.get_node_from_global_id(info, id, Collection)
def resolve_collections(self, info, query=None, **_kwargs):
- return resolve_collections(info, query)
+ return resolve_collections(info, query, **_kwargs)
@permission_required("product.manage_products")
def resolve_digital_content(self, info, id):
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
new file mode 100644
index 0000000000..8d42905e6b
--- /dev/null
+++ b/saleor/graphql/product/sorters.py
@@ -0,0 +1,28 @@
+import graphene
+
+from ..core.types import SortInputObjectType
+
+
+class CollectionSortEnum(graphene.Enum):
+ NAME = "name"
+ AVAILABILITY = "is_published"
+ # TODO: Add sorting by product count
+ # PRODUCT_COUNT = "collectionproduct"
+
+ @property
+ def description(self):
+ if self in [
+ CollectionSortEnum.NAME,
+ CollectionSortEnum.AVAILABILITY,
+ # CollectionSortEnum.PRODUCT_COUNT,
+ ]:
+ sort_name = self.name.lower().replace("_", " ")
+ return f"Sort collections by {sort_name}."
+ # pylint: disable=no-member
+ raise ValueError("Unsupported enum value: %s" % self.value)
+
+
+class CollectionSortInput(SortInputObjectType):
+ class Meta:
+ sort_enum = CollectionSortEnum
+ type_name = "collection"
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 97aac9c0a1..a3a491a3b3 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -950,6 +950,16 @@ type CollectionReorderProducts {
productErrors: [ProductError!]
}
+enum CollectionSortEnum {
+ NAME
+ AVAILABILITY
+}
+
+input CollectionSortInput {
+ direction: OrderDirection!
+ field: CollectionSortEnum
+}
+
type CollectionTranslatableContent implements Node {
seoTitle: String
seoDescription: String
@@ -3409,7 +3419,7 @@ type Query {
categories(query: String, filter: CategoryFilterInput, level: Int, before: String, after: String, first: Int, last: Int): CategoryCountableConnection
category(id: ID!): Category
collection(id: ID!): Collection
- collections(filter: CollectionFilterInput, query: String, before: String, after: String, first: Int, last: Int): CollectionCountableConnection
+ collections(filter: CollectionFilterInput, sortBy: CollectionSortInput, query: String, before: String, after: String, first: Int, last: Int): CollectionCountableConnection
product(id: ID!): Product
products(filter: ProductFilterInput, attributes: [AttributeScalar], categories: [ID], collections: [ID], sortBy: ProductOrder, stockAvailability: StockAvailability, query: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection
productType(id: ID!): ProductType
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index 43b0bd4d7f..9e4c8aa54c 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -1,7 +1,7 @@
from typing import Union
import graphene
-from django.db.models import Q
+from django.db.models import Q, QuerySet
from django.utils import timezone
from graphene_django.registry import get_global_registry
from graphql.error import GraphQLError
@@ -123,6 +123,25 @@ def filter_by_query_param(queryset, query, search_fields):
return queryset
+def sort_queryset(queryset: QuerySet, sort_by: dict):
+ """Sort queryset according to given parameters.
+
+ Keyword Arguments:
+ queryset - queryset to be filtered
+ sort_by - dictionary with sorting field and direction
+
+ """
+ if sort_by is None or not sort_by.field:
+ return queryset
+
+ direction = sort_by.direction
+ sorting_field = sort_by.field
+
+ queryset = queryset.order_by(f"{direction}{sorting_field}")
+
+ return queryset
+
+
def reporting_period_to_date(period):
now = timezone.now()
if period == ReportingPeriod.TODAY:
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 9ded6c1ad9..452ded1514 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -2641,6 +2641,53 @@ def test_collections_query_with_filter(
assert len(collections) == count
+QUERY_COLLECTIONS_WITH_SEARCH = """
+ query ($sort_by: CollectionSortInput!) {
+ collections(first:5, sortBy: $sort_by) {
+ edges{
+ node{
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+ "collection_sort, result_order",
+ [
+ ({"field": "NAME", "direction": "ASC"}, ["Coll1", "Coll2", "Coll3"]),
+ ({"field": "NAME", "direction": "DESC"}, ["Coll3", "Coll2", "Coll1"]),
+ ({"field": "AVAILABILITY", "direction": "ASC"}, ["Coll2", "Coll1", "Coll3"]),
+ ({"field": "AVAILABILITY", "direction": "DESC"}, ["Coll1", "Coll3", "Coll2"]),
+ # ({"field": "PRODUCT_COUNT", "direction": "ASC"}),
+ # ({"field": "PRODUCT_COUNT", "direction": "DESC"}),
+ ],
+)
+def test_collections_query_with_search(
+ collection_sort, result_order, staff_api_client, permission_manage_products
+):
+ Collection.objects.bulk_create(
+ [
+ Collection(name="Coll1", slug="collection-published1", is_published=True),
+ Collection(
+ name="Coll2", slug="collection-unpublished2", is_published=False
+ ),
+ Collection(name="Coll3", slug="collection-published", is_published=True),
+ ]
+ )
+
+ variables = {"sort_by": collection_sort}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(QUERY_COLLECTIONS_WITH_SEARCH, variables)
+ content = get_graphql_content(response)
+ collections = content["data"]["collections"]["edges"]
+
+ for order, colllection_name in enumerate(result_order):
+ assert collections[order]["node"]["name"] == colllection_name
+
+
@pytest.mark.parametrize(
"category_filter, count",
[