Skip to content

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

feat: deprecate product rating API and fix attribute sorting bug (#19783)

Lukasz Ostrowskie89fc5597ec7
diff --git a/saleor/graphql/core/descriptions.py b/saleor/graphql/core/descriptions.py
index a161aabe7b..741fdeabd1 100644
--- a/saleor/graphql/core/descriptions.py
+++ b/saleor/graphql/core/descriptions.py
@@ -28,6 +28,15 @@ DEPRECATED_LEGACY_PAYMENTS = (
DEPRECATED_LEGACY_PAYMENTS_TYPE_DESCRIPTION = "\n\n" + DEPRECATED_LEGACY_PAYMENTS
+DEPRECATED_PRODUCT_RATING = (
+ "Product rating is deprecated and will be removed. Use a numeric attribute instead."
+)
+
+DEPRECATED_PRODUCT_RATING_INPUT = (
+ f"{DEPRECATED_IN_3X_INPUT} {DEPRECATED_PRODUCT_RATING}"
+)
+
+
PREVIEW_FEATURE = (
"\n\nNote: this API is currently in Feature Preview and can be subject to "
"changes at later point."
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index 27e6d948e9..50efb39af7 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -24,7 +24,7 @@ from ....webhook.utils import get_webhooks_for_event
from ...attribute.types import AttributeValueInput
from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
from ...core.context import ChannelContext
-from ...core.descriptions import RICH_CONTENT
+from ...core.descriptions import DEPRECATED_PRODUCT_RATING_INPUT, RICH_CONTENT
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.enums import ErrorPolicyEnum
from ...core.fields import JSONString
@@ -134,7 +134,11 @@ class ProductBulkCreateInput(ProductCreateInput):
)
seo = SeoInput(description="Search engine optimization fields.")
weight = WeightScalar(description="Weight of the Product.", required=False)
- rating = graphene.Float(description="Defines the product rating value.")
+ rating = graphene.Float(
+ description=(
+ f"Defines the product rating value.{DEPRECATED_PRODUCT_RATING_INPUT}"
+ )
+ )
metadata = NonNullList(
MetadataInput,
description="Fields required to update the product metadata. "
diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.py
index ee8e3fbdc5..5175a40bf2 100644
--- a/saleor/graphql/product/mutations/product/product_create.py
+++ b/saleor/graphql/product/mutations/product/product_create.py
@@ -12,6 +12,7 @@ from ....core import ResolveInfo
from ....core.context import ChannelContext
from ....core.descriptions import (
DEPRECATED_IN_3X_INPUT,
+ DEPRECATED_PRODUCT_RATING_INPUT,
RICH_CONTENT,
)
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
@@ -63,7 +64,11 @@ class ProductInput(BaseInputObjectType):
)
seo = SeoInput(description="Search engine optimization fields.")
weight = WeightScalar(description="Weight of the Product.", required=False)
- rating = graphene.Float(description="Defines the product rating value.")
+ rating = graphene.Float(
+ description=(
+ f"Defines the product rating value.{DEPRECATED_PRODUCT_RATING_INPUT}"
+ )
+ )
metadata = NonNullList(
MetadataInput,
description="Fields required to update the product metadata. "
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index a0242b1656..54cfde281a 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -23,7 +23,11 @@ from ...product.models import (
Product,
ProductChannelListing,
)
-from ..core.descriptions import ADDED_IN_323, CHANNEL_REQUIRED
+from ..core.descriptions import (
+ ADDED_IN_323,
+ CHANNEL_REQUIRED,
+ DEPRECATED_PRODUCT_RATING,
+)
from ..core.doc_category import DOC_CATEGORY_PRODUCTS
from ..core.types import BaseEnum, ChannelSortInputObjectType, SortInputObjectType
@@ -211,6 +215,7 @@ class ProductOrderField(BaseEnum):
ProductOrderField.DATE.name: "Use `LAST_MODIFIED` instead.", # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501
ProductOrderField.PUBLICATION_DATE.name: "Use `PUBLISHED_AT` instead.", # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501
ProductOrderField.LAST_MODIFIED.name: "Use `LAST_MODIFIED_AT` instead.", # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501
+ ProductOrderField.RATING.name: DEPRECATED_PRODUCT_RATING, # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501
}
if self.name in deprecations:
return deprecations[self.name]
diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.py
index e7ade53acb..9988301632 100644
--- a/saleor/graphql/product/tests/queries/test_products_query.py
+++ b/saleor/graphql/product/tests/queries/test_products_query.py
@@ -1488,5 +1488,6 @@ def test_search_product_sort_by_attribute_returns_correct_cursor(
# Ref saleor.product.managers.ProductsQueryset.sort_by_attribute
# First field stores the flag to determine if product has assigned attribute values
- # Second is the list of attribute values as string
- assert ["0", attr_value.name, product.name] == cursor_data
+ # Second is the numeric value, set only for attributes of numeric input type
+ # Third is the list of attribute values as string
+ assert ["0", None, attr_value.name, product.name] == cursor_data
diff --git a/saleor/graphql/product/tests/test_product_sorting_attributes.py b/saleor/graphql/product/tests/test_product_sorting_attributes.py
index a808d08c3f..b8a5bbdcc2 100644
--- a/saleor/graphql/product/tests/test_product_sorting_attributes.py
+++ b/saleor/graphql/product/tests/test_product_sorting_attributes.py
@@ -19,12 +19,19 @@ query products(
$attributeId: ID
$direction: OrderDirection!
$channel: String
+ $first: Int = 100
+ $after: String
) {
products(
- first: 100,
+ first: $first,
+ after: $after,
channel: $channel,
sortBy: { field: $field, attributeId: $attributeId, direction: $direction }
) {
+ pageInfo {
+ hasNextPage
+ endCursor
+ }
edges {
node {
name
@@ -42,6 +49,41 @@ query products(
}
"""
+# Separate query for the paging walk: no `first` default, so a backward walk can
+# send `last`/`before` without `first` sneaking in and being rejected.
+QUERY_PAGINATE_PRODUCTS_BY_ATTRIBUTE = """
+query products(
+ $attributeId: ID
+ $direction: OrderDirection!
+ $channel: String
+ $first: Int
+ $after: String
+ $last: Int
+ $before: String
+) {
+ products(
+ first: $first,
+ after: $after,
+ last: $last,
+ before: $before,
+ channel: $channel,
+ sortBy: { attributeId: $attributeId, direction: $direction }
+ ) {
+ pageInfo {
+ hasNextPage
+ hasPreviousPage
+ startCursor
+ endCursor
+ }
+ edges {
+ node {
+ name
+ }
+ }
+ }
+}
+"""
+
COLORS = (["Blue", "Red"], ["Blue", "Gray"], ["Pink"], ["Pink"], ["Green"])
TRADEMARKS = ("A", "A", "ab", "b", "y")
DUMMIES = ("Oopsie",)
@@ -692,3 +734,267 @@ def test_sort_product_by_attribute_using_attribute_having_no_products(
assert len(products) == product_models.Product.objects.count()
assert products[0]["node"]["name"] == expected_first_product.name
+
+
+# Values whose numeric order differs from their lexicographic order. Fractional, so
+# that cursors have to round-trip a non-integral float.
+NUMERIC_VALUES = (2.5, 9.5, 10.25, 100.5)
+
+
+def _publish_product(name, product_type, category, channel):
+ product = product_models.Product.objects.create(
+ name=name,
+ slug=name.lower().replace(" ", "-"),
+ product_type=product_type,
+ category=category,
+ )
+ product_models.ProductChannelListing.objects.create(
+ product=product,
+ channel=channel,
+ is_published=True,
+ visible_in_listings=True,
+ )
+ variant = product_models.ProductVariant.objects.create(
+ product=product, sku=product.slug
+ )
+ product_models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel.currency_code,
+ )
+ return product
+
+
+def _numeric_attribute_value(attribute, number):
+ return attribute_models.AttributeValue.objects.create(
+ attribute=attribute,
+ name=str(number),
+ slug=str(number),
+ numeric=number,
+ )
+
+
+def _sort_products_by_attribute(api_client, attribute, direction, channel):
+ variables = {
+ "attributeId": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "direction": direction,
+ "channel": channel.slug,
+ }
+ response = get_graphql_content(
+ api_client.post_graphql(QUERY_SORT_PRODUCTS_BY_ATTRIBUTE, variables)
+ )
+ return [edge["node"]["name"] for edge in response["data"]["products"]["edges"]]
+
+
+def numeric_product_type(numeric_attribute):
+ product_type = product_models.ProductType.objects.create(
+ name="Rated", slug="rated", has_variants=False
+ )
+ product_type.product_attributes.add(numeric_attribute)
+ return product_type
+
+
+def numeric_attribute_with_products(
+ numeric_attribute, numeric_product_type, category, channel_USD
+):
+ for number in NUMERIC_VALUES:
+ product = _publish_product(
+ f"Product {number}", numeric_product_type, category, channel_USD
+ )
+ associate_attribute_values_to_instance(
+ product,
+ {
+ numeric_attribute.pk: [
+ _numeric_attribute_value(numeric_attribute, number)
+ ]
+ },
+ )
+ return numeric_attribute
+
+
+# Dropdown values whose sorted order (by value name) is the reverse of the owning
+# product names, so a name-only sort would give a different result. One product
+# holds multiple values ("b", "c") — the representative case for the
+# concatenated-values sort, whose cursor carries `None` in the numeric slot.
+DROPDOWN_PRODUCTS = {
+ "Product D": ["a"],
+ "Product C": ["b", "c"],
+ "Product B": ["d"],
+ "Product A": ["e"],
+}
+
+
+def dropdown_attribute_with_products(category, channel_USD):
+ attribute = attribute_models.Attribute.objects.create(
+ name="Flavor",
+ slug="flavor",
+ input_type=AttributeInputType.MULTISELECT,
+ type=AttributeType.PRODUCT_TYPE,
+ )
+ product_type = product_models.ProductType.objects.create(
+ name="Flavored", slug="flavored", has_variants=False
+ )
+ product_type.product_attributes.add(attribute)
+ for name, value_names in DROPDOWN_PRODUCTS.items():
+ product = _publish_product(name, product_type, category, channel_USD)
+ values = [
+ attribute_models.AttributeValue.objects.create(
+ attribute=attribute, name=value, slug=value
+ )
+ for value in value_names
+ ]
+ associate_attribute_values_to_instance(product, {attribute.pk: values})
+ return attribute
+
+
+def _walk_pages(api_client, attribute, direction, channel, page_size, backward):
+ """Paginate through every page and return the collected names in order."""
+ variables = {
+ "attributeId": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "direction": direction,
+ "channel": channel.slug,
+ }
+ collected: list[str] = []
+ cursor = None
+ while True:
+ if backward:
+ page_variables = {
+ **variables,
+ "first": None,
+ "last": page_size,
+ "before": cursor,
+ }
+ else:
+ page_variables = {**variables, "first": page_size, "after": cursor}
+ response = get_graphql_content(
+ api_client.post_graphql(
+ QUERY_PAGINATE_PRODUCTS_BY_ATTRIBUTE, page_variables
+ )
+ )
+ products = response["data"]["products"]
+ page_names = [edge["node"]["name"] for edge in products["edges"]]
+ page_info = products["pageInfo"]
+ if backward:
+ collected = page_names + collected
+ if not page_info["hasPreviousPage"]:
+ break
+ cursor = page_info["startCursor"]
+ else:
+ collected += page_names
+ if not page_info["hasNextPage"]:
+ break
+ cursor = page_info["endCursor"]
+ return collected
+
+
[email protected]("descending", [False, True])
+def test_sort_product_by_numeric_attribute(
+ api_client, numeric_attribute_with_products, descending, channel_USD
+):
+ # given
+ attribute = numeric_attribute_with_products
+ expected_names = [
+ f"Product {number}" for number in sorted(NUMERIC_VALUES, reverse=descending)
+ ]
+
+ # when
+ names = _sort_products_by_attribute(
+ api_client, attribute, "DESC" if descending else "ASC", channel_USD
+ )
+
+ # then
+ assert names == expected_names
+
+
[email protected]("descending", [False, True])
+def test_sort_product_by_numeric_attribute_without_assigned_values(
+ api_client,
+ numeric_attribute,
+ numeric_product_type,
+ category,
+ channel_USD,
+ descending,
+):
+ """Rank products with a value first, then valueless, then unrelated types."""
+ # given
+ other_product_type = product_models.ProductType.objects.create(
+ name="Unrated", slug="unrated", has_variants=False
+ )
+
+ with_value = _publish_product(
+ "With value", numeric_product_type, category, channel_USD
+ )
+ associate_attribute_values_to_instance(
+ with_value,
+ {numeric_attribute.pk: [_numeric_attribute_value(numeric_attribute, 7)]},
+ )
+ _publish_product("Without value", numeric_product_type, category, channel_USD)
+ _publish_product("Other type", other_product_type, category, channel_USD)
+
+ expected_names = ["With value", "Without value", "Other type"]
+ if descending:
+ expected_names.reverse()
+
+ # when
+ names = _sort_products_by_attribute(
+ api_client, numeric_attribute, "DESC" if descending else "ASC", channel_USD
+ )
+
+ # then
+ assert names == expected_names
+
+
[email protected]("backward", [False, True])
[email protected]("descending", [False, True])
+ ("attribute_fixture", "ordered_names"),
+ [
+ (
+ "numeric_attribute_with_products",
+ [f"Product {number}" for number in sorted(NUMERIC_VALUES)],
+ ),
+ (
+ "dropdown_attribute_with_products",
+ ["Product D", "Product C", "Product B", "Product A"],
+ ),
+ ],
+)
+def test_sort_product_by_attribute_survives_cursor_round_trip(
+ api_client,
+ request,
+ channel_USD,
+ attribute_fixture,
+ ordered_names,
+ descending,
+ backward,
+):
+ """Sort value survives the cursor round-trip in both directions and walks.
+
+ For a numeric attribute the cursor round-trips a non-integral float; for a
+ dropdown attribute (one product holding multiple values) it round-trips a
+ `None` numeric slot. A flipped direction also moves PostgreSQL's `NULL`s to
+ the other end, and a backward walk (`last`/`before`) must yield the same
+ full order as the forward walk (`first`/`after`).
+ """
+ # given
+ attribute = request.getfixturevalue(attribute_fixture)
+ page_size = 2
+ expected_names = list(reversed(ordered_names)) if descending else ordered_names
+
+ # when
+ names = _walk_pages(
+ api_client,
+ attribute,
+ "DESC" if descending else "ASC",
+ channel_USD,
+ page_size,
+ backward=backward,
+ )
+
+ # then
+ assert names == expected_names
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 4d2d2decfc..393e9dfe74 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -68,6 +68,7 @@ from ...core.context import (
from ...core.descriptions import (
ADDED_IN_322,
DEPRECATED_IN_3X_INPUT,
+ DEPRECATED_PRODUCT_RATING,
RICH_CONTENT,
)
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
@@ -880,7 +881,10 @@ class Product(ChannelContextType[models.Product]):
default_variant = graphene.Field(
ProductVariant, description="Default variant of the product."
)
- rating = graphene.Float(description="Rating of the product.")
+ rating = graphene.Float(
+ description="Rating of the product.",
+ deprecation_reason=DEPRECATED_PRODUCT_RATING,
+ )
channel = graphene.String(
description=(
"Channel given to retrieve this product. Also used by federation "
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 53ca6fd7bb..e8d7a39922 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4078,7 +4078,7 @@ type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(ca
defaultVariant: ProductVariant
"""Rating of the product."""
- rating: Float
+ rating: Float @deprecated(reason: "Product rating is deprecated and will be removed. Use a numeric attribute instead.")
"""
Channel given to retrieve this product. Also used by federation gateway to resolve this object in a federated query.
@@ -4835,7 +4835,7 @@ enum ProductOrderField @doc(category: "Products") {
COLLECTION
"""Sort products by rating."""
- RATING
+ RATING @deprecated(reason: "Product rating is deprecated and will be removed. Use a numeric attribute instead.")
"""Sort products by creation date."""
CREATED_AT
@@ -24705,7 +24705,7 @@ input ProductCreateInput @doc(category: "Products") {
weight: WeightScalar
"""Defines the product rating value."""
- rating: Float
+ rating: Float @deprecated(reason: "Product rating is deprecated and will be removed. Use a numeric attribute instead.")
"""
Fields required to update the product metadata. Can be read by any API client authorized to read the object it's attached to.
@@ -24922,7 +24922,7 @@ input ProductBulkCreateInput @doc(category: "Products") {
weight: WeightScalar
"""Defines the product rating value."""
- rating: Float
+ rating: Float @deprecated(reason: "Product rating is deprecated and will be removed. Use a numeric attribute instead.")
"""
Fields required to update the product metadata. Can be read by any API client authorized to read the object it's attached to.
@@ -25184,7 +25184,7 @@ input ProductInput @doc(category: "Products") {
weight: WeightScalar
"""Defines the product rating value."""
- rating: Float
+ rating: Float @deprecated(reason: "Product rating is deprecated and will be removed. Use a numeric attribute instead.")
"""
Fields required to update the product metadata. Can be read by any API client authorized to read the object it's attached to.
diff --git a/saleor/product/managers.py b/saleor/product/managers.py
index dbdbd7aa33..c692a32ccc 100644
--- a/saleor/product/managers.py
+++ b/saleor/product/managers.py
@@ -11,6 +11,7 @@ from django.db.models import (
Exists,
ExpressionWrapper,
F,
+ Min,
OuterRef,
Q,
Subquery,
@@ -175,12 +176,23 @@ class ProductsQueryset(models.QuerySet):
concatenated_values_order=Value(
None, output_field=models.IntegerField()
),
+ numeric_value=Value(None, output_field=models.FloatField()),
concatenated_values=Value(None, output_field=models.CharField()),
)
qs = qs.annotate(
# Implicit `GROUP BY` required for the `StringAgg` aggregation
grouped_ids=Count("id"),
+ # Numeric attributes must sort by their value, not by its string
+ # representation, otherwise "10" would come before "9". A numeric
+ # attribute holds exactly one value per product, so the choice of
+ # aggregate is arbitrary (`Min` == `Max` here); it merely reuses the
+ # join `concatenated_values` already needs and stays `NULL` for every
+ # other input type, making it a no-op for them.
+ numeric_value=Min(
+ "attributevalues__value__numeric",
+ filter=Q(attributevalues__value__attribute_id=attribute_pk),
+ ),
# String aggregation of the attribute's values to efficiently sort them
concatenated_values=Case(
# If the product has no association data but has
@@ -232,6 +244,7 @@ class ProductsQueryset(models.QuerySet):
ordering = "-" if descending else ""
return qs.order_by(
f"{ordering}concatenated_values_order",
+ f"{ordering}numeric_value",
f"{ordering}concatenated_values",
f"{ordering}name",
)
diff --git a/saleor/product/models.py b/saleor/product/models.py
index c956fa5d3e..3df2f87bb8 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -263,7 +263,12 @@ class Product(SeoModel, ModelWithMetadata, ModelWithExternalReference):
@staticmethod
def sort_by_attribute_fields() -> list:
- return ["concatenated_values_order", "concatenated_values", "name"]
+ return [
+ "concatenated_values_order",
+ "numeric_value",
+ "concatenated_values",
+ "name",
+ ]
class ProductTranslation(SeoModelTranslationWithSlug):