Skip to content

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

Attribute filters improvement (#11737)

Iga Karbowiakffa97e42f10d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 47826a211c..e8302db8e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,11 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix adding invalid label to meta fields - #11718 by @IKarbowiak
- Add filter by `checkoutToken` to `Query.orders`. - #11689 by @kadewu
- Add `WebhookTrigger` mutation - #11687 by @zedzior
+- Attribute filters improvement - #11737 by @IKarbowiak
+ - introduce `where` option on `attributes` query
+ - add `search` option on `attributes` query
+ - deprecate `product.variant` field
+ - deprecate the following `Attribute` fields: `filterableInStorefront`, `storefrontSearchPosition`, `availableInGrid`.
### Other changes
- Allow `webhookCreate` and `webhookUpdate` mutations to inherit events from `query` field - #11736 by @zedzior
diff --git a/saleor/attribute/migrations/0028_attribute_attribute_gin.py b/saleor/attribute/migrations/0028_attribute_attribute_gin.py
new file mode 100644
index 0000000000..268b735409
--- /dev/null
+++ b/saleor/attribute/migrations/0028_attribute_attribute_gin.py
@@ -0,0 +1,29 @@
+# Generated by Django 3.2.16 on 2023-01-18 14:56
+
+import django.contrib.postgres.indexes
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0027_auto_20221205_1650"),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name="attribute",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["slug", "name", "type", "input_type", "entity_type", "unit"],
+ name="attribute_gin",
+ opclasses=[
+ "gin_trgm_ops",
+ "gin_trgm_ops",
+ "gin_trgm_ops",
+ "gin_trgm_ops",
+ "gin_trgm_ops",
+ "gin_trgm_ops",
+ ],
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 50dbdaddbe..cce7f1db50 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, TypeVar, Union
from django.contrib.postgres.indexes import GinIndex
from django.db import models
-from django.db.models import F, OrderBy, Q
+from django.db.models import Exists, F, OrderBy, OuterRef, Q
from ...core.db.fields import SanitizedJSONField
from ...core.models import ModelWithExternalReference, ModelWithMetadata, SortableModel
@@ -50,7 +50,8 @@ class BaseAttributeQuerySet(models.QuerySet[T]):
class AssociatedAttributeQuerySet(BaseAttributeQuerySet[T]):
def get_public_attributes(self):
- return self.filter(attribute__visible_in_storefront=True)
+ attributes = Attribute.objects.filter(visible_in_storefront=True)
+ return self.filter(Exists(attributes.filter(id=OuterRef("attribute_id"))))
AssociatedAttributeManager = models.Manager.from_queryset(AssociatedAttributeQuerySet)
@@ -168,6 +169,15 @@ class Attribute(ModelWithMetadata, ModelWithExternalReference):
class Meta(ModelWithMetadata.Meta):
ordering = ("storefront_search_position", "slug")
+ indexes = [
+ *ModelWithMetadata.Meta.indexes,
+ GinIndex(
+ name="attribute_gin",
+ # `opclasses` and `fields` should be the same length
+ fields=["slug", "name", "type", "input_type", "entity_type", "unit"],
+ opclasses=["gin_trgm_ops"] * 6,
+ ),
+ ]
def __str__(self) -> str:
return self.name
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
index eac1d12141..b61808e7f7 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -2,23 +2,34 @@ import django_filters
import graphene
from django.db.models import Q
+from ...attribute import AttributeInputType
from ...attribute.models import Attribute, AttributeValue
from ...permission.utils import has_one_of_permissions
from ...product import models
from ...product.models import ALL_PRODUCTS_PERMISSIONS
-from ..attribute.enums import AttributeTypeEnum
from ..channel.filters import get_channel_slug_from_filter_data
+from ..core.descriptions import ADDED_IN_311, PREVIEW_FEATURE
+from ..core.enums import MeasurementUnitsEnum
from ..core.filters import (
EnumFilter,
GlobalIDFilter,
GlobalIDMultipleChoiceFilter,
ListObjectTypeFilter,
MetadataFilterBase,
+ OperationObjectTypeFilter,
filter_slug_list,
)
-from ..core.types import ChannelFilterInputObjectType, FilterInputObjectType
+from ..core.types import (
+ ChannelFilterInputObjectType,
+ FilterInputObjectType,
+ NonNullList,
+ StringFilterInput,
+)
+from ..core.types.filter_input import FilterInputDescriptions, WhereInputObjectType
from ..core.utils import from_global_id_or_error
from ..utils import get_user_or_app_from_context
+from ..utils.filters import filter_by_id, filter_by_string_field
+from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug):
@@ -55,7 +66,13 @@ def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug
)
-def filter_attribute_type(qs, _, value):
+def filter_attribute_search(qs, _, value):
+ if not value:
+ return qs
+ return qs.filter(Q(slug__ilike=value) | Q(name__ilike=value))
+
+
+def filter_by_attribute_type(qs, _, value):
if not value:
return qs
return qs.filter(type=value)
@@ -79,9 +96,9 @@ class AttributeValueFilter(django_filters.FilterSet):
class AttributeFilter(MetadataFilterBase):
- search = django_filters.CharFilter(method="filter_attribute_search")
+ search = django_filters.CharFilter(method=filter_attribute_search)
ids = GlobalIDMultipleChoiceFilter(field_name="id")
- type = EnumFilter(input_class=AttributeTypeEnum, method=filter_attribute_type)
+ type = EnumFilter(input_class=AttributeTypeEnum, method=filter_by_attribute_type)
in_collection = GlobalIDFilter(method="filter_in_collection")
in_category = GlobalIDFilter(method="filter_in_category")
@@ -98,9 +115,6 @@ class AttributeFilter(MetadataFilterBase):
"available_in_grid",
]
- def filter_attribute_search(self, qs, _, value):
- return qs.filter(Q(slug__ilike=value) | Q(name__ilike=value))
-
def filter_in_collection(self, qs, name, value):
requestor = get_user_or_app_from_context(self.request)
channel_slug = get_channel_slug_from_filter_data(self.data)
@@ -124,3 +138,125 @@ class AttributeFilterInput(ChannelFilterInputObjectType):
class AttributeValueFilterInput(FilterInputObjectType):
class Meta:
filterset_class = AttributeValueFilter
+
+
+class AttributeInputTypeEnumFilterInput(graphene.InputObjectType):
+ eq = AttributeInputTypeEnum(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ AttributeInputTypeEnum,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+
+class AttributeEntityTypeEnumFilterInput(graphene.InputObjectType):
+ eq = AttributeEntityTypeEnum(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ AttributeEntityTypeEnum,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+
+class AttributeTypeEnumFilterInput(graphene.InputObjectType):
+ eq = AttributeTypeEnum(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ AttributeTypeEnum,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+
+class MeasurementUnitsEnumFilterInput(graphene.InputObjectType):
+ eq = MeasurementUnitsEnum(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ MeasurementUnitsEnum,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+
+def filter_attribute_name(qs, _, value):
+ return filter_by_string_field(qs, "name", value)
+
+
+def filter_attribute_slug(qs, _, value):
+ return filter_by_string_field(qs, "slug", value)
+
+
+def filter_with_choices(qs, _, value):
+ lookup = Q(input_type__in=AttributeInputType.TYPES_WITH_CHOICES)
+ if value is True:
+ return qs.filter(lookup)
+ elif value is False:
+ return qs.exclude(lookup)
+ return qs
+
+
+def filter_attribute_input_type(qs, _, value):
+ return filter_by_string_field(qs, "input_type", value)
+
+
+def filter_attribute_entity_type(qs, _, value):
+ return filter_by_string_field(qs, "entity_type", value)
+
+
+def filter_attribute_type(qs, _, value):
+ return filter_by_string_field(qs, "type", value)
+
+
+def filter_attribute_unit(qs, _, value):
+ return filter_by_string_field(qs, "unit", value)
+
+
+class AttributeWhere(MetadataFilterBase):
+ ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("Attribute"))
+ name = OperationObjectTypeFilter(
+ input_class=StringFilterInput, method=filter_attribute_name
+ )
+ slug = OperationObjectTypeFilter(
+ input_class=StringFilterInput, method=filter_attribute_slug
+ )
+ with_choices = django_filters.BooleanFilter(method=filter_with_choices)
+ input_type = OperationObjectTypeFilter(
+ AttributeInputTypeEnumFilterInput, method=filter_attribute_input_type
+ )
+ entity_type = OperationObjectTypeFilter(
+ AttributeEntityTypeEnumFilterInput, method=filter_attribute_entity_type
+ )
+ type = OperationObjectTypeFilter(
+ AttributeTypeEnumFilterInput, method=filter_attribute_type
+ )
+ unit = OperationObjectTypeFilter(
+ MeasurementUnitsEnumFilterInput, method=filter_attribute_unit
+ )
+ in_collection = GlobalIDFilter(method="filter_in_collection")
+ in_category = GlobalIDFilter(method="filter_in_category")
+
+ class Meta:
+ model = Attribute
+ fields = [
+ "value_required",
+ "visible_in_storefront",
+ "filterable_in_dashboard",
+ ]
+
+ def filter_in_collection(self, qs, name, value):
+ requestor = get_user_or_app_from_context(self.request)
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return filter_attributes_by_product_types(
+ qs, name, value, requestor, channel_slug
+ )
+
+ def filter_in_category(self, qs, name, value):
+ requestor = get_user_or_app_from_context(self.request)
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return filter_attributes_by_product_types(
+ qs, name, value, requestor, channel_slug
+ )
+
+
+class AttributeWhereInput(WhereInputObjectType):
+ class Meta:
+ filterset_class = AttributeWhere
+ description = "Where filtering options." + ADDED_IN_311 + PREVIEW_FEATURE
diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.py
index d8c80b08c7..64f0626bb8 100644
--- a/saleor/graphql/attribute/mutations/attribute_create.py
+++ b/saleor/graphql/attribute/mutations/attribute_create.py
@@ -69,15 +69,19 @@ class AttributeCreateInput(graphene.InputObjectType):
)
filterable_in_storefront = graphene.Boolean(
description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT
+ + DEPRECATED_IN_3X_INPUT
)
filterable_in_dashboard = graphene.Boolean(
description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD
)
storefront_search_position = graphene.Int(
- required=False, description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
+ required=False,
+ description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
+ + DEPRECATED_IN_3X_INPUT,
)
available_in_grid = graphene.Boolean(
- required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID
+ required=False,
+ description=AttributeDescriptions.AVAILABLE_IN_GRID + DEPRECATED_IN_3X_INPUT,
)
external_reference = graphene.String(
description="External ID of this attribute." + ADDED_IN_310, required=False
diff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.py
index 16f4508618..4a411b4aa5 100644
--- a/saleor/graphql/attribute/mutations/attribute_update.py
+++ b/saleor/graphql/attribute/mutations/attribute_update.py
@@ -5,7 +5,7 @@ from ....attribute import models as models
from ....attribute.error_codes import AttributeErrorCode
from ....permission.enums import ProductTypePermissions
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_310
+from ...core.descriptions import ADDED_IN_310, DEPRECATED_IN_3X_INPUT
from ...core.enums import MeasurementUnitsEnum
from ...core.mutations import ModelWithExtRefMutation
from ...core.types import AttributeError, NonNullList
@@ -43,15 +43,19 @@ class AttributeUpdateInput(graphene.InputObjectType):
)
filterable_in_storefront = graphene.Boolean(
description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT
+ + DEPRECATED_IN_3X_INPUT
)
filterable_in_dashboard = graphene.Boolean(
description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD
)
storefront_search_position = graphene.Int(
- required=False, description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
+ required=False,
+ description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
+ + DEPRECATED_IN_3X_INPUT,
)
available_in_grid = graphene.Boolean(
- required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID
+ required=False,
+ description=AttributeDescriptions.AVAILABLE_IN_GRID + DEPRECATED_IN_3X_INPUT,
)
external_reference = graphene.String(
description="External ID of this product." + ADDED_IN_310, required=False
diff --git a/saleor/graphql/attribute/resolvers.py b/saleor/graphql/attribute/resolvers.py
index fa80222b43..bd5a01fd29 100644
--- a/saleor/graphql/attribute/resolvers.py
+++ b/saleor/graphql/attribute/resolvers.py
@@ -5,4 +5,4 @@ from ..utils import get_user_or_app_from_context
def resolve_attributes(info, qs=None):
requestor = get_user_or_app_from_context(info.context)
qs = qs or models.Attribute.objects.get_visible_to_user(requestor)
- return qs.distinct()
+ return qs
diff --git a/saleor/graphql/attribute/schema.py b/saleor/graphql/attribute/schema.py
index add1391688..2fe14c00d4 100644
--- a/saleor/graphql/attribute/schema.py
+++ b/saleor/graphql/attribute/schema.py
@@ -3,12 +3,12 @@ import graphene
from ...attribute import models
from ..core import ResolveInfo
from ..core.connection import create_connection_slice, filter_connection_queryset
-from ..core.descriptions import ADDED_IN_310
+from ..core.descriptions import ADDED_IN_310, ADDED_IN_311, PREVIEW_FEATURE
from ..core.fields import FilterConnectionField
from ..core.utils.resolvers import resolve_by_global_id_slug_or_ext_ref
from ..translations.mutations import AttributeTranslate, AttributeValueTranslate
from .bulk_mutations import AttributeBulkDelete, AttributeValueBulkDelete
-from .filters import AttributeFilterInput
+from .filters import AttributeFilterInput, AttributeWhereInput, filter_attribute_search
from .mutations import (
AttributeCreate,
AttributeDelete,
@@ -28,6 +28,14 @@ class AttributeQueries(graphene.ObjectType):
AttributeCountableConnection,
description="List of the shop's attributes.",
filter=AttributeFilterInput(description="Filtering options for attributes."),
+ where=AttributeWhereInput(
+ description="Filtering options for attributes."
+ + ADDED_IN_311
+ + PREVIEW_FEATURE
+ ),
+ search=graphene.String(
+ description="Search attributes." + ADDED_IN_311 + PREVIEW_FEATURE
+ ),
sort_by=AttributeSortingInput(description="Sorting options for attributes."),
channel=graphene.String(
description="Slug of a channel for which the data should be returned."
@@ -43,9 +51,11 @@ class AttributeQueries(graphene.ObjectType):
description="Look up an attribute by ID, slug or external reference.",
)
- def resolve_attributes(self, info: ResolveInfo, **kwargs):
+ def resolve_attributes(self, info: ResolveInfo, *, search=None, **kwargs):
qs = resolve_attributes(info)
qs = filter_connection_queryset(qs, kwargs, info.context)
+ if search:
+ qs = filter_attribute_search(qs, None, search)
return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)
def resolve_attribute(
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_where.py b/saleor/graphql/attribute/tests/queries/test_attribute_where.py
new file mode 100644
index 0000000000..dec71bc2a8
--- /dev/null
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_where.py
@@ -0,0 +1,1659 @@
+import json
+
+import graphene
+import pytest
+
+from .....attribute import AttributeInputType, AttributeType
+from .....attribute.models import Attribute
+from .....attribute.utils import associate_attribute_values_to_instance
+from .....core.units import MeasurementUnits
+from .....product import ProductTypeKind
+from .....product.models import ProductType
+from ....core.enums import MeasurementUnitsEnum
+from ....tests.utils import get_graphql_content, get_graphql_content_from_response
+from ...enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
+
+ATTRIBUTES_WHERE_QUERY = """
+ query($where: AttributeWhereInput!, $channel: String) {
+ attributes(first: 10, where: $where, channel: $channel) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_attributes_filter_by_ids(api_client, product_type_attribute_list):
+ # given
+ ids = [
+ graphene.Node.to_global_id("Attribute", attribute.pk)
+ for attribute in product_type_attribute_list[:2]
+ ]
+ variables = {"where": {"ids": ids}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ attributes = data["data"]["attributes"]["edges"]
+ assert len(attributes) == 2
+ received_slugs = {node["node"]["slug"] for node in attributes}
+ assert received_slugs == {
+ product_type_attribute_list[0].slug,
+ product_type_attribute_list[1].slug,
+ }
+
+
+ "where, indexes",
+ [
+ ({"eq": "Color"}, [0]),
+ ({"eq": "test"}, []),
+ ({"oneOf": ["Color", "Text"]}, [0, 2]),
+ ({"oneOf": ["a", "acd"]}, []),
+ ],
+)
+def test_attributes_filter_by_name(
+ where, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+ variables = {"where": {"name": where}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"eq": "color"}, [0]),
+ ({"eq": "test"}, []),
+ ({"oneOf": ["color", "text"]}, [0, 2]),
+ ({"oneOf": ["a", "acd"]}, []),
+ ],
+)
+def test_attributes_filter_by_slug(
+ where, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+ variables = {"where": {"slug": where}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
[email protected]("value, indexes", [(True, [0]), (False, [1, 2])])
+def test_attributes_filter_by_with_choices(
+ value, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+ variables = {"where": {"withChoices": value}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"eq": AttributeInputTypeEnum.DROPDOWN.name}, [0]),
+ ({"eq": AttributeInputTypeEnum.FILE.name}, []),
+ (
+ {
+ "oneOf": [
+ AttributeInputTypeEnum.RICH_TEXT.name,
+ AttributeInputTypeEnum.DATE.name,
+ ]
+ },
+ [1, 2],
+ ),
+ (
+ {
+ "oneOf": [
+ AttributeInputTypeEnum.DATE_TIME.name,
+ AttributeInputTypeEnum.FILE.name,
+ ]
+ },
+ [],
+ ),
+ ],
+)
+def test_attributes_filter_by_input_type(
+ where, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+ variables = {"where": {"inputType": where}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"eq": AttributeEntityTypeEnum.PRODUCT_VARIANT.name}, [2]),
+ ({"eq": AttributeEntityTypeEnum.PRODUCT.name}, []),
+ (
+ {
+ "oneOf": [
+ AttributeEntityTypeEnum.PAGE.name,
+ AttributeEntityTypeEnum.PRODUCT_VARIANT.name,
+ ]
+ },
+ [1, 2],
+ ),
+ (
+ {
+ "oneOf": [
+ AttributeEntityTypeEnum.PRODUCT.name,
+ ]
+ },
+ [],
+ ),
+ ],
+)
+def test_attributes_filter_by_entity_type(
+ where,
+ indexes,
+ api_client,
+ color_attribute,
+ product_type_page_reference_attribute,
+ page_type_variant_reference_attribute,
+):
+ # given
+ attributes = [
+ color_attribute,
+ product_type_page_reference_attribute,
+ page_type_variant_reference_attribute,
+ ]
+ variables = {"where": {"entityType": where}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"eq": AttributeTypeEnum.PRODUCT_TYPE.name}, [0, 1]),
+ ({"eq": AttributeTypeEnum.PAGE_TYPE.name}, []),
+ (
+ {
+ "oneOf": [
+ AttributeTypeEnum.PRODUCT_TYPE.name,
+ AttributeTypeEnum.PAGE_TYPE.name,
+ ]
+ },
+ [0, 1],
+ ),
+ (
+ {
+ "oneOf": [
+ AttributeTypeEnum.PAGE_TYPE.name,
+ ]
+ },
+ [],
+ ),
+ ],
+)
+def test_attributes_filter_by_type(
+ where,
+ indexes,
+ api_client,
+ color_attribute,
+ product_type_page_reference_attribute,
+):
+ # given
+ attributes = [
+ color_attribute,
+ product_type_page_reference_attribute,
+ ]
+ variables = {"where": {"type": where}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"eq": MeasurementUnitsEnum.CM.name}, [1]),
+ ({"eq": MeasurementUnitsEnum.SQ_CM.name}, []),
+ (
+ {
+ "oneOf": [
+ MeasurementUnitsEnum.CM.name,
+ MeasurementUnitsEnum.M.name,
+ ]
+ },
+ [1, 2],
+ ),
+ (
+ {
+ "oneOf": [
+ MeasurementUnitsEnum.SQ_CM.name,
+ ]
+ },
+ [],
+ ),
+ ],
+)
+def test_attributes_filter_by_unit(
+ where,
+ indexes,
+ api_client,
+ color_attribute,
+ numeric_attribute,
+ date_attribute,
+):
+ # given
+ numeric_attribute_2 = Attribute.objects.create(
+ slug="length-2",
+ name="Length 2",
+ type=AttributeType.PRODUCT_TYPE,
+ input_type=AttributeInputType.NUMERIC,
+ unit=MeasurementUnits.M,
+ filterable_in_dashboard=True,
+ )
+ attributes = [
+ color_attribute,
+ numeric_attribute,
+ numeric_attribute_2,
+ date_attribute,
+ ]
+ variables = {"where": {"unit": where}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
[email protected]("value, indexes", [(True, [0, 1]), (False, [2])])
+def test_attributes_filter_by_value_required(
+ value, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+
+ color_attribute.value_required = True
+ date_attribute.value_required = True
+ rich_text_attribute.value_required = False
+
+ Attribute.objects.bulk_update(attributes, ["value_required"])
+
+ variables = {"where": {"valueRequired": value}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
[email protected]("value, indexes", [(True, [0, 1]), (False, [2])])
+def test_attributes_filter_by_visible_in_storefront(
+ value,
+ indexes,
+ staff_api_client,
+ color_attribute,
+ date_attribute,
+ rich_text_attribute,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+
+ color_attribute.visible_in_storefront = True
+ date_attribute.visible_in_storefront = True
+ rich_text_attribute.visible_in_storefront = False
+
+ Attribute.objects.bulk_update(attributes, ["visible_in_storefront"])
+
+ variables = {"where": {"visibleInStorefront": value}}
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
[email protected]("value, indexes", [(True, [0]), (False, [1, 2])])
+def test_attributes_filter_by_filterable_in_dashboard(
+ value, indexes, api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ attributes = [color_attribute, date_attribute, rich_text_attribute]
+
+ color_attribute.filterable_in_dashboard = True
+ date_attribute.filterable_in_dashboard = False
+ rich_text_attribute.filterable_in_dashboard = False
+
+ Attribute.objects.bulk_update(attributes, ["filterable_in_dashboard"])
+
+ variables = {"where": {"filterableInDashboard": value}}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+def test_attributes_filter_attributes_in_collection_not_visible_in_listings_by_customer(
+ user_api_client, product_list, weight_attribute, collection, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_collection_not_published_by_customer(
+ user_api_client, product_list, weight_attribute, collection, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_attributes_filter_in_collection_not_published_by_staff_with_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_collection_not_published_by_staff_without_manage_products(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ collection,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+
+
+def test_attributes_filter_in_collection_not_published_by_app_with_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_collection_not_published_by_app_without_manage_products(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ collection,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+
+
+def test_attributes_filter_attributes_in_collection_invalid_collection_id(
+ user_api_client, product_list, weight_attribute, collection, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ variables = {
+ "where": {
+ "inCollection": "xnd",
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ message_error = (
+ '{"in_collection": [{"message": "Invalid ID specified.", "code": ""}]}'
+ )
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == message_error
+ assert content["data"]["attributes"] is None
+
+
+def test_attributes_filter_attributes_in_collection_object_with_given_id_does_not_exist(
+ user_api_client, product_list, weight_attribute, collection, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ variables = {
+ "where": {
+ "inCollection": graphene.Node.to_global_id("Product", -1),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["attributes"]["edges"] == []
+
+
+def test_attributes_filter_in_category_not_visible_in_listings_by_customer(
+ user_api_client, product_list, weight_attribute, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_attributes_filter_in_category_not_visible_in_listings_by_staff_with_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_category_not_in_listings_by_staff_without_manage_products(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1 # product not listed will not count
+
+
+def test_attributes_filter_in_category_not_visible_in_listings_by_app_with_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_category_not_in_listings_by_app_without_manage_products(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1 # product not visible will not count
+
+
+def test_attributes_filter_in_category_not_published_by_customer(
+ user_api_client, product_list, weight_attribute, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_attributes_filter_in_category_not_published_by_staff_with_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_category_not_published_by_staff_without_manage_products(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+
+
+def test_attributes_filter_in_category_not_published_by_app_with_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count
+
+
+def test_attributes_filter_in_category_not_published_by_app_without_manage_products(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attributes = content["data"]["attributes"]["edges"]
+ assert len(attributes) == attribute_count - 1
+
+
+def test_attributes_filter_in_category_invalid_category_id(
+ user_api_client, product_list, weight_attribute, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ variables = {
+ "where": {
+ "inCategory": "xyz",
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ message_error = (
+ '{"in_category": [{"message": "Invalid ID specified.", "code": ""}]}'
+ )
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == message_error
+ assert content["data"]["attributes"] is None
+
+
+def test_attributes_filter_in_category_object_with_given_id_does_not_exist(
+ user_api_client, product_list, weight_attribute, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ variables = {
+ "where": {
+ "inCategory": graphene.Node.to_global_id("Product", -1),
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["attributes"]["edges"] == []
+
+
+def test_attributes_filter_and_where_both_used(api_client, product_type_attribute_list):
+ # given
+ query = """
+ query($where: AttributeWhereInput!, $filter: AttributeFilterInput!) {
+ attributes(first: 10, where: $where, filter: $filter) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+ """
+ ids = [
+ graphene.Node.to_global_id("Attribute", attribute.pk)
+ for attribute in product_type_attribute_list[:2]
+ ]
+ variables = {
+ "where": {"AND": [{"ids": ids}]},
+ "filter": {"filterableInDashboard": True},
+ }
+
+ # when
+ response = api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ message_error = "Only one filtering argument (filter or where) can be specified."
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == message_error
+ assert content["data"]["attributes"] is None
+
+
+ "where, field_name",
+ [
+ ({"name": {"eq": "Text", "oneOf": ["Color", "Text"]}}, "name"),
+ ({"slug": {"eq": "text", "oneOf": ["color", "text"]}}, "slug"),
+ (
+ {
+ "inputType": {
+ "eq": AttributeInputTypeEnum.DATE.name,
+ "oneOf": [
+ AttributeInputTypeEnum.RICH_TEXT.name,
+ AttributeInputTypeEnum.DATE_TIME.name,
+ ],
+ }
+ },
+ "input_type",
+ ),
+ (
+ {
+ "entityType": {
+ "eq": AttributeEntityTypeEnum.PAGE.name,
+ "oneOf": [
+ AttributeEntityTypeEnum.PAGE.name,
+ AttributeEntityTypeEnum.PRODUCT_VARIANT.name,
+ ],
+ }
+ },
+ "entity_type",
+ ),
+ (
+ {
+ "type": {
+ "eq": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "oneOf": [
+ AttributeTypeEnum.PAGE_TYPE.name,
+ AttributeTypeEnum.PRODUCT_TYPE.name,
+ ],
+ }
+ },
+ "type",
+ ),
+ (
+ {
+ "unit": {
+ "eq": MeasurementUnitsEnum.M.name,
+ "oneOf": [
+ MeasurementUnitsEnum.CM.name,
+ MeasurementUnitsEnum.SQ_CM.name,
+ ],
+ }
+ },
+ "unit",
+ ),
+ ],
+)
+def test_attributes_filter_invalid_input(
+ where,
+ field_name,
+ api_client,
+ color_attribute,
+ numeric_attribute,
+ date_attribute,
+):
+ # given
+ variables = {"where": where}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ message_error = "Only one option can be specified."
+ assert len(content["errors"]) == 1
+ message = json.loads(content["errors"][0]["message"])
+ assert message[field_name][0]["message"] == message_error
+ assert content["data"]["attributes"] is None
+
+
+ "where",
+ [
+ # {"name": {"eq": "Text"}, "NOT": {"slug": {"eq": "test"}}},
+ {"name": {"eq": "Text"}, "AND": [{"slug": {"eq": "test"}}]},
+ {"name": {"eq": "Text"}, "OR": [{"slug": {"eq": "test"}}]},
+ {"AND": [{"name": {"eq": "Text"}}], "OR": [{"slug": {"eq": "test"}}]},
+ # {"AND": [{"name": {"eq": "Text"}}], "NOT": {"slug": {"eq": "test"}}},
+ # {"OR": [{"name": {"eq": "Text"}}], "NOT": {"slug": {"eq": "test"}}},
+ # {"NOT": {"slug": {"eq": "test"}, "AND": [{"name": {"eq": "Text"}}]}},
+ {"OR": [{"slug": {"eq": "test"}, "AND": [{"name": {"eq": "Text"}}]}]},
+ {"AND": [{"slug": {"eq": "test"}, "OR": [{"name": {"eq": "Text"}}]}]},
+ ],
+)
+def test_attributes_where_operator_invalid_input_data(where, api_client):
+ # given
+ variables = {"where": where}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ message_error = "Cannot mix operators with other filter inputs."
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == message_error
+ assert content["data"]["attributes"] is None
+
+
+def test_attributes_where_with_and_operator(
+ api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ variables = {
+ "where": {
+ "AND": [
+ {"type": {"eq": AttributeTypeEnum.PRODUCT_TYPE.name}},
+ {"inputType": {"eq": AttributeInputTypeEnum.DATE.name}},
+ ]
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == 1
+ assert nodes[0]["node"]["slug"] == date_attribute.slug
+
+
+# def test_attributes_where_with_not_operator(
+# api_client, color_attribute, date_attribute, rich_text_attribute
+# ):
+# # given
+# variables = {
+# "where": {
+# "NOT": {
+# "inputType": {"eq": AttributeInputTypeEnum.RICH_TEXT.name},
+# }
+# }
+# }
+
+# # when
+# response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+# # then
+# data = get_graphql_content(response)
+# nodes = data["data"]["attributes"]["edges"]
+# assert len(nodes) == 2
+# assert {node["node"]["slug"] for node in nodes} == {
+# color_attribute.slug,
+# date_attribute.slug,
+# }
+
+
+# def test_attributes_where_with_not_operator_nested_query(
+# api_client, color_attribute, date_attribute, rich_text_attribute
+# ):
+# # given
+# variables = {
+# "where": {
+# "NOT": {
+# "OR": [
+# {"inputType": {"eq": AttributeInputTypeEnum.DATE.name}},
+# {"name": {"eq": "Color"}},
+# ]
+# }
+# }
+# }
+
+# # when
+# response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+# # then
+# data = get_graphql_content(response)
+# nodes = data["data"]["attributes"]["edges"]
+# assert len(nodes) == 1
+# assert nodes[0]["node"]["slug"] == rich_text_attribute.slug
+
+
+def test_attributes_where_with_or_operator(
+ api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ variables = {
+ "where": {
+ "OR": [
+ {"inputType": {"eq": AttributeInputTypeEnum.DATE.name}},
+ {"name": {"eq": "Color"}},
+ ]
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == 2
+ assert {node["node"]["slug"] for node in nodes} == {
+ color_attribute.slug,
+ date_attribute.slug,
+ }
+
+
+def test_attributes_where_with_multiple_nested_operators(
+ api_client, color_attribute, date_attribute, rich_text_attribute
+):
+ # given
+ variables = {
+ "where": {
+ "AND": [
+ {
+ "OR": [
+ {
+ "AND": [
+ {
+ "AND": [
+ {
+ "AND": [
+ {
+ "AND": [
+ {
+ "AND": [
+ {
+ "slug": {
+ "oneOf": [
+ "color",
+ "text",
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "OR": [
+ {"inputType": {"eq": AttributeInputTypeEnum.DATE.name}},
+ {"name": {"eq": "Color"}},
+ ]
+ },
+ ]
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == 1
+ assert nodes[0]["node"]["slug"] == color_attribute.slug
+
+
+ATTRIBUTES_SEARCH_QUERY = """
+ query($search: String, $channel: String) {
+ attributes(first: 10, search: $search, channel: $channel) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+ "search, indexes",
+ [
+ ("color", [0]),
+ ("size", [1]),
+ ("date", [2, 3]),
+ ("ABCD", []),
+ (None, [0, 1, 2, 3]),
+ ("", [0, 1, 2, 3]),
+ ],
+)
+def test_search_attributes_on_root_level(
+ search,
+ indexes,
+ api_client,
+ color_attribute,
+ size_attribute,
+ date_attribute,
+ date_time_attribute,
+):
+ # given
+ attributes = [color_attribute, size_attribute, date_attribute, date_time_attribute]
+ variables = {"search": search}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTES_SEARCH_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["attributes"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {attributes[index].slug for index in indexes}
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 224c2fbd40..0bf45c0f5e 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -198,6 +198,7 @@ class Attribute(ModelObjectType[models.Attribute]):
f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.name}."
),
required=True,
+ deprecation_reason=DEPRECATED_IN_3X_FIELD,
)
filterable_in_dashboard = graphene.Boolean(
description=(
@@ -218,6 +219,7 @@ class Attribute(ModelObjectType[models.Attribute]):
f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.name}."
),
required=True,
+ deprecation_reason=DEPRECATED_IN_3X_FIELD,
)
storefront_search_position = graphene.Int(
description=(
@@ -228,6 +230,7 @@ class Attribute(ModelObjectType[models.Attribute]):
f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.name}."
),
required=True,
+ deprecation_reason=DEPRECATED_IN_3X_FIELD,
)
translation = TranslationField(AttributeTranslation, type_name="attribute")
with_choices = graphene.Boolean(
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index 6bdedea391..10734f7311 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -38,6 +38,8 @@ ConnectionArguments = Dict[str, Any]
EPSILON = Decimal("0.000001")
FILTERS_NAME = "_FILTERS_NAME"
FILTERSET_CLASS = "_FILTERSET_CLASS"
+WHERE_NAME = "_WHERE_NAME"
+WHERE_FILTERSET_CLASS = "_WHERE_FILTERSET_CLASS"
def to_global_cursor(values):
@@ -447,40 +449,164 @@ def slice_connection_iterable(
def filter_connection_queryset(iterable, args, request=None, root=None):
- filterset_class = args[FILTERSET_CLASS]
- filter_field_name = args[FILTERS_NAME]
- filter_input = args.get(filter_field_name)
+ update_args_with_channel(args, root)
+ if args.get(args[FILTERS_NAME]) and args.get(args[WHERE_NAME]):
+ raise GraphQLError(
+ "Only one filtering argument (filter or where) can be specified."
+ )
+
+ if filter_input := args.get(args[FILTERS_NAME]):
+ filterset_class = args[FILTERSET_CLASS]
+ filter_func = filter_qs
+ else:
+ filter_input = args.get(args[WHERE_NAME])
+ filterset_class = args[WHERE_FILTERSET_CLASS]
+ filter_func = where_filter_qs
if filter_input:
- # for nested filters get channel from ChannelContext object
- if "channel" not in args and root and hasattr(root, "channel_slug"):
- args["channel"] = root.channel_slug
+ return filter_func(iterable, args, filterset_class, filter_input, request)
- try:
- filter_channel = str(filter_input["channel"])
- except (NoDefaultChannel, ChannelNotDefined, GraphQLError, KeyError):
- filter_channel = None
- filter_input["channel"] = (
- args.get("channel")
- or filter_channel
- or get_default_channel_slug_or_graphql_error()
+ return iterable
+
+
+def update_args_with_channel(args, root):
+ # for nested filters get channel from ChannelContext object
+ if "channel" not in args and root and hasattr(root, "channel_slug"):
+ args["channel"] = root.channel_slug
+
+
+def filter_qs(iterable, args, filterset_class, filter_input, request):
+ try:
+ filter_channel = str(filter_input["channel"])
+ except (NoDefaultChannel, ChannelNotDefined, GraphQLError, KeyError):
+ filter_channel = None
+ filter_input["channel"] = (
+ args.get("channel")
+ or filter_channel
+ or get_default_channel_slug_or_graphql_error()
+ )
+
+ if isinstance(iterable, ChannelQsContext):
+ queryset = iterable.qs
+ else:
+ queryset = iterable
+
+ filterset = filterset_class(filter_input, queryset=queryset, request=request)
+ if not filterset.is_valid():
+ raise GraphQLError(json.dumps(filterset.errors.get_json_data()))
+
+ if isinstance(iterable, ChannelQsContext):
+ return ChannelQsContext(filterset.qs, iterable.channel_slug)
+
+ return filterset.qs
+
+
+def where_filter_qs(iterable, args, filterset_class, filter_input, request):
+ """Filter queryset by complex statement provided in where argument.
+
+ Handle `AND`, `OR`, `NOT` operators, as well as flat filter input.
+ The returned queryset contains data that fulfill all specified statements.
+ The condition can be nested, the operators cannot be mixed in
+ a single filter object.
+ Multiple operators can be provided with use of nesting. See the example below.
+
+ E.g.
+ {
+ 'where': {
+ 'AND': [
+ {'input_type': {'one_of': ['rich-text', 'dropdown']}}
+ {
+ 'OR': [
+ {'name': {'eq': 'Author'}},
+ {'slug': {'one_of': ['a-rich', 'abv']}}
+ ]
+ },
+ {
+ 'NOT': {'name': {'eq': 'ABV'}}
+ }
+ ],
+ }
+ }
+ For above example the returned instances will fulfill following conditions:
+ - it must be a type o 'rich-text'or 'dropdown'
+ - the name must equal to 'Author' or the slug must be equal to `a-rich` or `abv`
+ - the name cannot be equal to `ABV`
+ """
+ # when any operator appear there cannot be any more data in filter input
+ if contains_filter_operator(filter_input) and len(filter_input) > 1:
+ raise GraphQLError("Cannot mix operators with other filter inputs.")
+
+ and_filter_input = filter_input.pop("AND", None)
+ or_filter_input = filter_input.pop("OR", None)
+ # TODO: needs optimization
+ # not_filter_input = filter_input.pop("NOT", None)
+
+ if isinstance(iterable, ChannelQsContext):
+ queryset = iterable.qs
+ else:
+ queryset = iterable
+
+ if and_filter_input:
+ queryset = _handle_add_filter_input(
+ and_filter_input, queryset, args, filterset_class, request
)
- if isinstance(iterable, ChannelQsContext):
- queryset = iterable.qs
- else:
- queryset = iterable
+ if or_filter_input:
+ queryset = _handle_or_filter_input(
+ or_filter_input, queryset, args, filterset_class, request
+ )
- filterset = filterset_class(filter_input, queryset=queryset, request=request)
- if not filterset.is_valid():
- raise GraphQLError(json.dumps(filterset.errors.get_json_data()))
+ # TODO: needs optimization
+ # if not_filter_input:
+ # queryset = _handle_not_filter_input(
+ # not_filter_input, queryset, args, filterset_class, request
+ # )
- if isinstance(iterable, ChannelQsContext):
- return ChannelQsContext(filterset.qs, iterable.channel_slug)
+ if filter_input:
+ queryset &= filter_qs(iterable, args, filterset_class, filter_input, request)
- return filterset.qs
+ return queryset
- return iterable
+
+def contains_filter_operator(input: Dict[str, Union[dict, str]]):
+ return any([operator in input for operator in ["AND", "OR", "NOT"]])
+
+
+def _handle_add_filter_input(filter_input, queryset, args, filterset_class, request):
+ for input in filter_input:
+ if contains_filter_operator(input):
+ # when the input contains the operator run the where_filter_qs method again
+ # to properly handle the nested input
+ queryset &= where_filter_qs(queryset, args, filterset_class, input, request)
+ else:
+ queryset &= filter_qs(queryset, args, filterset_class, input, request)
+ return queryset
+
+
+def _handle_or_filter_input(filter_input, queryset, args, filterset_class, request):
+ # for the OR operator the instanced that passed one of specified condition are
+ # found, then the return queryset is joined with the use of AND operator with
+ # main qs
+ qs = queryset.model.objects.none()
+ for input in filter_input:
+ if contains_filter_operator(input):
+ # when the input contains the operator run the where_filter_qs method again
+ # to properly handle the nested input
+ qs |= where_filter_qs(queryset, args, filterset_class, input, request)
+ else:
+ qs |= filter_qs(queryset, args, filterset_class, input, request)
+ queryset &= qs
+ return queryset
+
+
+# TODO: needs optimization
+# def _handle_not_filter_input(filter_input, queryset, args, filterset_class, request):
+# if contains_filter_operator(filter_input):
+# qs = where_filter_qs(queryset, args, filterset_class, filter_input, request)
+# else:
+# qs = filter_qs(queryset, args, filterset_class, filter_input, request)
+# queryset = queryset.exclude(Exists(qs.filter(id=OuterRef("id"))))
+# return queryset
class NonNullConnection(Connection):
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.py
index f8984e4e16..08209c68fd 100644
--- a/saleor/graphql/core/fields.py
+++ b/saleor/graphql/core/fields.py
@@ -8,7 +8,7 @@ from graphql import GraphQLError
from ...permission.utils import message_one_of_permissions_required
from ..decorators import one_of_permissions_required
-from .connection import FILTERS_NAME, FILTERSET_CLASS
+from .connection import FILTERS_NAME, FILTERSET_CLASS, WHERE_FILTERSET_CLASS, WHERE_NAME
class PermissionsField(graphene.Field):
@@ -92,6 +92,13 @@ class FilterConnectionField(ConnectionField):
self.filterset_class = None
if self.filter_input:
self.filterset_class = self.filter_input.filterset_class
+
+ self.where_field_name = kwargs.get("where_field_name", "where")
+ self.where_input = kwargs.get(self.where_field_name)
+ self.where_filterset_class = None
+ if self.where_input:
+ self.where_filterset_class = self.where_input.filterset_class
+
super().__init__(type_, *args, **kwargs)
def get_resolver(self, parent_resolver):
@@ -101,6 +108,8 @@ class FilterConnectionField(ConnectionField):
def new_resolver(obj, info, **kwargs):
kwargs[FILTERSET_CLASS] = self.filterset_class
kwargs[FILTERS_NAME] = self.filter_field_name
+ kwargs[WHERE_FILTERSET_CLASS] = self.where_filterset_class
+ kwargs[WHERE_NAME] = self.where_field_name
return wrapped_resolver(obj, info, **kwargs)
return new_resolver
diff --git a/saleor/graphql/core/filters.py b/saleor/graphql/core/filters.py
index 4e552fe8e9..00bc3cafc0 100644
--- a/saleor/graphql/core/filters.py
+++ b/saleor/graphql/core/filters.py
@@ -59,6 +59,21 @@ class ObjectTypeFilter(django_filters.Filter):
super().__init__(*args, **kwargs)
+class DefaultOperationField(Field):
+ def validate(self, value):
+ if value and len(value) > 1:
+ raise ValidationError("Only one option can be specified.", code="invalid")
+ return super().validate(value)
+
+
+class OperationObjectTypeFilter(django_filters.Filter):
+ field_class = DefaultOperationField
+
+ def __init__(self, input_class, *args, **kwargs):
+ self.input_class = input_class
+ super().__init__(*args, **kwargs)
+
+
def filter_created_at(qs, _, value):
return filter_range_field(qs, "created_at", value)
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index dc7bdcb91e..c06f27d7e9 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -60,7 +60,14 @@ from .common import (
Weight,
)
from .event import SubscriptionObjectType
-from .filter_input import ChannelFilterInputObjectType, FilterInputObjectType
+from .filter_input import (
+ ChannelFilterInputObjectType,
+ DateFilterInput,
+ DateTimeFilterInput,
+ FilterInputObjectType,
+ IntFilterInput,
+ StringFilterInput,
+)
from .model import ModelObjectType
from .money import VAT, Money, MoneyRange, ReducedRate, TaxedMoney, TaxedMoneyRange
from .sort_input import ChannelSortInputObjectType, SortInputObjectType
@@ -139,4 +146,8 @@ __all__ = [
"ChannelSortInputObjectType",
"Upload",
"TYPES_WITH_DOUBLE_ID_AVAILABLE",
+ "StringFilterInput",
+ "IntFilterInput",
+ "DateFilterInput",
+ "DateTimeFilterInput",
]
diff --git a/saleor/graphql/core/types/converter.py b/saleor/graphql/core/types/converter.py
index f08a1138aa..1c9251a334 100644
--- a/saleor/graphql/core/types/converter.py
+++ b/saleor/graphql/core/types/converter.py
@@ -12,6 +12,7 @@ from ..filters import (
GlobalIDMultipleChoiceField,
ListObjectTypeFilter,
ObjectTypeFilter,
+ OperationObjectTypeFilter,
)
from .common import NonNullList
@@ -51,6 +52,7 @@ def convert_form_field_to_float(field):
)
+@convert_form_field.register(OperationObjectTypeFilter)
@convert_form_field.register(ObjectTypeFilter)
@convert_form_field.register(EnumFilter)
def convert_convert_enum(field):
diff --git a/saleor/graphql/core/types/filter_input.py b/saleor/graphql/core/types/filter_input.py
index 785441e915..722c68af3f 100644
--- a/saleor/graphql/core/types/filter_input.py
+++ b/saleor/graphql/core/types/filter_input.py
@@ -1,13 +1,17 @@
import itertools
+import graphene
from django.db import models
from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS, BaseFilterSet
from graphene import Argument, InputField, InputObjectType, String
from graphene.types.inputobjecttype import InputObjectTypeOptions
from graphene.types.utils import yank_fields_from_attrs
-from ..descriptions import DEPRECATED_IN_3X_INPUT
+from ..descriptions import ADDED_IN_311, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE
from ..filters import GlobalIDFilter, GlobalIDMultipleChoiceFilter
+from ..scalars import Date
+from . import NonNullList
+from .common import DateRangeInput, DateTimeRangeInput, IntRangeInput
from .converter import convert_form_field
GLOBAL_ID_FILTERS = {
@@ -35,7 +39,7 @@ def get_filterset_class(filterset_class=None):
class FilterInputObjectType(InputObjectType):
- """Class for storing and serving django-filtres as graphQL input.
+ """Class for storing and serving django-filters as graphQL input.
FilterSet class which inherits from django-filters.FilterSet should be
provided with using fitlerset_class argument.
@@ -99,3 +103,114 @@ class ChannelFilterInputObjectType(FilterInputObjectType):
class Meta:
abstract = True
+
+
+class WhereInputObjectType(FilterInputObjectType):
+ """Class for storing and serving django-filters with additional operators input.
+
+ FilterSet class which inherits from django-filters.FilterSet should be
+ provided with using fitlerset_class argument.
+
+ AND, OR, and NOT class type fields are automatically added to available input
+ fields, allowing to create complex filter statements.
+ """
+
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def __init_subclass_with_meta__(cls, _meta=None, **options):
+ super().__init_subclass_with_meta__(_meta=_meta, **options)
+ cls._meta.fields.update(
+ {
+ "AND": graphene.Field(
+ NonNullList(
+ cls,
+ ),
+ description="List of conditions that must be met.",
+ ),
+ "OR": graphene.Field(
+ NonNullList(
+ cls,
+ ),
+ description=(
+ "A list of conditions of which at least one must be met."
+ ),
+ ),
+ # TODO: needs optimization
+ # "NOT": graphene.Field(
+ # cls, description="A condition that cannot be met."
+ # ),
+ }
+ )
+
+
+class FilterInputDescriptions:
+ EQ = "The value equal to."
+ ONE_OF = "The value included in."
+ RANGE = "The value in range."
+
+
+class StringFilterInput(graphene.InputObjectType):
+ eq = graphene.String(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ graphene.String,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+ class Meta:
+ description = (
+ "Define the filtering options for string fields."
+ + ADDED_IN_311
+ + PREVIEW_FEATURE
+ )
+
+
+class IntFilterInput(graphene.InputObjectType):
+ eq = graphene.Int(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ graphene.Int, description=FilterInputDescriptions.ONE_OF, required=False
+ )
+ range = IntRangeInput(description=FilterInputDescriptions.RANGE, required=False)
+
+ class Meta:
+ description = (
+ "Define the filtering options for integer fields."
+ + ADDED_IN_311
+ + PREVIEW_FEATURE
+ )
+
+
+class DateFilterInput(graphene.InputObjectType):
+ eq = Date(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ Date, description=FilterInputDescriptions.ONE_OF, required=False
+ )
+ range = DateRangeInput(description=FilterInputDescriptions.RANGE, required=False)
+
+ class Meta:
+ description = (
+ "Define the filtering options for date fields."
+ + ADDED_IN_311
+ + PREVIEW_FEATURE
+ )
+
+
+class DateTimeFilterInput(graphene.InputObjectType):
+ eq = graphene.DateTime(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ graphene.DateTime,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+ range = DateTimeRangeInput(
+ description=FilterInputDescriptions.RANGE, required=False
+ )
+
+ class Meta:
+ description = (
+ "Define the filtering options for date time fields."
+ + ADDED_IN_311
+ + PREVIEW_FEATURE
+ )
diff --git a/saleor/graphql/page/tests/queries/test_page_type.py b/saleor/graphql/page/tests/queries/test_page_type.py
index ecf766c6bd..8b10afb62f 100644
--- a/saleor/graphql/page/tests/queries/test_page_type.py
+++ b/saleor/graphql/page/tests/queries/test_page_type.py
@@ -7,7 +7,9 @@ from ....tests.utils import (
)
PAGE_TYPE_QUERY = """
- query PageType($id: ID!, $filters: AttributeFilterInput) {
+ query PageType(
+ $id: ID!, $filters: AttributeFilterInput, $where: AttributeWhereInput
+ ) {
pageType(id: $id) {
id
name
@@ -16,7 +18,7 @@ PAGE_TYPE_QUERY = """
attributes {
slug
}
- availableAttributes(first: 10, filter: $filters) {
+ availableAttributes(first: 10, filter: $filters, where: $where) {
edges {
node {
slug
@@ -170,6 +172,40 @@ def test_page_type_query_filter_unassigned_attributes(
assert available_attributes[0]["node"]["slug"] == expected_attribute.slug
+def test_page_type_query_where_filter_unassigned_attributes(
+ staff_api_client,
+ page_type,
+ permission_manage_pages,
+ page_type_attribute_list,
+ color_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_pages)
+
+ expected_attribute = page_type_attribute_list[0]
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "where": {"name": {"eq": expected_attribute.name}},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ page_type_data = content["data"]["pageType"]
+
+ assert page_type_data["slug"] == page_type.slug
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ attr.slug for attr in page_type.page_attributes.all()
+ }
+ available_attributes = page_type_data["availableAttributes"]["edges"]
+ assert len(available_attributes) == 1
+ assert available_attributes[0]["node"]["slug"] == expected_attribute.slug
+
+
def test_page_type_query_no_pages(
staff_api_client,
page_type,
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index b2cb6f485e..88aea9928c 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -5,7 +5,7 @@ import graphene
from ...attribute import models as attribute_models
from ...page import models
from ...permission.enums import PagePermissions
-from ..attribute.filters import AttributeFilterInput
+from ..attribute.filters import AttributeFilterInput, AttributeWhereInput
from ..attribute.types import Attribute, AttributeCountableConnection, SelectedAttribute
from ..core import ResolveInfo
from ..core.connection import (
@@ -40,6 +40,7 @@ class PageType(ModelObjectType[models.PageType]):
available_attributes = FilterConnectionField(
AttributeCountableConnection,
filter=AttributeFilterInput(),
+ where=AttributeWhereInput(),
description="Attributes that can be assigned to the page type.",
permissions=[
PagePermissions.MANAGE_PAGES,
diff --git a/saleor/graphql/product/tests/queries/test_product_type_query.py b/saleor/graphql/product/tests/queries/test_product_type_query.py
index 2dfb4f25e0..95dd962d1d 100644
--- a/saleor/graphql/product/tests/queries/test_product_type_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_type_query.py
@@ -325,9 +325,11 @@ def test_product_type_query_only_assigned_variant_selections_value_set(
QUERY_AVAILABLE_ATTRIBUTES = """
- query($productTypeId:ID!, $filters: AttributeFilterInput) {
+ query(
+ $productTypeId:ID!, $filters: AttributeFilterInput, $where: AttributeWhereInput
+ ) {
productType(id: $productTypeId) {
- availableAttributes(first: 10, filter: $filters) {
+ availableAttributes(first: 10, filter: $filters, where: $where) {
edges {
node {
id
@@ -443,6 +445,31 @@ def test_product_type_filter_unassigned_attributes(
assert attribute_id == str(expected_attribute.pk)
+def test_product_type_where_filter_unassigned_attributes(
+ staff_api_client, permission_manage_products, product_type_attribute_list
+):
+ expected_attribute = product_type_attribute_list[0]
+ query = QUERY_AVAILABLE_ATTRIBUTES
+ product_type = ProductType.objects.create(
+ name="Empty Type", kind=ProductTypeKind.NORMAL
+ )
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ where = {"name": {"eq": expected_attribute.name}}
+
+ found_attributes = get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ {"productTypeId": product_type_id, "where": where},
+ permissions=[permission_manage_products],
+ )
+ )["data"]["productType"]["availableAttributes"]["edges"]
+
+ assert len(found_attributes) == 1
+
+ _, attribute_id = graphene.Node.from_global_id(found_attributes[0]["node"]["id"])
+ assert attribute_id == str(expected_attribute.pk)
+
+
QUERY_PRODUCT_TYPE = """
query ($id: ID!){
productType(
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index b63129aed5..88802bc5dc 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -31,7 +31,7 @@ from ....thumbnail.utils import get_image_or_proxy_url, get_thumbnail_size
from ....warehouse.reservations import is_reservation_enabled
from ...account import types as account_types
from ...account.enums import CountryCodeEnum
-from ...attribute.filters import AttributeFilterInput
+from ...attribute.filters import AttributeFilterInput, AttributeWhereInput
from ...attribute.resolvers import resolve_attributes
from ...attribute.types import (
AssignedVariantAttribute,
@@ -895,6 +895,7 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):
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}",
+ deprecation_reason=f"{DEPRECATED_IN_3X_FIELD} Use top-level `variant` query.",
)
variants = NonNullList(
ProductVariant,
@@ -1612,6 +1613,7 @@ class ProductType(ModelObjectType[models.ProductType]):
available_attributes = FilterConnectionField(
AttributeCountableConnection,
filter=AttributeFilterInput(),
+ where=AttributeWhereInput(),
description="List of attributes which can be assigned to this product type.",
permissions=[ProductPermissions.MANAGE_PRODUCTS],
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index af31493e8d..ff12b99b6b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1170,6 +1170,24 @@ type Query {
"""Filtering options for attributes."""
filter: AttributeFilterInput
+ """
+ Filtering options for attributes.
+
+ Added in Saleor 3.11.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ where: AttributeWhereInput
+
+ """
+ Search attributes.
+
+ Added in Saleor 3.11.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ search: String
+
"""Sorting options for attributes."""
sortBy: AttributeSortingInput
@@ -4928,7 +4946,7 @@ type Product implements Node & ObjectWithMetadata {
"""SKU of the variant."""
sku: String
- ): ProductVariant
+ ): ProductVariant @deprecated(reason: "This field will be removed in Saleor 4.0. Use top-level `variant` query.")
"""
List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.
@@ -5098,6 +5116,7 @@ type ProductType implements Node & ObjectWithMetadata {
"""
availableAttributes(
filter: AttributeFilterInput
+ where: AttributeWhereInput
"""Return the elements in the list that come before the specified cursor."""
before: String
@@ -5314,7 +5333,7 @@ type Attribute implements Node & ObjectWithMetadata {
"""
Whether the attribute can be filtered in storefront. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.
"""
- filterableInStorefront: Boolean!
+ filterableInStorefront: Boolean! @deprecated(reason: "This field will be removed in Saleor 4.0.")
"""
Whether the attribute can be filtered in dashboard. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.
@@ -5324,12 +5343,12 @@ type Attribute implements Node & ObjectWithMetadata {
"""
Whether the attribute can be displayed in the admin product list. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.
"""
- availableInGrid: Boolean!
+ availableInGrid: Boolean! @deprecated(reason: "This field will be removed in Saleor 4.0.")
"""
The position of the attribute in the storefront navigation (0 by default). Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.
"""
- storefrontSearchPosition: Int!
+ storefrontSearchPosition: Int! @deprecated(reason: "This field will be removed in Saleor 4.0.")
"""Returns translated attribute fields for the given language code."""
translation(
@@ -5660,6 +5679,83 @@ input MetadataFilter {
value: String
}
+"""
+Where filtering options.
+
+Added in Saleor 3.11.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+input AttributeWhereInput {
+ valueRequired: Boolean
+ visibleInStorefront: Boolean
+ filterableInDashboard: Boolean
+ metadata: [MetadataFilter!]
+ ids: [ID!]
+ name: StringFilterInput
+ slug: StringFilterInput
+ withChoices: Boolean
+ inputType: AttributeInputTypeEnumFilterInput
+ entityType: AttributeEntityTypeEnumFilterInput
+ type: AttributeTypeEnumFilterInput
+ unit: MeasurementUnitsEnumFilterInput
+ inCollection: ID
+ inCategory: ID
+
+ """List of conditions that must be met."""
+ AND: [AttributeWhereInput!]
+
+ """A list of conditions of which at least one must be met."""
+ OR: [AttributeWhereInput!]
+}
+
+"""
+Define the filtering options for string fields.
+
+Added in Saleor 3.11.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+input StringFilterInput {
+ """The value equal to."""
+ eq: String
+
+ """The value included in."""
+ oneOf: [String!]
+}
+
+input AttributeInputTypeEnumFilterInput {
+ """The value equal to."""
+ eq: AttributeInputTypeEnum
+
+ """The value included in."""
+ oneOf: [AttributeInputTypeEnum!]
+}
+
+input AttributeEntityTypeEnumFilterInput {
+ """The value equal to."""
+ eq: AttributeEntityTypeEnum
+
+ """The value included in."""
+ oneOf: [AttributeEntityTypeEnum!]
+}
+
+input AttributeTypeEnumFilterInput {
+ """The value equal to."""
+ eq: AttributeTypeEnum
+
+ """The value included in."""
+ oneOf: [AttributeTypeEnum!]
+}
+
+input MeasurementUnitsEnumFilterInput {
+ """The value equal to."""
+ eq: MeasurementUnitsEnum
+
+ """The value included in."""
+ oneOf: [MeasurementUnitsEnum!]
+}
+
"""
Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront.
"""
@@ -7309,6 +7405,7 @@ type PageType implements Node & ObjectWithMetadata {
"""
availableAttributes(
filter: AttributeFilterInput
+ where: AttributeWhereInput
"""Return the elements in the list that come before the specified cursor."""
before: String
@@ -22451,7 +22548,11 @@ input AttributeCreateInput {
"""Whether the attribute should be visible or not in storefront."""
visibleInStorefront: Boolean
- """Whether the attribute can be filtered in storefront."""
+ """
+ Whether the attribute can be filtered in storefront.
+
+ DEPRECATED: this field will be removed in Saleor 4.0.
+ """
filterableInStorefront: Boolean
"""Whether the attribute can be filtered in dashboard."""
@@ -22459,10 +22560,16 @@ input AttributeCreateInput {
"""
The position of the attribute in the storefront navigation (0 by default).
+
+ DEPRECATED: this field will be removed in Saleor 4.0.
"""
storefrontSearchPosition: Int
- """Whether the attribute can be displayed in the admin product list."""
+ """
+ Whether the attribute can be displayed in the admin product list.
+
+ DEPRECATED: this field will be removed in Saleor 4.0.
+ """
availableInGrid: Boolean
"""
@@ -22559,7 +22666,11 @@ input AttributeUpdateInput {
"""Whether the attribute should be visible or not in storefront."""
visibleInStorefront: Boolean
- """Whether the attribute can be filtered in storefront."""
+ """
+ Whether the attribute can be filtered in storefront.
+
+ DEPRECATED: this field will be removed in Saleor 4.0.
+ """
filterableInStorefront: Boolean
"""Whether the attribute can be filtered in dashboard."""
@@ -22567,10 +22678,16 @@ input AttributeUpdateInput {
"""
The position of the attribute in the storefront navigation (0 by default).
+
+ DEPRECATED: this field will be removed in Saleor 4.0.
"""
storefrontSearchPosition: Int
- """Whether the attribute can be displayed in the admin product list."""
+ """
+ Whether the attribute can be displayed in the admin product list.
+
+ DEPRECATED: this field will be removed in Saleor 4.0.
+ """
availableInGrid: Boolean
"""
diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.py
index c0a09a092f..19aa271ba1 100644
--- a/saleor/graphql/utils/filters.py
+++ b/saleor/graphql/utils/filters.py
@@ -1,7 +1,12 @@
+from typing import TYPE_CHECKING, Dict, List, Union
+
from django.utils import timezone
from ..core.enums import ReportingPeriod
+if TYPE_CHECKING:
+ from django.db.models import QuerySet
+
def reporting_period_to_date(period):
now = timezone.now()
@@ -40,3 +45,15 @@ def filter_by_id(object_type):
return qs.filter(id__in=obj_pks)
return inner
+
+
+def filter_by_string_field(
+ qs: "QuerySet", field: str, value: Dict[str, Union[str, List[str]]]
+):
+ eq = value.get("eq")
+ one_of = value.get("one_of")
+ if eq:
+ qs = qs.filter(**{field: eq})
+ if one_of:
+ qs = qs.filter(**{f"{field}__in": one_of})
+ return qs