Skip to content

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

New properties for Product type for improving client-side filters (#10537)

Maciej Korycinski7309f835ac2c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c138bb81a0..7626990007 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,9 @@ All notable, unreleased changes to this project will be documented in this file.
### GraphQL API
- Add `attribute` field to `AttributeValueTranslatableContent` type. #11028 by @zedzior
+- Add new properties in the `Product` type - #10537 by @kadewu
+ - Add new fields: `Product.attribute`, `Product.variant`
+ - Add `sortBy` argument to `Product.media`
### Other changes
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index 61d3964905..c5590833ac 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -301,3 +301,22 @@ class ProductTypeSortingInput(SortInputObjectType):
class Meta:
sort_enum = ProductTypeSortField
type_name = "product types"
+
+
+class MediaChoicesSortField(graphene.Enum):
+ ID = ["id"]
+
+ @property
+ def description(self):
+ descriptions = {
+ MediaChoicesSortField.ID.name: "Sort media by ID.",
+ }
+ if self.name in descriptions:
+ return descriptions[self.name]
+ raise ValueError(f"Unsupported enum value: {self.value}")
+
+
+class MediaSortingInput(SortInputObjectType):
+ class Meta:
+ sort_enum = MediaChoicesSortField
+ type_name = "media"
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.py
index f3fa820ac0..daa43a7f82 100644
--- a/saleor/graphql/product/tests/queries/test_product_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_query.py
@@ -1970,3 +1970,284 @@ def test_query_product_media_for_federation(
"url": f"http://{site_settings.site.domain}/media/products/product.jpg",
}
]
+
+
+QUERY_PRODUCT_WITH_VARIANT = """
+ query Product($id: ID!, $channel: String, $variant_id: ID, $sku: String){
+ product(id: $id, channel: $channel){
+ variant(id: $variant_id, sku: $sku){
+ id
+ sku
+ }
+ }
+ }
+ """
+
+
+ "variant_id, sku, result",
+ ((False, "123", "123"), (True, None, "123")),
+)
+def test_product_variant_field_filtering(
+ staff_api_client,
+ product,
+ variant_id,
+ sku,
+ result,
+ channel_USD,
+):
+ # given
+ variant = product.variants.first()
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "variant_id": (
+ graphene.Node.to_global_id("ProductVariant", variant.pk)
+ if variant_id
+ else None
+ ),
+ "sku": sku,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_VARIANT,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["product"]["variant"]["sku"] == result
+
+
+def test_product_variant_field_filtering_null_response(
+ staff_api_client,
+ product,
+ channel_USD,
+):
+ # given
+ sku = "not_existing"
+ variant_id = None
+
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "variant_id": variant_id,
+ "sku": sku,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_VARIANT,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["product"]["variant"] is None
+
+
+def test_product_variant_field_filtering_argument_required_error(
+ staff_api_client,
+ product,
+ channel_USD,
+):
+ # given
+ sku = None
+ variant_id = None
+
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "variant_id": variant_id,
+ "sku": sku,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_VARIANT,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ error_message = "At least one of arguments is required"
+ assert error_message in content["errors"][0]["message"]
+
+
+def test_product_variant_field_filtering_argument_cannot_be_combined_error(
+ staff_api_client,
+ product,
+ channel_USD,
+):
+ # given
+ sku = "123"
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "variant_id": variant_id,
+ "sku": sku,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_VARIANT,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ error_message = "Argument 'id' cannot be combined"
+ assert error_message in content["errors"][0]["message"]
+
+
+QUERY_PRODUCT_WITH_SORTED_MEDIA = """
+ query Product($id: ID!, $channel: String, $sort_by: MediaSortingInput){
+ product(id: $id, channel: $channel){
+ media(sortBy: $sort_by){
+ id
+ sortOrder
+ }
+ }
+ }
+ """
+
+
+def test_query_product_media_sorting_asc(
+ staff_api_client,
+ product_with_image_list,
+ channel_USD,
+):
+ # given
+ sort_by = {"field": "ID", "direction": "ASC"}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product_with_image_list.pk),
+ "channel": channel_USD.slug,
+ "sort_by": sort_by,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_SORTED_MEDIA,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ media = content["data"]["product"]["media"]
+ _, media1 = graphene.Node.from_global_id(media[0]["id"])
+ _, media2 = graphene.Node.from_global_id(media[1]["id"])
+ assert media1 < media2
+
+
+def test_query_product_media_sorting_desc(
+ staff_api_client, product_with_image_list, channel_USD
+):
+ # given
+ sort_by = {"field": "ID", "direction": "DESC"}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product_with_image_list.pk),
+ "channel": channel_USD.slug,
+ "sort_by": sort_by,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_SORTED_MEDIA,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ media = content["data"]["product"]["media"]
+ _, media1 = graphene.Node.from_global_id(media[0]["id"])
+ _, media2 = graphene.Node.from_global_id(media[1]["id"])
+ assert media1 > media2
+
+
+def test_query_product_media_sorting_default(
+ staff_api_client, product_with_image_list, channel_USD
+):
+ # given
+ sort_by = None
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product_with_image_list.pk),
+ "channel": channel_USD.slug,
+ "sort_by": sort_by,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_SORTED_MEDIA,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ media = content["data"]["product"]["media"]
+ media1 = media[0]["sortOrder"]
+ media2 = media[1]["sortOrder"]
+ assert media1 <= media2
+
+
+QUERY_PRODUCT_WITH_ATTRIBUTE = """
+query Product($id: ID!, $channel: String, $slug: String!){
+ product(id: $id, channel: $channel){
+ attribute(slug: $slug){
+ attribute{
+ id
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_product_attribute_field_filtering(staff_api_client, product, channel_USD):
+ # given
+ slug = "color"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "slug": slug,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ expected_slug = "color"
+ content = get_graphql_content(response)
+ queried_slug = content["data"]["product"]["attribute"]["attribute"]["slug"]
+ assert queried_slug == expected_slug
+
+
+def test_product_attribute_field_filtering_not_found(
+ staff_api_client, product, channel_USD
+):
+ # given
+ slug = ""
+
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "slug": slug,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["product"]["attribute"] is None
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 53d8cdb985..71ba025cde 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -79,6 +79,7 @@ from ...core.types import (
Weight,
)
from ...core.utils import from_global_id_or_error
+from ...core.validators import validate_one_of_args_is_in_query
from ...discount.dataloaders import DiscountsByDateTimeLoader
from ...meta.types import ObjectWithMetadata
from ...order.dataloaders import (
@@ -137,6 +138,7 @@ from ..dataloaders import (
)
from ..enums import ProductMediaType, ProductTypeKindEnum, VariantAttributeScope
from ..resolvers import resolve_product_variants, resolve_products
+from ..sorters import MediaSortingInput
from .channels import ProductChannelListing, ProductVariantChannelListing
from .digital_contents import DigitalContent
@@ -847,6 +849,18 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
description="A type of tax. Assigned by enabled tax gateway",
deprecation_reason=f"{DEPRECATED_IN_3X_FIELD} Use `taxClass` field instead.",
)
+ attribute = graphene.Field(
+ SelectedAttribute,
+ slug=graphene.Argument(
+ graphene.String,
+ description="Slug of the attribute",
+ required=True,
+ ),
+ description=(
+ f"Get a single attribute attached to product by attribute slug."
+ f"{ADDED_IN_39}"
+ ),
+ )
attributes = NonNullList(
SelectedAttribute,
required=True,
@@ -870,6 +884,12 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
f"{DEPRECATED_IN_3X_FIELD} Use the `mediaById` field instead."
),
)
+ variant = graphene.Field(
+ ProductVariant,
+ id=graphene.Argument(graphene.ID, description="ID of the variant."),
+ sku=graphene.Argument(graphene.String, description="SKU of the variant."),
+ description=f"Get a single variant by SKU or ID. {ADDED_IN_39}",
+ )
variants = NonNullList(
ProductVariant,
description=(
@@ -880,6 +900,9 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
)
media = NonNullList(
lambda: ProductMedia,
+ sort_by=graphene.Argument(
+ MediaSortingInput, description=f"Sort media. {ADDED_IN_39}"
+ ),
description="List of media for the product.",
)
images = NonNullList(
@@ -1219,6 +1242,22 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
.then(check_is_available_for_purchase)
)
+ @staticmethod
+ def resolve_attribute(root: ChannelContext[models.Product], info, slug):
+ def get_selected_attribute_by_slug(
+ attributes: List[SelectedAttribute],
+ ) -> Optional[SelectedAttribute]:
+ return next(
+ (atr for atr in attributes if atr["attribute"].slug == slug),
+ None,
+ )
+
+ return (
+ SelectedAttributesByProductIdLoader(info.context)
+ .load(root.node.id)
+ .then(get_selected_attribute_by_slug)
+ )
+
@staticmethod
def resolve_attributes(root: ChannelContext[models.Product], info):
return SelectedAttributesByProductIdLoader(info.context).load(root.node.id)
@@ -1234,13 +1273,62 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
return root.node.media.filter(pk=pk).first()
@staticmethod
- def resolve_media(root: ChannelContext[models.Product], info):
- return MediaByProductIdLoader(info.context).load(root.node.id)
+ def resolve_media(root: ChannelContext[models.Product], info, sort_by=None):
+ if sort_by is None:
+ sort_by = {
+ "field": ["sort_order"],
+ "direction": "",
+ }
+
+ def sort_media(media) -> list[ProductMedia]:
+ reversed = sort_by["direction"] == "-"
+ media_sorted = sorted(
+ media,
+ key=lambda x: tuple(getattr(x, field) for field in sort_by["field"]),
+ reverse=reversed,
+ )
+ return media_sorted
+
+ return MediaByProductIdLoader(info.context).load(root.node.id).then(sort_media)
@staticmethod
def resolve_images(root: ChannelContext[models.Product], info):
return ImagesByProductIdLoader(info.context).load(root.node.id)
+ @staticmethod
+ def resolve_variant(root: ChannelContext[models.Product], info, id=None, sku=None):
+ validate_one_of_args_is_in_query("id", id, "sku", sku)
+
+ def get_product_variant(
+ product_variants,
+ ) -> Optional[ProductVariant]:
+ if id:
+ id_type, variant_id = graphene.Node.from_global_id(id)
+ if id_type != "ProductVariant":
+ return None
+
+ return next(
+ (
+ variant
+ for variant in product_variants
+ if variant.node.id == int(variant_id)
+ ),
+ None,
+ )
+ if sku:
+ return next(
+ (
+ variant
+ for variant in product_variants
+ if variant.node.sku == sku
+ ),
+ None,
+ )
+ return None
+
+ variants = Product.resolve_variants(root, info)
+ return variants.then(get_product_variant)
+
@staticmethod
def resolve_variants(root: ChannelContext[models.Product], info):
requestor = get_user_or_app_from_context(info.context)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 62b489d6fc..58b5312825 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4803,6 +4803,16 @@ type Product implements Node & ObjectWithMetadata {
"""A type of tax. Assigned by enabled tax gateway"""
taxType: TaxType @deprecated(reason: "This field will be removed in Saleor 4.0. Use `taxClass` field instead.")
+ """
+ Get a single attribute attached to product by attribute slug.
+
+ Added in Saleor 3.9.
+ """
+ attribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): SelectedAttribute
+
"""List of attributes assigned to this product."""
attributes: [SelectedAttribute!]!
@@ -4825,13 +4835,33 @@ type Product implements Node & ObjectWithMetadata {
id: ID
): ProductImage @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `mediaById` field instead.")
+ """
+ Get a single variant by SKU or ID.
+
+ Added in Saleor 3.9.
+ """
+ variant(
+ """ID of the variant."""
+ id: ID
+
+ """SKU of the variant."""
+ sku: String
+ ): ProductVariant
+
"""
List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.
"""
variants: [ProductVariant!]
"""List of media for the product."""
- media: [ProductMedia!]
+ media(
+ """
+ Sort media.
+
+ Added in Saleor 3.9.
+ """
+ sortBy: MediaSortingInput
+ ): [ProductMedia!]
"""List of images for the product."""
images: [ProductImage!] @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `media` field instead.")
@@ -6307,6 +6337,19 @@ type Margin {
stop: Int
}
+input MediaSortingInput {
+ """Specifies the direction in which to sort products."""
+ direction: OrderDirection!
+
+ """Sort media by the selected field."""
+ field: MediaChoicesSortField!
+}
+
+enum MediaChoicesSortField {
+ """Sort media by ID."""
+ ID
+}
+
"""Represents a collection of products."""
type Collection implements Node & ObjectWithMetadata {
id: ID!
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index c1dad19e4d..4087c78f3b 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -3188,6 +3188,13 @@ def product_with_image(product, image, media_root):
return product
+def product_with_image_list(product, image_list, media_root):
+ ProductMedia.objects.create(product=product, image=image_list[0])
+ ProductMedia.objects.create(product=product, image=image_list[1])
+ return product
+
+
@pytest.fixture
def unavailable_product(product_type, category, channel_USD, default_tax_class):
product = Product.objects.create(