Skip to content

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

Add attributes where parameter to pages (#17872)

Maciej Korycinski01138c1e4e6f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18cc9736a9..58d2b76a97 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ All notable, unreleased changes to this project will be documented in this file.
- You can now filter and search orders using the new `where` and `search` fields on the `pages` query.
- Use `where` to define complex conditions with `AND`/`OR` logic and operators like `eq`, `oneOf`, `range`.
- Use `search` to perform full-text search across relevant fields.
+- Add support for filtering `pages` by associated attributes
- You can now filter and search orders using the new `where` and `search` fields on the `orders` query.
- Use `where` to define complex conditions with `AND`/`OR` logic and operators like `eq`, `oneOf`, `range`.
- Use `search` to perform full-text search across relevant fields.
@@ -78,6 +79,7 @@ All notable, unreleased changes to this project will be documented in this file.
- `collection.products`
- `pageType.availableAttributes`
+
### Webhooks
- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.
diff --git a/saleor/graphql/page/filters.py b/saleor/graphql/page/filters.py
index b6c6fef47e..b7f1d9ae2a 100644
--- a/saleor/graphql/page/filters.py
+++ b/saleor/graphql/page/filters.py
@@ -1,7 +1,11 @@
import django_filters
import graphene
-from django.db.models import Q
+from django.db.models import Exists, FloatField, OuterRef, Q
+from django.db.models.functions import Cast
+from graphql import GraphQLError
+from ...attribute import AttributeInputType
+from ...attribute.models import AssignedPageAttributeValue, Attribute, AttributeValue
from ...page import models
from ..core.doc_category import DOC_CATEGORY_PAGES
from ..core.filters import (
@@ -12,20 +16,26 @@ from ..core.filters import (
)
from ..core.filters.where_filters import (
GlobalIDMultipleChoiceWhereFilter,
+ ListObjectTypeWhereFilter,
MetadataWhereBase,
OperationObjectTypeWhereFilter,
)
from ..core.filters.where_input import (
+ DecimalFilterInput,
GlobalIDFilterInput,
StringFilterInput,
WhereInputObjectType,
)
+from ..core.types.base import BaseInputObjectType
+from ..core.types.common import DateRangeInput, DateTimeRangeInput
from ..utils import resolve_global_ids_to_primary_keys
from ..utils.filters import (
filter_by_id,
filter_by_ids,
+ filter_range_field,
filter_slug_list,
filter_where_by_id_field,
+ filter_where_by_numeric_field,
filter_where_by_value_field,
)
from .types import Page, PageType
@@ -54,6 +64,265 @@ def filter_page_type_search(qs, _, value):
return qs.filter(Q(name__trigram_similar=value) | Q(slug__trigram_similar=value))
+def filter_by_slug_or_name(attr_id, attr_value, db_connection_name: str):
+ attribute_values = AttributeValue.objects.using(db_connection_name).filter(
+ attribute_id=attr_id
+ )
+ if "slug" in attr_value:
+ attribute_values = filter_where_by_value_field(
+ attribute_values, "slug", attr_value["slug"]
+ )
+ if "name" in attr_value:
+ attribute_values = filter_where_by_value_field(
+ attribute_values, "name", attr_value["name"]
+ )
+ assigned_attr_value = AssignedPageAttributeValue.objects.using(
+ db_connection_name
+ ).filter(
+ Exists(attribute_values.filter(id=OuterRef("value_id"))),
+ page_id=OuterRef("id"),
+ )
+ return Q(Exists(assigned_attr_value))
+
+
+def filter_by_numeric_attribute(attr_id, numeric_value, db_connection_name: str):
+ qs_by_numeric = AttributeValue.objects.using(db_connection_name).filter(
+ attribute_id=attr_id
+ )
+ qs_by_numeric = qs_by_numeric.annotate(numeric_value=Cast("name", FloatField()))
+ qs_by_numeric = filter_where_by_numeric_field(
+ qs_by_numeric,
+ "numeric_value",
+ numeric_value,
+ )
+ assigned_attr_value = AssignedPageAttributeValue.objects.using(
+ db_connection_name
+ ).filter(
+ Exists(qs_by_numeric.filter(id=OuterRef("value_id"))),
+ page_id=OuterRef("id"),
+ )
+ return Q(Exists(assigned_attr_value))
+
+
+def filter_by_boolean_attribute(attr_id, boolean_value, db_connection_name: str):
+ qs_by_boolean = AttributeValue.objects.using(db_connection_name).filter(
+ attribute_id=attr_id
+ )
+ qs_by_boolean = qs_by_boolean.filter(boolean=boolean_value)
+ assigned_attr_value = AssignedPageAttributeValue.objects.using(
+ db_connection_name
+ ).filter(
+ Exists(qs_by_boolean.filter(id=OuterRef("value_id"))),
+ page_id=OuterRef("id"),
+ )
+ return Q(Exists(assigned_attr_value))
+
+
+def filter_by_date_attribute(attr_id, date_value, db_connection_name: str):
+ qs_by_date = AttributeValue.objects.using(db_connection_name).filter(
+ attribute_id=attr_id
+ )
+ qs_by_date = filter_range_field(
+ qs_by_date,
+ "date_time__date",
+ date_value,
+ )
+ assigned_attr_value = AssignedPageAttributeValue.objects.using(
+ db_connection_name
+ ).filter(
+ Exists(qs_by_date.filter(id=OuterRef("value_id"))),
+ page_id=OuterRef("id"),
+ )
+ return Q(Exists(assigned_attr_value))
+
+
+def filter_by_date_time_attribute(attr_id, date_time_value, db_connection_name: str):
+ qs_by_date_time = AttributeValue.objects.using(db_connection_name).filter(
+ attribute_id=attr_id
+ )
+ qs_by_date_time = filter_range_field(
+ qs_by_date_time,
+ "date_time",
+ date_time_value,
+ )
+ assigned_attr_value = AssignedPageAttributeValue.objects.using(
+ db_connection_name
+ ).filter(
+ Exists(qs_by_date_time.filter(id=OuterRef("value_id"))),
+ page_id=OuterRef("id"),
+ )
+ return Exists(assigned_attr_value)
+
+
+def filter_pages_by_attributes(qs, value):
+ attribute_slugs = {attr_filter["slug"] for attr_filter in value}
+ attributes_map = {
+ attr.slug: attr
+ for attr in Attribute.objects.using(qs.db).filter(slug__in=attribute_slugs)
+ }
+ if len(attribute_slugs) != len(attributes_map.keys()):
+ # Filter over non existing attribute
+ return qs.none()
+
+ attr_filter_expression = Q()
+ attr_without_values_input = [
+ attributes_map[attr_filter["slug"]]
+ for attr_filter in value
+ if not attr_filter.get("value")
+ ]
+ if attr_without_values_input:
+ atr_value_qs = AttributeValue.objects.using(qs.db).filter(
+ attribute_id__in=[attr.id for attr in attr_without_values_input]
+ )
+ assigned_attr_value = AssignedPageAttributeValue.objects.using(qs.db).filter(
+ Exists(atr_value_qs.filter(id=OuterRef("value_id"))),
+ page_id=OuterRef("id"),
+ )
+ attr_filter_expression = Q(Exists(assigned_attr_value))
+
+ for attr_filter in value:
+ attr_value = attr_filter.get("value")
+ if not attr_value:
+ # attrs without value input are handled separately
+ continue
+
+ attr = attributes_map[attr_filter["slug"]]
+ attr_value = attr_filter["value"]
+ if "slug" in attr_value or "name" in attr_value:
+ attr_filter_expression &= filter_by_slug_or_name(
+ attr.id,
+ attr_value,
+ qs.db,
+ )
+ elif attr.input_type == AttributeInputType.NUMERIC:
+ attr_filter_expression &= filter_by_numeric_attribute(
+ attr.id, attr_value["numeric"], qs.db
+ )
+ elif attr.input_type == AttributeInputType.BOOLEAN:
+ attr_filter_expression &= filter_by_boolean_attribute(
+ attr.id, attr_value["boolean"], qs.db
+ )
+ elif attr.input_type == AttributeInputType.DATE:
+ attr_filter_expression &= filter_by_date_attribute(
+ attr.id, attr_value["date"], qs.db
+ )
+ elif attr.input_type == AttributeInputType.DATE_TIME:
+ attr_filter_expression &= filter_by_date_time_attribute(
+ attr.id, attr_value["date_time"], qs.db
+ )
+ if attr_filter_expression != Q():
+ return qs.filter(attr_filter_expression)
+ return qs.none()
+
+
+def validate_attribute_value_input(attributes: list[dict], db_connection_name: str):
+ slug_list = [attr["slug"] for attr in attributes]
+ value_as_empty_list = []
+ value_more_than_one_list = []
+ invalid_input_type_list = []
+ if len(slug_list) != len(set(slug_list)):
+ raise GraphQLError(
+ message="Duplicated attribute slugs in attribute 'where' input are not allowed."
+ )
+
+ type_specific_value_list = {}
+ for attr in attributes:
+ if "value" not in attr:
+ continue
+ value = attr["value"]
+ if not value:
+ value_as_empty_list.append(attr["slug"])
+ continue
+ value_keys = value.keys()
+ if len(value_keys) > 1:
+ value_more_than_one_list.append(attr["slug"])
+ continue
+ value_key = list(value_keys)[0]
+ if value_key not in ["slug", "name"]:
+ type_specific_value_list[attr["slug"]] = value_key
+ if value[value_key] is None:
+ value_as_empty_list.append(attr["slug"])
+ continue
+
+ if type_specific_value_list:
+ attribute_input_type_map = Attribute.objects.using(db_connection_name).in_bulk(
+ type_specific_value_list.keys(),
+ field_name="slug",
+ )
+
+ for attr_slug, value_key in type_specific_value_list.items():
+ if attr_slug not in attribute_input_type_map:
+ continue
+
+ input_type = attribute_input_type_map[attr_slug].input_type
+ if "numeric" == value_key and input_type != AttributeInputType.NUMERIC:
+ invalid_input_type_list.append(attr_slug)
+ if "date" == value_key and input_type != AttributeInputType.DATE:
+ invalid_input_type_list.append(attr_slug)
+ if "date_time" == value_key and input_type != AttributeInputType.DATE_TIME:
+ invalid_input_type_list.append(attr_slug)
+ if "boolean" == value_key and input_type != AttributeInputType.BOOLEAN:
+ invalid_input_type_list.append(attr_slug)
+
+ if value_as_empty_list:
+ raise GraphQLError(
+ message=(
+ f"Incorrect input for attributes with slugs: {','.join(value_as_empty_list)}. "
+ "Provided 'value' cannot be empty or null."
+ )
+ )
+ if value_more_than_one_list:
+ raise GraphQLError(
+ message=(
+ f"Incorrect input for attributes with slugs: {','.join(value_more_than_one_list)}. "
+ "Provided 'value' must have only one input key."
+ )
+ )
+ if invalid_input_type_list:
+ raise GraphQLError(
+ message=(
+ f"Incorrect input for attributes with slugs: {','.join(invalid_input_type_list)}. "
+ "Provided 'value' do not match the attribute input type."
+ )
+ )
+
+
+class AttributeValuePageInput(BaseInputObjectType):
+ slug = StringFilterInput(
+ description="Filter by slug assigned to AttributeValue.",
+ )
+ name = StringFilterInput(
+ description="Filter by name assigned to AttributeValue.",
+ )
+ numeric = DecimalFilterInput(
+ required=False,
+ description="Filter by numeric value for attributes of numeric type.",
+ )
+ date = DateRangeInput(
+ required=False,
+ description="Filter by date value for attributes of date type.",
+ )
+ date_time = DateTimeRangeInput(
+ required=False,
+ description="Filter by date time value for attributes of date time type.",
+ )
+ boolean = graphene.Boolean(
+ required=False,
+ description="Filter by boolean value for attributes of boolean type.",
+ )
+
+
+class AttributePageWhereInput(BaseInputObjectType):
+ slug = graphene.String(description="Filter by attribute slug.", required=True)
+ value = AttributeValuePageInput(
+ required=False,
+ description=(
+ "Filter by value of the attribute. Only one value input field is allowed. "
+ "If provided more than one, the error will be raised."
+ ),
+ )
+
+
class PageWhere(MetadataWhereBase):
ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Page"))
slug = OperationObjectTypeWhereFilter(
@@ -66,6 +335,11 @@ class PageWhere(MetadataWhereBase):
method="filter_page_type",
help_text="Filter by page type.",
)
+ attributes = ListObjectTypeWhereFilter(
+ input_class=AttributePageWhereInput,
+ method="filter_attributes",
+ help_text="Filter by attributes associated with the page.",
+ )
@staticmethod
def filter_page_slug(qs, _, value):
@@ -77,6 +351,17 @@ class PageWhere(MetadataWhereBase):
return qs
return filter_where_by_id_field(qs, "page_type", value, "PageType")
+ @staticmethod
+ def filter_attributes(qs, _, value):
+ if not value:
+ return qs
+ return filter_pages_by_attributes(qs, value)
+
+ def is_valid(self):
+ if attributes := self.data.get("attributes"):
+ validate_attribute_value_input(attributes, self.queryset.db)
+ return super().is_valid()
+
def filter_page_search(qs, _, value):
# Skip search, as search is applied on resolver side.
diff --git a/saleor/graphql/page/tests/queries/test_pages_with_where.py b/saleor/graphql/page/tests/queries/test_pages_with_where.py
index ee60a1a0f4..7e04fd659d 100644
--- a/saleor/graphql/page/tests/queries/test_pages_with_where.py
+++ b/saleor/graphql/page/tests/queries/test_pages_with_where.py
@@ -1,6 +1,10 @@
+import datetime
+
import graphene
import pytest
+from .....attribute import AttributeInputType
+from .....attribute.utils import associate_attribute_values_to_instance
from .....page.models import Page, PageType
from ....tests.utils import get_graphql_content
@@ -144,6 +148,7 @@ def test_pages_with_where_metadata(
def test_pages_query_with_where_by_ids(
staff_api_client, permission_manage_pages, page_list, page_list_unpublished
):
+ # given
query = QUERY_PAGES_WITH_WHERE
page_ids = [
@@ -151,7 +156,860 @@ def test_pages_query_with_where_by_ids(
for page in [page_list[0], page_list_unpublished[-1]]
]
variables = {"where": {"ids": page_ids}}
+
+ # when
staff_api_client.user.user_permissions.add(permission_manage_pages)
+
+ # then
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert content["data"]["pages"]["totalCount"] == len(page_ids)
+
+
+def test_pages_query_with_attribute_slug(
+ staff_api_client, page_list, page_type, size_page_attribute
+):
+ # given
+ page_type.page_attributes.add(size_page_attribute)
+ page_attr_value = size_page_attribute.values.first()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {size_page_attribute.pk: [page_attr_value]}
+ )
+
+ variables = {"where": {"attributes": [{"slug": size_page_attribute.slug}]}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == 1
+ assert pages_nodes[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Page", page_list[0].pk
+ )
+
+
+ ("slug_input", "expected_count"),
+ [
+ ({"eq": "test-slug-1"}, 1),
+ ({"oneOf": ["test-slug-1", "test-slug-2"]}, 2),
+ ],
+)
+def test_pages_query_with_attribute_value_slug(
+ slug_input,
+ expected_count,
+ staff_api_client,
+ page_list,
+ page_type,
+ size_page_attribute,
+):
+ # given
+ page_type.page_attributes.add(size_page_attribute)
+
+ attr_value_1 = size_page_attribute.values.first()
+ attr_value_1.slug = "test-slug-1"
+ attr_value_1.save()
+
+ attr_value_2 = size_page_attribute.values.last()
+ attr_value_2.slug = "test-slug-2"
+ attr_value_2.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {size_page_attribute.pk: [attr_value_1]}
+ )
+
+ associate_attribute_values_to_instance(
+ page_list[1], {size_page_attribute.pk: [attr_value_2]}
+ )
+
+ variables = {
+ "where": {
+ "attributes": [
+ {"slug": size_page_attribute.slug, "value": {"slug": slug_input}}
+ ]
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == expected_count
+
+
+ ("name_input", "expected_count"),
+ [
+ ({"eq": "test-name-1"}, 1),
+ ({"oneOf": ["test-name-1", "test-name-2"]}, 2),
+ ],
+)
+def test_pages_query_with_attribute_value_name(
+ name_input,
+ expected_count,
+ staff_api_client,
+ page_list,
+ page_type,
+ size_page_attribute,
+):
+ # given
+ page_type.page_attributes.add(size_page_attribute)
+
+ attr_value_1 = size_page_attribute.values.first()
+ attr_value_1.name = "test-name-1"
+ attr_value_1.save()
+
+ attr_value_2 = size_page_attribute.values.last()
+ attr_value_2.name = "test-name-2"
+ attr_value_2.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {size_page_attribute.pk: [attr_value_1]}
+ )
+
+ associate_attribute_values_to_instance(
+ page_list[1], {size_page_attribute.pk: [attr_value_2]}
+ )
+
+ variables = {
+ "where": {
+ "attributes": [
+ {"slug": size_page_attribute.slug, "value": {"name": name_input}}
+ ]
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == expected_count
+
+
+ ("numeric_input", "expected_count"),
+ [
+ ({"numeric": {"eq": 1.2}}, 1),
+ ({"numeric": {"oneOf": [1.2, 2]}}, 2),
+ ({"numeric": {"range": {"gte": 1, "lte": 2}}}, 2),
+ ({"name": {"eq": "1.2"}}, 1),
+ ({"slug": {"eq": "1.2"}}, 1),
+ ({"name": {"oneOf": ["1.2", "2"]}}, 2),
+ ({"slug": {"oneOf": ["1.2", "2"]}}, 2),
+ ],
+)
+def test_pages_query_with_attribute_value_numeric(
+ numeric_input,
+ expected_count,
+ staff_api_client,
+ page_list,
+ page_type,
+ numeric_attribute_without_unit,
+):
+ # given
+ numeric_attribute_without_unit.type = "PAGE_TYPE"
+ numeric_attribute_without_unit.save()
+
+ page_type.page_attributes.add(numeric_attribute_without_unit)
+
+ attr_value_1 = numeric_attribute_without_unit.values.first()
+ attr_value_1.name = "1.2"
+ attr_value_1.slug = "1.2"
+ attr_value_1.save()
+
+ attr_value_2 = numeric_attribute_without_unit.values.last()
+ attr_value_2.name = "2"
+ attr_value_2.slug = "2"
+ attr_value_2.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {numeric_attribute_without_unit.pk: [attr_value_1]}
+ )
+
+ associate_attribute_values_to_instance(
+ page_list[1], {numeric_attribute_without_unit.pk: [attr_value_2]}
+ )
+
+ variables = {
+ "where": {
+ "attributes": [
+ {
+ "slug": numeric_attribute_without_unit.slug,
+ "value": numeric_input,
+ }
+ ]
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == expected_count
+
+
+ ("date_input", "expected_count"),
+ [
+ ({"date": {"gte": "2021-01-01"}}, 2),
+ ({"name": {"eq": "date-name-1"}}, 1),
+ ({"slug": {"eq": "date-slug-1"}}, 1),
+ (
+ {
+ "name": {"oneOf": ["date-name-1", "date-name-2"]},
+ },
+ 2,
+ ),
+ (
+ {
+ "slug": {"oneOf": ["date-slug-1", "date-slug-2"]},
+ },
+ 2,
+ ),
+ ({"date": {"gte": "2021-01-01", "lte": "2021-01-02"}}, 1),
+ ],
+)
+def test_pages_query_with_attribute_value_date(
+ date_input,
+ expected_count,
+ staff_api_client,
+ page_list,
+ page_type,
+ date_attribute,
+):
+ # given
+ date_attribute.type = "PAGE_TYPE"
+ date_attribute.save()
+
+ page_type.page_attributes.add(date_attribute)
+
+ attr_value_1 = date_attribute.values.first()
+ attr_value_1.date_time = datetime.datetime(2021, 1, 3, tzinfo=datetime.UTC)
+ attr_value_1.name = "date-name-1"
+ attr_value_1.slug = "date-slug-1"
+ attr_value_1.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {date_attribute.pk: [attr_value_1]}
+ )
+
+ second_attr_value = date_attribute.values.last()
+ second_attr_value.date_time = datetime.datetime(2021, 1, 1, tzinfo=datetime.UTC)
+ second_attr_value.name = "date-name-2"
+ second_attr_value.slug = "date-slug-2"
+ second_attr_value.save()
+
+ associate_attribute_values_to_instance(
+ page_list[1], {date_attribute.pk: [second_attr_value]}
+ )
+
+ variables = {
+ "where": {"attributes": [{"slug": date_attribute.slug, "value": date_input}]}
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == expected_count
+
+
+ ("date_time_input", "expected_count"),
+ [
+ (
+ {
+ "name": {"eq": "datetime-name-1"},
+ },
+ 1,
+ ),
+ (
+ {
+ "slug": {"eq": "datetime-slug-1"},
+ },
+ 1,
+ ),
+ (
+ {
+ "name": {"oneOf": ["datetime-name-1", "datetime-name-2"]},
+ },
+ 2,
+ ),
+ (
+ {
+ "slug": {"oneOf": ["datetime-slug-1", "datetime-slug-2"]},
+ },
+ 2,
+ ),
+ ({"dateTime": {"gte": "2021-01-01T00:00:00Z"}}, 2),
+ (
+ {
+ "dateTime": {
+ "gte": "2021-01-01T00:00:00Z",
+ "lte": "2021-01-02T00:00:00Z",
+ }
+ },
+ 1,
+ ),
+ ],
+)
+def test_pages_query_with_attribute_value_date_time(
+ date_time_input,
+ expected_count,
+ staff_api_client,
+ page_list,
+ page_type,
+ date_time_attribute,
+):
+ # given
+ date_time_attribute.type = "PAGE_TYPE"
+ date_time_attribute.save()
+
+ page_type.page_attributes.add(date_time_attribute)
+
+ attr_value_1 = date_time_attribute.values.first()
+ attr_value_1.date_time = datetime.datetime(2021, 1, 3, tzinfo=datetime.UTC)
+ attr_value_1.name = "datetime-name-1"
+ attr_value_1.slug = "datetime-slug-1"
+ attr_value_1.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {date_time_attribute.pk: [attr_value_1]}
+ )
+
+ second_attr_value = date_time_attribute.values.last()
+ second_attr_value.date_time = datetime.datetime(2021, 1, 1, tzinfo=datetime.UTC)
+ second_attr_value.name = "datetime-name-2"
+ second_attr_value.slug = "datetime-slug-2"
+ second_attr_value.save()
+
+ associate_attribute_values_to_instance(
+ page_list[1], {date_time_attribute.pk: [second_attr_value]}
+ )
+
+ variables = {
+ "where": {
+ "attributes": [
+ {
+ "slug": date_time_attribute.slug,
+ "value": date_time_input,
+ }
+ ]
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == expected_count
+
+
+ "boolean_input",
+ [
+ {"boolean": True},
+ {
+ "name": {"eq": "True-name"},
+ },
+ {
+ "slug": {"eq": "true_slug"},
+ },
+ {"name": {"oneOf": ["True-name", "True-name-2"]}},
+ {
+ "slug": {"oneOf": ["true_slug"]},
+ },
+ ],
+)
+def test_pages_query_with_attribute_value_boolean(
+ boolean_input,
+ staff_api_client,
+ page_list,
+ page_type,
+ boolean_attribute,
+):
+ # given
+ boolean_attribute.type = "PAGE_TYPE"
+ boolean_attribute.save()
+
+ page_type.page_attributes.add(boolean_attribute)
+
+ true_value = boolean_attribute.values.filter(boolean=True).first()
+ true_value.name = "True-name"
+ true_value.slug = "true_slug"
+ true_value.save()
+
+ false_value = boolean_attribute.values.filter(boolean=False).first()
+ false_value.name = "False-name"
+ false_value.slug = "false_slug"
+ false_value.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0], {boolean_attribute.pk: [true_value]}
+ )
+
+ associate_attribute_values_to_instance(
+ page_list[1], {boolean_attribute.pk: [false_value]}
+ )
+
+ variables = {"where": {"attributes": [{"slug": "boolean", "value": boolean_input}]}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == 1
+ assert pages_nodes[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Page", page_list[0].pk
+ )
+
+
+ "attribute_filter",
+ [
+ # When input receives None
+ [{"slug": "page-size"}, {"slug": "page-size"}],
+ [{"slug": "page-size", "value": {"slug": None}}],
+ [{"slug": "page-size", "value": {"name": None}}],
+ # Cant have multiple value input fields
+ [
+ {
+ "slug": "page-size",
+ "value": {
+ "slug": {"eq": "true_slug"},
+ "name": {"eq": "name"},
+ },
+ }
+ ],
+ [
+ {
+ "slug": "page-size",
+ "value": {
+ "slug": {"oneOf": ["true_slug"]},
+ "name": {"oneOf": ["name"]},
+ },
+ }
+ ],
+ [
+ {
+ "slug": "page-size",
+ "value": {
+ "name": {"eq": "name"},
+ },
+ },
+ {"slug": "count", "value": {"numeric": None}},
+ ],
+ # numeric attribute
+ [{"slug": "count", "value": {"numeric": None}}],
+ [{"slug": "count", "value": {"name": None}}],
+ [{"slug": "count", "value": {"slug": None}}],
+ # Numeric can't be used with non numeric fields
+ [{"slug": "count", "value": {"boolean": False}}],
+ # boolean attribute
+ [{"slug": "boolean", "value": {"boolean": None}}],
+ [{"slug": "boolean", "value": {"name": None}}],
+ [{"slug": "boolean", "value": {"slug": None}}],
+ # Boolean can't be used with non boolean fields
+ [{"slug": "boolean", "value": {"numeric": {"eq": 1.2}}}],
+ # date attribute
+ [{"slug": "date", "value": {"date": None}}],
+ [{"slug": "date", "value": {"name": None}}],
+ [{"slug": "date", "value": {"slug": None}}],
+ # Date can't be used with non date fields
+ [{"slug": "date", "value": {"numeric": {"eq": 1.2}}}],
+ # datetime attribute
+ [{"slug": "date_time", "value": {"dateTime": None}}],
+ [{"slug": "date_time", "value": {"name": None}}],
+ [{"slug": "date_time", "value": {"slug": None}}],
+ # Date time can't be used with non date time fields
+ [{"slug": "date_time", "value": {"numeric": {"eq": 1.2}}}],
+ ],
+)
+def test_pages_query_failed_filter_validation(
+ attribute_filter,
+ staff_api_client,
+ page_list,
+ page_type,
+ size_page_attribute,
+ tag_page_attribute,
+ boolean_attribute,
+ numeric_attribute_without_unit,
+ date_attribute,
+ date_time_attribute,
+):
+ # given
+ boolean_attribute.type = "PAGE_TYPE"
+ boolean_attribute.save()
+ numeric_attribute_without_unit.type = "PAGE_TYPE"
+ numeric_attribute_without_unit.save()
+
+ page_type.page_attributes.add(size_page_attribute)
+ page_type.page_attributes.add(tag_page_attribute)
+ page_type.page_attributes.add(boolean_attribute)
+ page_type.page_attributes.add(numeric_attribute_without_unit)
+ page_type.page_attributes.add(date_attribute)
+ page_type.page_attributes.add(date_time_attribute)
+
+ size_value = size_page_attribute.values.get(slug="10")
+ tag_value = tag_page_attribute.values.get(name="About")
+ boolean_value = boolean_attribute.values.filter(boolean=True).first()
+ numeric_value = numeric_attribute_without_unit.values.first()
+ date_time_value = date_time_attribute.values.first()
+ date_value = date_attribute.values.first()
+
+ date_attribute.slug = "date"
+ date_attribute.save()
+ date_time_attribute.slug = "date_time"
+ date_time_attribute.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0],
+ {
+ size_page_attribute.pk: [size_value],
+ tag_page_attribute.pk: [tag_value],
+ boolean_attribute.pk: [boolean_value],
+ numeric_attribute_without_unit.pk: [numeric_value],
+ date_attribute.pk: [date_value],
+ date_time_attribute.pk: [date_time_value],
+ },
+ )
+
+ variables = {"where": {"attributes": attribute_filter}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+ assert content["data"]["pages"] is None
+
+
+ "attribute_filter",
+ [
+ # Non-existing attribute slug
+ [{"slug": "non-existing-attribute"}],
+ # Existing attribute with non-existing value name
+ [{"slug": "tag", "value": {"name": {"eq": "Non-existing Name"}}}],
+ # Existing numeric attribute with out-of-range value
+ [{"slug": "count", "value": {"numeric": {"eq": 999}}}],
+ # Existing boolean attribute with no matching boolean value
+ [{"slug": "boolean", "value": {"boolean": False}}],
+ # Multiple attributes where one doesn't exist
+ [
+ {"slug": "page-size", "value": {"slug": {"eq": "10"}}},
+ {"slug": "non-existing-attr", "value": {"slug": {"eq": "some-value"}}},
+ ],
+ ],
+)
+def test_pages_query_with_non_matching_records(
+ attribute_filter,
+ staff_api_client,
+ page_list,
+ page_type,
+ size_page_attribute,
+ tag_page_attribute,
+ boolean_attribute,
+ numeric_attribute_without_unit,
+ date_attribute,
+ date_time_attribute,
+):
+ # given
+ boolean_attribute.type = "PAGE_TYPE"
+ boolean_attribute.save()
+ numeric_attribute_without_unit.type = "PAGE_TYPE"
+ numeric_attribute_without_unit.save()
+
+ page_type.page_attributes.add(size_page_attribute)
+ page_type.page_attributes.add(tag_page_attribute)
+ page_type.page_attributes.add(boolean_attribute)
+ page_type.page_attributes.add(numeric_attribute_without_unit)
+ page_type.page_attributes.add(date_attribute)
+ page_type.page_attributes.add(date_time_attribute)
+
+ size_value = size_page_attribute.values.get(slug="10")
+ tag_value = tag_page_attribute.values.get(name="About")
+ boolean_value = boolean_attribute.values.filter(boolean=True).first()
+ numeric_value = numeric_attribute_without_unit.values.first()
+ date_time_value = date_time_attribute.values.first()
+ date_value = date_attribute.values.first()
+
+ date_attribute.slug = "date"
+ date_attribute.save()
+ date_time_attribute.slug = "date_time"
+ date_time_attribute.save()
+
+ associate_attribute_values_to_instance(
+ page_list[0],
+ {
+ size_page_attribute.pk: [size_value],
+ tag_page_attribute.pk: [tag_value],
+ boolean_attribute.pk: [boolean_value],
+ numeric_attribute_without_unit.pk: [numeric_value],
+ date_attribute.pk: [date_value],
+ date_time_attribute.pk: [date_time_value],
+ },
+ )
+
+ variables = {"where": {"attributes": attribute_filter}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == 0
+
+
+ ("attribute_where_input", "expected_count_result"),
+ [
+ (
+ [
+ {
+ "slug": "page-size",
+ "value": {
+ "numeric": {"range": {"lte": 89}},
+ },
+ },
+ {
+ "slug": "tag",
+ "value": {"name": {"oneOf": ["About", "Help"]}},
+ },
+ {
+ "slug": "author",
+ "value": {
+ "slug": {"oneOf": ["test-author-1"]},
+ },
+ },
+ {"slug": "boolean", "value": {"boolean": True}},
+ ],
+ 1,
+ ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {
+ # "slug": {"eq": "10"},
+ # },
+ # },
+ # {
+ # "slug": "tag",
+ # "value": {"name": {"oneOf": ["About", "Help"]}},
+ # },
+ # ],
+ # 1,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"eq": "10"}},
+ # },
+ # {"slug": "boolean", "value": {"boolean": False}},
+ # ],
+ # 0,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "tag",
+ # "value": {
+ # "name": {"eq": "About"},
+ # },
+ # },
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"eq": "10"}},
+ # },
+ # ],
+ # 1,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"eq": "15"}},
+ # },
+ # {
+ # "slug": "tag",
+ # "value": {"name": {"eq": "Help"}},
+ # },
+ # {"slug": "boolean", "value": {"boolean": False}},
+ # ],
+ # 0,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "author",
+ # "value": {"slug": {"oneOf": ["test-author-1", "test-author-2"]}},
+ # },
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"eq": "10"}},
+ # },
+ # ],
+ # 1,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"eq": "10"}},
+ # },
+ # {
+ # "slug": "author",
+ # "value": {"name": {"eq": "Test author 1"}},
+ # },
+ # ],
+ # 1,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"eq": "10"}},
+ # },
+ # {
+ # "slug": "tag",
+ # "value": {"name": {"eq": "About"}},
+ # },
+ # {
+ # "slug": "author",
+ # "value": {"slug": {"eq": "test-author-1"}},
+ # },
+ # ],
+ # 1,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"oneOf": ["10", "15"]}},
+ # },
+ # {
+ # "slug": "tag",
+ # "value": {"name": {"oneOf": ["About", "Help"]}},
+ # },
+ # ],
+ # 2,
+ # ),
+ # (
+ # [
+ # {
+ # "slug": "page-size",
+ # "value": {"slug": {"oneOf": ["10", "15"]}},
+ # },
+ # {"slug": "boolean", "value": {"boolean": True}},
+ # ],
+ # 1,
+ # ),
+ ],
+)
+def test_pages_query_with_multiple_attribute_filters(
+ attribute_where_input,
+ expected_count_result,
+ staff_api_client,
+ page_list,
+ page_type,
+ size_page_attribute,
+ tag_page_attribute,
+ author_page_attribute,
+ boolean_attribute,
+):
+ # given
+ boolean_attribute.type = "PAGE_TYPE"
+ boolean_attribute.save()
+
+ page_type.page_attributes.add(size_page_attribute)
+ size_page_attribute.input_type = AttributeInputType.NUMERIC
+ size_page_attribute.save()
+
+ page_type.page_attributes.add(tag_page_attribute)
+ page_type.page_attributes.add(author_page_attribute)
+ page_type.page_attributes.add(boolean_attribute)
+
+ size_value = size_page_attribute.values.get(slug="10")
+ tag_value = tag_page_attribute.values.get(name="About")
+ author_value = author_page_attribute.values.get(slug="test-author-1")
+ boolean_value = boolean_attribute.values.filter(boolean=True).first()
+
+ associate_attribute_values_to_instance(
+ page_list[0],
+ {
+ size_page_attribute.pk: [size_value],
+ tag_page_attribute.pk: [tag_value],
+ author_page_attribute.pk: [author_value],
+ boolean_attribute.pk: [boolean_value],
+ },
+ )
+
+ tag_value_2 = tag_page_attribute.values.get(name="Help")
+ size_value_15 = size_page_attribute.values.get(slug="15")
+
+ associate_attribute_values_to_instance(
+ page_list[1],
+ {
+ size_page_attribute.pk: [size_value_15],
+ tag_page_attribute.pk: [tag_value_2],
+ },
+ )
+
+ variables = {"where": {"attributes": attribute_where_input}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGES_WITH_WHERE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["pages"]["edges"]
+ assert len(pages_nodes) == expected_count_result
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b4f82bdf57..342139b4af 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -12867,6 +12867,9 @@ input PageWhereInput @doc(category: "Pages") {
"""Filter by page type."""
pageType: GlobalIDFilterInput
+ """Filter by attributes associated with the page."""
+ attributes: [AttributePageWhereInput!]
+
"""List of conditions that must be met."""
AND: [PageWhereInput!]
@@ -12904,6 +12907,36 @@ input MetadataValueFilterInput {
oneOf: [String!]
}
+input AttributePageWhereInput {
+ """Filter by attribute slug."""
+ slug: String!
+
+ """
+ Filter by value of the attribute. Only one value input field is allowed. If provided more than one, the error will be raised.
+ """
+ value: AttributeValuePageInput
+}
+
+input AttributeValuePageInput {
+ """Filter by slug assigned to AttributeValue."""
+ slug: StringFilterInput
+
+ """Filter by name assigned to AttributeValue."""
+ name: StringFilterInput
+
+ """Filter by numeric value for attributes of numeric type."""
+ numeric: DecimalFilterInput
+
+ """Filter by date value for attributes of date type."""
+ date: DateRangeInput
+
+ """Filter by date time value for attributes of date time type."""
+ dateTime: DateTimeRangeInput
+
+ """Filter by boolean value for attributes of boolean type."""
+ boolean: Boolean
+}
+
type PageTypeCountableConnection @doc(category: "Pages") {
"""Pagination data for this connection."""
pageInfo: PageInfo!