Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix reordering collection products (#6488)
Damian Wysocki59a64935c2a9
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.pyindex 80f2144258..c94f7ece7a 100644--- a/saleor/graphql/product/sorters.py+++ b/saleor/graphql/product/sorters.py@@ -1,6 +1,7 @@import graphene-from django.db.models import Count, IntegerField, Min, OuterRef, QuerySet, Subquery-from django.db.models.functions import Coalesce+from django.db.models import Count, F, IntegerField, Min, OuterRef, QuerySet, Subquery+from django.db.models.expressions import Window+from django.db.models.functions import Coalesce, RowNumberfrom ...product.models import Category, Productfrom ..core.types import SortInputObjectType@@ -139,25 +140,30 @@ class ProductOrderField(graphene.Enum):TYPE = ["product_type__name", "name", "slug"]PUBLISHED = ["is_published", "name", "slug"]PUBLICATION_DATE = ["publication_date", "name", "slug"]+ COLLECTION = ["row_number"]RATING = ["rating", "name", "slug"]@propertydef description(self):# pylint: disable=no-memberdescriptions = {- ProductOrderField.NAME.name: "name",- ProductOrderField.PRICE.name: "price",- ProductOrderField.TYPE.name: "type",+ ProductOrderField.COLLECTION.name: (+ "collection. Note: "+ "This option is available only for the `Collection.products` query."+ ),+ ProductOrderField.NAME.name: "name.",+ ProductOrderField.PRICE.name: "price.",+ ProductOrderField.TYPE.name: "type.",ProductOrderField.MINIMAL_PRICE.name: (- "a minimal price of a product's variant"+ "a minimal price of a product's variant."),- ProductOrderField.DATE.name: "update date",- ProductOrderField.PUBLISHED.name: "publication status",- ProductOrderField.PUBLICATION_DATE.name: "publication date",- ProductOrderField.RATING.name: "rating",+ ProductOrderField.DATE.name: "update date.",+ ProductOrderField.PUBLISHED.name: "publication status.",+ ProductOrderField.PUBLICATION_DATE.name: "publication date.",+ ProductOrderField.RATING.name: "rating.",}if self.name in descriptions:- return f"Sort products by {descriptions[self.name]}."+ return f"Sort products by {descriptions[self.name]}"raise ValueError("Unsupported enum value: %s" % self.value)@staticmethod@@ -166,6 +172,18 @@ class ProductOrderField(graphene.Enum):min_variants_price_amount=Min("variants__price_amount"))+ @staticmethod+ def qs_with_collection(queryset: QuerySet) -> QuerySet:+ return queryset.annotate(+ row_number=Window(+ expression=RowNumber(),+ order_by=(+ F("collectionproduct__sort_order").asc(nulls_last=True),+ F("collectionproduct__id"),+ ),+ )+ )+class ProductOrder(SortInputObjectType):attribute_id = graphene.Argument(diff --git a/saleor/graphql/product/tests/test_product_sorting.py b/saleor/graphql/product/tests/test_product_sorting.pyindex 4b3df183a8..5b43202256 100644--- a/saleor/graphql/product/tests/test_product_sorting.py+++ b/saleor/graphql/product/tests/test_product_sorting.py@@ -13,7 +13,7 @@ mutation ReorderCollectionProducts($collectionId: ID!, $moves: [MoveProductInputcollectionReorderProducts(collectionId: $collectionId, moves: $moves) {collection {id- products(first: 10) {+ products(first: 10, sortBy:{field:COLLECTION, direction:ASC}) {edges {node {name@@ -91,28 +91,15 @@ def test_sort_products_within_collection(collection_id = graphene.Node.to_global_id("Collection", collection.pk)products = collection_with_products- assert len(products) == 3-- # Sort the products per sort_order- products = list(collection.products.collection_sorted(staff_user))- assert len(products) == 3+ product = graphene.Node.to_global_id("Product", products[0].pk)+ second_product = graphene.Node.to_global_id("Product", products[1].pk)+ third_product = graphene.Node.to_global_id("Product", products[2].pk)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": product, "sortOrder": -1}],}- 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"]@@ -120,13 +107,23 @@ def test_sort_products_within_collection(assert content["collection"]["id"] == collection_id- gql_products = content["collection"]["products"]["edges"]- assert len(gql_products) == len(expected_order)+ products = content["collection"]["products"]["edges"]+ assert products[0]["node"]["id"] == product+ assert products[1]["node"]["id"] == third_product+ assert products[2]["node"]["id"] == second_product++ variables = {+ "collectionId": collection_id,+ "moves": [{"productId": product, "sortOrder": 1}],+ }+ content = get_graphql_content(+ staff_api_client.post_graphql(COLLECTION_RESORT_QUERY, variables)+ )["data"]["collectionReorderProducts"]- 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_pk+ products = content["collection"]["products"]["edges"]+ assert products[0]["node"]["id"] == third_product+ assert products[1]["node"]["id"] == product+ assert products[2]["node"]["id"] == second_productGET_SORTED_PRODUCTS_QUERY = """diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex d13a378af4..3549e74031 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -762,7 +762,7 @@ class Collection(CountableDjangoObjectType):@staticmethoddef resolve_products(root: models.Collection, info, first=None, **kwargs):- return root.products.collection_sorted(info.context.user)+ return root.products.visible_to_user(info.context.user)@classmethoddef get_node(cls, info, id):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 00264dfca8..c1f3c77119 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3665,6 +3665,7 @@ enum ProductOrderField {TYPEPUBLISHEDPUBLICATION_DATE+ COLLECTIONRATING}diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 72f2a9f1d4..1ed8abf280 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -126,14 +126,6 @@ class ProductType(ModelWithMetadata):class ProductsQueryset(PublishedQuerySet):- def collection_sorted(self, user: "User"):- qs = self.visible_to_user(user)- qs = qs.order_by(- F("collectionproduct__sort_order").asc(nulls_last=True),- F("collectionproduct__id"),- )- return qs-def published_with_variants(self):published = self.published()return published.filter(variants__isnull=False).distinct()