Skip to content

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

Where filters for products (#12960)

Piotr Zabieglik8b3b87a0a6b4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05613783bf..dc3cdfe3c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,6 +37,7 @@ All notable, unreleased changes to this project will be documented in this file.
- [Preview] Add `ORDER_BULK_CREATED` event, which is sent for successfully imported orders - #12536 by @zedzior
- Add `brand` optional field with brand data (initially logo image) to `Manifest`, `AppInstallation` and `App` - #12361 by @przlada
- [Preview] Add `AttributeBulkTranslate` and `AttributeValueBulkTranslate` mutation - #12965 by @SzymJ
+- [Preview] Add `where` and `search` filtering option on `products` query - #12960 by @zedzior
### Saleor Apps
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index 72297859f5..95667a63bd 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -546,7 +546,7 @@ def where_filter_qs(iterable, args, filterset_class, filter_input, request):
queryset = iterable
if and_filter_input:
- queryset = _handle_add_filter_input(
+ queryset = _handle_and_filter_input(
and_filter_input, queryset, args, filterset_class, request
)
@@ -562,7 +562,17 @@ def where_filter_qs(iterable, args, filterset_class, filter_input, request):
# )
if filter_input:
- queryset &= filter_qs(iterable, args, filterset_class, filter_input, request)
+ qs_to_combine = filter_qs(
+ iterable, args, filterset_class, filter_input, request
+ )
+ if isinstance(qs_to_combine, ChannelQsContext):
+ queryset &= qs_to_combine.qs
+
+ else:
+ queryset &= qs_to_combine
+
+ if isinstance(iterable, ChannelQsContext):
+ return ChannelQsContext(queryset, iterable.channel_slug)
return queryset
@@ -571,7 +581,7 @@ 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):
+def _handle_and_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
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index b307c30938..0cd62bebac 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -25,6 +25,7 @@ from ...core.doc_category import (
DOC_CATEGORY_USERS,
DOC_CATEGORY_WEBHOOKS,
)
+from ...core.scalars import Decimal
from ..descriptions import (
ADDED_IN_36,
ADDED_IN_312,
@@ -778,6 +779,11 @@ class PriceRangeInput(graphene.InputObjectType):
lte = graphene.Float(description="Price less than or equal to.", required=False)
+class DecimalRangeInput(graphene.InputObjectType):
+ gte = Decimal(description="Decimal value greater than or equal to.", required=False)
+ lte = Decimal(description="Decimal value less than or equal to.", required=False)
+
+
class DateRangeInput(graphene.InputObjectType):
gte = Date(description="Start date.", required=False)
lte = Date(description="End date.", required=False)
diff --git a/saleor/graphql/core/types/filter_input.py b/saleor/graphql/core/types/filter_input.py
index 3e01f9ac02..4abaae1475 100644
--- a/saleor/graphql/core/types/filter_input.py
+++ b/saleor/graphql/core/types/filter_input.py
@@ -7,12 +7,18 @@ from graphene import Argument, InputField, String
from graphene.types.inputobjecttype import InputObjectTypeOptions
from graphene.types.utils import yank_fields_from_attrs
-from ..descriptions import ADDED_IN_311, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE
+from ...core.scalars import Decimal
+from ..descriptions import (
+ ADDED_IN_311,
+ ADDED_IN_314,
+ DEPRECATED_IN_3X_INPUT,
+ PREVIEW_FEATURE,
+)
from ..filters import GlobalIDFilter, GlobalIDMultipleChoiceFilter
from ..scalars import Date
from . import NonNullList
from .base import BaseInputObjectType
-from .common import DateRangeInput, DateTimeRangeInput, IntRangeInput
+from .common import DateRangeInput, DateTimeRangeInput, DecimalRangeInput, IntRangeInput
from .converter import convert_form_field
GLOBAL_ID_FILTERS = {
@@ -183,6 +189,21 @@ class IntFilterInput(graphene.InputObjectType):
)
+class DecimalFilterInput(graphene.InputObjectType):
+ eq = Decimal(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ Decimal, description=FilterInputDescriptions.ONE_OF, required=False
+ )
+ range = DecimalRangeInput(description=FilterInputDescriptions.RANGE, required=False)
+
+ class Meta:
+ description = (
+ "Define the filtering options for decimal fields."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ )
+
+
class DateFilterInput(graphene.InputObjectType):
eq = Date(description=FilterInputDescriptions.EQ, required=False)
one_of = NonNullList(
@@ -215,3 +236,19 @@ class DateTimeFilterInput(graphene.InputObjectType):
+ ADDED_IN_311
+ PREVIEW_FEATURE
)
+
+
+class GlobalIDFilterInput(graphene.InputObjectType):
+ eq = graphene.ID(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ graphene.ID,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+ class Meta:
+ description = (
+ "Define the filtering options for foreign key fields."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ )
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index b07c232710..3a44721601 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -44,6 +44,7 @@ from ..core.filters import (
ListObjectTypeFilter,
MetadataFilterBase,
ObjectTypeFilter,
+ OperationObjectTypeFilter,
filter_slug_list,
)
from ..core.types import (
@@ -54,9 +55,21 @@ from ..core.types import (
IntRangeInput,
NonNullList,
PriceRangeInput,
+ StringFilterInput,
+)
+from ..core.types.filter_input import (
+ DecimalFilterInput,
+ GlobalIDFilterInput,
+ WhereInputObjectType,
)
from ..utils import resolve_global_ids_to_primary_keys
-from ..utils.filters import filter_by_id, filter_range_field
+from ..utils.filters import (
+ filter_by_id,
+ filter_by_string_field,
+ filter_range_field,
+ filter_where_by_id_field,
+ filter_where_by_numeric_field,
+)
from ..warehouse import types as warehouse_types
from . import types as product_types
from .enums import (
@@ -797,6 +810,212 @@ class ProductFilter(MetadataFilterBase):
return _filter_stock_availability(queryset, name, value, channel_slug)
+class ProductWhere(MetadataFilterBase):
+ ids = GlobalIDMultipleChoiceFilter(method=filter_by_id("Product"))
+ name = OperationObjectTypeFilter(
+ input_class=StringFilterInput,
+ method="filter_product_name",
+ help_text="Filter by product name.",
+ )
+ slug = OperationObjectTypeFilter(
+ input_class=StringFilterInput,
+ method="filter_product_slug",
+ help_text="Filter by product slug.",
+ )
+ product_type = OperationObjectTypeFilter(
+ input_class=GlobalIDFilterInput,
+ method="filter_product_type",
+ help_text="Filter by product type.",
+ )
+ category = OperationObjectTypeFilter(
+ input_class=GlobalIDFilterInput,
+ method="filter_category",
+ help_text="Filter by product category.",
+ )
+ collection = OperationObjectTypeFilter(
+ input_class=GlobalIDFilterInput,
+ method="filter_collection",
+ help_text="Filter by collection.",
+ )
+ is_available = django_filters.BooleanFilter(
+ method="filter_is_available", help_text="Filter by availability for purchase."
+ )
+ is_published = django_filters.BooleanFilter(
+ method="filter_is_published", help_text="Filter by public visibility."
+ )
+ is_visible_in_listing = django_filters.BooleanFilter(
+ method="filter_is_listed", help_text="Filter by visibility on the channel."
+ )
+ published_from = ObjectTypeFilter(
+ input_class=graphene.DateTime,
+ method="filter_published_from",
+ help_text="Filter by the publication date.",
+ )
+ available_from = ObjectTypeFilter(
+ input_class=graphene.DateTime,
+ method="filter_available_from",
+ help_text="Filter by the date of availability for purchase.",
+ )
+ has_category = django_filters.BooleanFilter(
+ method=filter_has_category,
+ help_text="Filter by product with category assigned.",
+ )
+ price = OperationObjectTypeFilter(
+ input_class=DecimalFilterInput,
+ method="filter_variant_price",
+ help_text="Filter by product variant price.",
+ )
+ minimal_price = OperationObjectTypeFilter(
+ input_class=DecimalFilterInput,
+ method="filter_minimal_price",
+ field_name="minimal_price_amount",
+ help_text="Filter by the lowest variant price after discounts.",
+ )
+ attributes = ListObjectTypeFilter(
+ input_class="saleor.graphql.attribute.types.AttributeInput",
+ method="filter_attributes",
+ help_text="Filter by attributes associated with the product.",
+ )
+ stock_availability = EnumFilter(
+ input_class=StockAvailability,
+ method="filter_stock_availability",
+ help_text="Filter by variants having specific stock status.",
+ )
+ stocks = ObjectTypeFilter(
+ input_class=ProductStockFilterInput,
+ method=filter_stocks,
+ help_text="Filter by stock of the product variant.",
+ )
+ gift_card = django_filters.BooleanFilter(
+ method=filter_gift_card,
+ help_text="Filter on whether product is a gift card or not.",
+ )
+ has_preordered_variants = django_filters.BooleanFilter(
+ method=filter_has_preordered_variants,
+ help_text="Filter by product with preordered variants.",
+ )
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput,
+ method=filter_updated_at_range,
+ help_text="Filter by when was the most recent update.",
+ )
+
+ class Meta:
+ model = Product
+ fields = []
+
+ @staticmethod
+ def filter_product_name(qs, _, value):
+ return filter_by_string_field(qs, "name", value)
+
+ @staticmethod
+ def filter_product_slug(qs, _, value):
+ return filter_by_string_field(qs, "slug", value)
+
+ @staticmethod
+ def filter_product_type(qs, _, value):
+ return filter_where_by_id_field(qs, "product_type", value, "ProductType")
+
+ @staticmethod
+ def filter_category(qs, _, value):
+ return filter_where_by_id_field(qs, "category", value, "Category")
+
+ @staticmethod
+ def filter_collection(qs, _, value):
+ collection_products_qs = CollectionProduct.objects.filter()
+ collection_products_qs = filter_where_by_id_field(
+ collection_products_qs, "collection_id", value, "Collection"
+ )
+ collection_products = collection_products_qs.values("product_id")
+ return qs.filter(Exists(collection_products.filter(product_id=OuterRef("pk"))))
+
+ def filter_is_available(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_products_is_available(
+ queryset,
+ name,
+ value,
+ channel_slug,
+ )
+
+ def filter_is_published(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_products_is_published(
+ queryset,
+ name,
+ value,
+ channel_slug,
+ )
+
+ def filter_is_listed(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_products_visible_in_listing(
+ queryset,
+ name,
+ value,
+ channel_slug,
+ )
+
+ def filter_published_from(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_products_channel_field_from_date(
+ queryset,
+ name,
+ value,
+ channel_slug,
+ "published_at",
+ )
+
+ def filter_available_from(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_products_channel_field_from_date(
+ queryset,
+ name,
+ value,
+ channel_slug,
+ "available_for_purchase_at",
+ )
+
+ @staticmethod
+ def filter_has_category(qs, _, value):
+ return qs.filter(category__isnull=not value)
+
+ def filter_variant_price(self, qs, _, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ channel_id = Channel.objects.filter(slug=channel_slug).values("pk")
+ variant_listing = ProductVariantChannelListing.objects.filter(
+ Exists(channel_id.filter(pk=OuterRef("channel_id")))
+ )
+ variant_listing = filter_where_by_numeric_field(
+ variant_listing, "price_amount", value
+ )
+ variant_listing = variant_listing.values("variant_id")
+ variants = ProductVariant.objects.filter(
+ Exists(variant_listing.filter(variant_id=OuterRef("pk")))
+ ).values("product_id")
+ return qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))
+
+ def filter_minimal_price(self, qs, _, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ channel = Channel.objects.filter(slug=channel_slug).first()
+ if not channel:
+ return qs
+ product_listing = ProductChannelListing.objects.filter(channel_id=channel.id)
+ product_listing = filter_where_by_numeric_field(
+ product_listing, "discounted_price_amount", value
+ )
+ product_listing = product_listing.values("product_id")
+ return qs.filter(Exists(product_listing.filter(product_id=OuterRef("pk"))))
+
+ @staticmethod
+ def filter_attributes(queryset, name, value):
+ return _filter_attributes(queryset, name, value)
+
+ def filter_stock_availability(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_stock_availability(queryset, name, value, channel_slug)
+
+
class ProductVariantFilter(MetadataFilterBase):
search = django_filters.CharFilter(method="product_variant_filter_search")
sku = ListObjectTypeFilter(input_class=graphene.String, method=filter_sku_list)
@@ -897,6 +1116,12 @@ class ProductFilterInput(ChannelFilterInputObjectType):
filterset_class = ProductFilter
+class ProductWhereInput(WhereInputObjectType):
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+ filterset_class = ProductWhere
+
+
class ProductVariantFilterInput(FilterInputObjectType):
class Meta:
doc_category = DOC_CATEGORY_PRODUCTS
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 953346c8c8..4d14e0cad0 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -6,11 +6,12 @@ from graphql import GraphQLError
from ...permission.enums import ProductPermissions
from ...permission.utils import has_one_of_permissions
from ...product.models import ALL_PRODUCTS_PERMISSIONS
-from ..channel import ChannelContext
+from ...product.search import search_products
+from ..channel import ChannelContext, ChannelQsContext
from ..channel.utils import get_default_channel_slug_or_graphql_error
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_314, PREVIEW_FEATURE
from ..core.doc_category import DOC_CATEGORY_PRODUCTS
from ..core.enums import ReportingPeriod
from ..core.fields import (
@@ -50,6 +51,7 @@ from .filters import (
ProductFilterInput,
ProductTypeFilterInput,
ProductVariantFilterInput,
+ ProductWhereInput,
)
from .mutations import (
CategoryCreate,
@@ -240,7 +242,11 @@ class ProductQueries(graphene.ObjectType):
products = FilterConnectionField(
ProductCountableConnection,
filter=ProductFilterInput(description="Filtering options for products."),
+ where=ProductWhereInput(
+ description="Where filtering options." + ADDED_IN_314 + PREVIEW_FEATURE
+ ),
sort_by=ProductOrder(description="Sort products."),
+ search=graphene.String(description="Search products." + ADDED_IN_314),
channel=graphene.String(
description="Slug of a channel for which the data should be returned."
),
@@ -428,7 +434,9 @@ class ProductQueries(graphene.ObjectType):
@staticmethod
@traced_resolver
- def resolve_products(_root, info: ResolveInfo, *, channel=None, **kwargs):
+ def resolve_products(
+ _root, info: ResolveInfo, *, channel=None, search=None, **kwargs
+ ):
if sort_field_from_kwargs(kwargs) == ProductOrderField.RANK:
# sort by RANK can be used only with search filter
if not search_string_in_kwargs(kwargs):
@@ -450,6 +458,10 @@ class ProductQueries(graphene.ObjectType):
if channel is None and not has_required_permissions:
channel = get_default_channel_slug_or_graphql_error()
qs = resolve_products(info, requestor, channel_slug=channel)
+ if search:
+ qs = ChannelQsContext(
+ qs=search_products(qs.qs, search), channel_slug=channel
+ )
kwargs["channel"] = channel
qs = filter_connection_queryset(qs, kwargs)
return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.py
index a97056b811..90d0d98f69 100644
--- a/saleor/graphql/product/tests/queries/test_products_query.py
+++ b/saleor/graphql/product/tests/queries/test_products_query.py
@@ -2,6 +2,7 @@ from datetime import datetime
from decimal import Decimal
import graphene
+import pytest
from django.utils.dateparse import parse_datetime
from .....core.postgres import FlatConcatSearchVector
@@ -1134,3 +1135,45 @@ def test_products_with_variants_query_as_app(
attrs = response_product["node"]["attributes"]
assert len(attrs) == 1
assert attrs[0]["attribute"]["id"] == attribute_id
+
+
+PRODUCT_SEARCH_QUERY = """
+ query($search: String, $channel: String) {
+ products(first: 10, search: $search, channel: $channel) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+ "search, indexes",
+ [
+ ("small", [2]),
+ ("big", [0, 1]),
+ ("product", [0, 1, 2]),
+ ("ABCD", []),
+ (None, [0, 1, 2]),
+ ("", [0, 1, 2]),
+ ],
+)
+def test_search_products_on_root_level(
+ search, indexes, api_client, product_list, channel_USD
+):
+ # given
+ variables = {"search": search, "channel": channel_USD.slug}
+
+ # when
+ response = api_client.post_graphql(PRODUCT_SEARCH_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_attrs = {node["node"]["slug"] for node in nodes}
+ assert returned_attrs == {product_list[index].slug for index in indexes}
diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_where.py b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
new file mode 100644
index 0000000000..2ed24e79e5
--- /dev/null
+++ b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
@@ -0,0 +1,1517 @@
+from datetime import timedelta
+
+import graphene
+import pytest
+from django.utils import timezone
+
+from .....attribute.models import Attribute, AttributeValue
+from .....attribute.utils import associate_attribute_values_to_instance
+from .....product import ProductTypeKind
+from .....product.models import Product, ProductChannelListing, ProductType
+from .....warehouse.models import Allocation, Reservation, Stock, Warehouse
+from ....tests.utils import get_graphql_content
+
+PRODUCTS_WHERE_QUERY = """
+ query($where: ProductWhereInput!, $channel: String) {
+ products(first: 10, where: $where, channel: $channel) {
+ edges {
+ node {
+ id
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_product_filter_by_ids(api_client, product_list, channel_USD):
+ # given
+ ids = [
+ graphene.Node.to_global_id("Product", product.pk)
+ for product in product_list[:2]
+ ]
+ variables = {"channel": channel_USD.slug, "where": {"ids": ids}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 2
+ returned_slugs = {node["node"]["slug"] for node in products}
+ assert returned_slugs == {
+ product_list[0].slug,
+ product_list[1].slug,
+ }
+
+
+ "where, indexes",
+ [
+ ({"eq": "Test product 1"}, [0]),
+ ({"eq": "Non-existing"}, []),
+ ({"oneOf": ["Test product 1", "Test product 2"]}, [0, 1]),
+ ({"oneOf": ["Test product 1", "Non-existing"]}, [0]),
+ ({"oneOf": ["Non-existing 1", "Non-existing 2"]}, []),
+ ],
+)
+def test_product_filter_by_name(where, indexes, api_client, product_list, channel_USD):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"name": where}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"eq": "test-product-a"}, [0]),
+ ({"eq": "non-existing"}, []),
+ ({"oneOf": ["test-product-a", "test-product-b"]}, [0, 1]),
+ ({"oneOf": ["test-product-a", "non-existing"]}, [0]),
+ ({"oneOf": ["non-existing-1", "non-existing-2"]}, []),
+ ],
+)
+def test_product_filter_by_slug(where, indexes, api_client, product_list, channel_USD):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"slug": where}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+def test_product_filter_by_product_types(
+ api_client, product_list, channel_USD, product_type_list
+):
+ # given
+ product_list[0].product_type = product_type_list[0]
+ product_list[1].product_type = product_type_list[1]
+ product_list[2].product_type = product_type_list[2]
+ Product.objects.bulk_update(product_list, ["product_type"])
+
+ type_ids = [
+ graphene.Node.to_global_id("ProductType", type.pk)
+ for type in product_type_list[:2]
+ ]
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"productType": {"oneOf": type_ids}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 2
+ returned_slugs = {node["node"]["slug"] for node in products}
+ assert returned_slugs == {
+ product_list[0].slug,
+ product_list[1].slug,
+ }
+
+
+def test_product_filter_by_product_type(
+ api_client, product_list, channel_USD, product_type_list
+):
+ # given
+ product_list[0].product_type = product_type_list[0]
+ Product.objects.bulk_update(product_list, ["product_type"])
+
+ type_id = graphene.Node.to_global_id("ProductType", product_type_list[0].pk)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"productType": {"eq": type_id}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert product_list[0].slug == products[0]["node"]["slug"]
+
+
+def test_product_filter_by_categories(
+ api_client, product_list, channel_USD, category_list
+):
+ # given
+ product_list[0].category = category_list[0]
+ product_list[1].category = category_list[1]
+ product_list[2].category = category_list[2]
+ Product.objects.bulk_update(product_list, ["category"])
+
+ category_ids = [
+ graphene.Node.to_global_id("Category", category.pk)
+ for category in category_list[:2]
+ ]
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"category": {"oneOf": category_ids}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 2
+ returned_slugs = {node["node"]["slug"] for node in products}
+ assert returned_slugs == {
+ product_list[0].slug,
+ product_list[1].slug,
+ }
+
+
+def test_product_filter_by_category(
+ api_client, product_list, channel_USD, category_list
+):
+ # given
+ product_list[1].category = category_list[1]
+ Product.objects.bulk_update(product_list, ["category"])
+
+ category_id = graphene.Node.to_global_id("Category", category_list[1].pk)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"category": {"eq": category_id}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert product_list[1].slug == products[0]["node"]["slug"]
+
+
+def test_product_filter_by_collections(
+ api_client, product_list, channel_USD, collection_list
+):
+ # given
+ collection_list[0].products.add(product_list[0])
+ collection_list[1].products.add(product_list[1])
+ collection_list[2].products.add(product_list[2])
+
+ collection_ids = [
+ graphene.Node.to_global_id("Collection", collection.pk)
+ for collection in collection_list[:2]
+ ]
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"collection": {"oneOf": collection_ids}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 2
+ returned_slugs = {node["node"]["slug"] for node in products}
+ assert returned_slugs == {product_list[0].slug, product_list[1].slug}
+
+
+def test_product_filter_by_collection(
+ api_client, product_list, channel_USD, collection_list
+):
+ # given
+ collection_list[1].products.add(product_list[1])
+ collection_id = graphene.Node.to_global_id("Collection", collection_list[1].pk)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"collection": {"eq": collection_id}},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert product_list[1].slug == products[0]["node"]["slug"]
+
+
+ "where, indexes",
+ [({"isAvailable": True}, [0, 2]), ({"isAvailable": False}, [1])],
+)
+def test_product_filter_by_is_available(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ ProductChannelListing.objects.filter(
+ product=product_list[1], channel=channel_USD
+ ).update(available_for_purchase_at=timezone.now() + timedelta(days=1))
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [({"isPublished": True}, [0, 2]), ({"isPublished": False}, [])],
+)
+def test_product_filter_by_is_published(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ ProductChannelListing.objects.filter(
+ product=product_list[1], channel=channel_USD
+ ).update(is_published=False)
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [({"isVisibleInListing": True}, [0, 2]), ({"isVisibleInListing": False}, [])],
+)
+def test_product_filter_by_is_visible_in_listing(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ ProductChannelListing.objects.filter(
+ product=product_list[1], channel=channel_USD
+ ).update(visible_in_listings=False)
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [({"hasCategory": True}, [0, 2]), ({"hasCategory": False}, [1])],
+)
+def test_product_filter_by_has_category(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ product_list[1].category = None
+ product_list[1].save(update_fields=["category"])
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+def test_product_filter_by_published_from(api_client, product_list, channel_USD):
+ # given
+ timestamp = timezone.now()
+ ProductChannelListing.objects.filter(
+ product__in=product_list, channel=channel_USD
+ ).update(published_at=timestamp + timedelta(days=1))
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).update(published_at=timestamp - timedelta(days=1))
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"publishedFrom": timestamp},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert product_list[0].slug == products[0]["node"]["slug"]
+
+
+def test_product_filter_by_available_from(api_client, product_list, channel_USD):
+ # given
+ timestamp = timezone.now()
+ ProductChannelListing.objects.filter(
+ product__in=product_list, channel=channel_USD
+ ).update(available_for_purchase_at=timestamp - timedelta(days=1))
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).update(available_for_purchase_at=timestamp + timedelta(days=1))
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"availableFrom": timestamp},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert product_list[1].slug == products[0]["node"]["slug"]
+ assert product_list[2].slug == products[1]["node"]["slug"]
+
+
+ "where, indexes",
+ [
+ ({"price": {"range": {"gte": 0, "lte": 50}}}, [0, 1, 2]),
+ ({"price": {"range": {"gte": 10, "lte": 20}}}, [0, 1]),
+ ({"price": {"range": {"gte": 15}}}, [1, 2]),
+ ({"price": {"range": {"lte": 15}}}, [0]),
+ ({"price": {"range": {"gte": 9.9999, "lte": 19.9999}}}, [0]),
+ ({"price": {"eq": 20}}, [1]),
+ ({"price": {"oneOf": [20, 30, 50]}}, [1, 2]),
+ ],
+)
+def test_product_filter_by_variant_price(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+ "where, indexes",
+ [
+ ({"minimalPrice": {"range": {"gte": 0, "lte": 50}}}, [0, 1, 2]),
+ ({"minimalPrice": {"range": {"gte": 10, "lte": 20}}}, [0, 1]),
+ ({"minimalPrice": {"range": {"gte": 15}}}, [1, 2]),
+ ({"minimalPrice": {"range": {"lte": 15}}}, [0]),
+ ({"minimalPrice": {"range": {"gte": 9.9999, "lte": 19.9999}}}, [0]),
+ ({"minimalPrice": {"eq": 20}}, [1]),
+ ({"minimalPrice": {"oneOf": [20, 30, 50]}}, [1, 2]),
+ ],
+)
+def test_product_filter_by_minimal_price(
+ where, indexes, api_client, product_list, channel_USD
+):
+ # given
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+def test_products_filter_by_attributes(
+ api_client,
+ product_list,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ kind=ProductTypeKind.NORMAL,
+ )
+ attribute = Attribute.objects.create(slug="new_attr", name="Attr")
+ attribute.product_types.add(product_type)
+ attr_value = AttributeValue.objects.create(
+ attribute=attribute, name="First", slug="first"
+ )
+ product = product_list[0]
+ product.product_type = product_type
+ product.save()
+ associate_attribute_values_to_instance(product, attribute, attr_value)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [{"slug": attribute.slug, "values": [attr_value.slug]}],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == product_id
+ assert products[0]["node"]["name"] == product.name
+
+
+ "values_range, indexes",
+ [
+ ({"lte": 8}, [1, 2]),
+ ({"gte": 0, "lte": 8}, [1, 2]),
+ ({"gte": 7, "lte": 8}, []),
+ ({"gte": 5}, [0, 1, 2]),
+ ({"gte": 8, "lte": 10}, [0]),
+ ({"gte": 12}, [0]),
+ ({"gte": 20}, []),
+ ({"gte": 20, "lte": 8}, []),
+ ({"gte": 5, "lte": 5}, [1, 2]),
+ ],
+)
+def test_products_filter_by_numeric_attributes(
+ values_range,
+ indexes,
+ api_client,
+ product_list,
+ numeric_attribute,
+ channel_USD,
+):
+ # given
+ product_list[0].product_type.product_attributes.add(numeric_attribute)
+ associate_attribute_values_to_instance(
+ product_list[0], numeric_attribute, *numeric_attribute.values.all()
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ numeric_attribute.product_types.add(product_type)
+
+ product_list[1].product_type = product_type
+ attr_value = AttributeValue.objects.create(
+ attribute=numeric_attribute, name="5", slug="5"
+ )
+ associate_attribute_values_to_instance(
+ product_list[1], numeric_attribute, attr_value
+ )
+
+ attr_value = AttributeValue.objects.create(
+ attribute=numeric_attribute, name="5", slug="5_X"
+ )
+ product_list[2].product_type = product_type
+ associate_attribute_values_to_instance(
+ product_list[2], numeric_attribute, attr_value
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {"slug": numeric_attribute.slug, "valuesRange": values_range}
+ ]
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
[email protected]("filter_value, indexes", [(False, [0, 1]), (True, [0])])
+def test_products_filter_by_boolean_attributes(
+ filter_value,
+ indexes,
+ api_client,
+ product_list,
+ boolean_attribute,
+ channel_USD,
+):
+ # given
+ product_list[0].product_type.product_attributes.add(boolean_attribute)
+ associate_attribute_values_to_instance(
+ product_list[0],
+ boolean_attribute,
+ boolean_attribute.values.get(boolean=filter_value),
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ boolean_attribute.product_types.add(product_type)
+
+ product_list[1].product_type = product_type
+ associate_attribute_values_to_instance(
+ product_list[1], boolean_attribute, boolean_attribute.values.get(boolean=False)
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [{"slug": boolean_attribute.slug, "boolean": filter_value}]
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+def test_products_filter_by_attributes_values_and_range(
+ api_client,
+ product_list,
+ category,
+ numeric_attribute,
+ channel_USD,
+):
+ # given
+ product_attr = product_list[0].attributes.first()
+ attr_value_1 = product_attr.values.first()
+ product_list[0].product_type.product_attributes.add(numeric_attribute)
+ associate_attribute_values_to_instance(
+ product_list[0], numeric_attribute, *numeric_attribute.values.all()
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ kind=ProductTypeKind.NORMAL,
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ numeric_attribute.product_types.add(product_type)
+
+ product_list[1].product_type = product_type
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=numeric_attribute, name="1.2", slug="1_2"
+ )
+ associate_attribute_values_to_instance(
+ product_list[1], numeric_attribute, attr_value_2
+ )
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {"slug": numeric_attribute.slug, "valuesRange": {"gte": 2}},
+ {"slug": attr_value_1.attribute.slug, "values": [attr_value_1.slug]},
+ ]
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product_list[0].pk
+ )
+ assert products[0]["node"]["slug"] == product_list[0].slug
+
+
+def test_products_filter_by_swatch_attributes(
+ api_client,
+ product_list,
+ swatch_attribute,
+ channel_USD,
+):
+ # given
+ product_list[0].product_type.product_attributes.add(swatch_attribute)
+ associate_attribute_values_to_instance(
+ product_list[0], swatch_attribute, *swatch_attribute.values.all()
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ swatch_attribute.product_types.add(product_type)
+
+ product_list[1].product_type = product_type
+ attr_value = AttributeValue.objects.create(
+ attribute=swatch_attribute, name="Dark", slug="dark"
+ )
+ associate_attribute_values_to_instance(
+ product_list[1], swatch_attribute, attr_value
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [{"slug": swatch_attribute.slug, "values": [attr_value.slug]}]
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert products[0]["node"]["slug"] == product_list[1].slug
+
+
+def test_products_filter_by_date_range_date_attributes(
+ api_client,
+ product_list,
+ date_attribute,
+ channel_USD,
+):
+ """Ensure both products will be returned when filtering attributes by date range,
+ products with the same date attribute value."""
+
+ # given
+ product_type = product_list[0].product_type
+ date_value = timezone.now()
+ product_type.product_attributes.add(date_attribute)
+ attr_value_1 = AttributeValue.objects.create(
+ attribute=date_attribute, name="First", slug="first", date_time=date_value
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=date_attribute, name="Second", slug="second", date_time=date_value
+ )
+ attr_value_3 = AttributeValue.objects.create(
+ attribute=date_attribute,
+ name="Third",
+ slug="third",
+ date_time=date_value - timedelta(days=1),
+ )
+
+ associate_attribute_values_to_instance(
+ product_list[0], date_attribute, attr_value_1
+ )
+ associate_attribute_values_to_instance(
+ product_list[1], date_attribute, attr_value_2
+ )
+ associate_attribute_values_to_instance(
+ product_list[2], date_attribute, attr_value_3
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {
+ "slug": date_attribute.slug,
+ "date": {"gte": date_value.date(), "lte": date_value.date()},
+ }
+ ],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert {node["node"]["id"] for node in products} == {
+ graphene.Node.to_global_id("Product", instance.id)
+ for instance in product_list[:2]
+ }
+
+
+def test_products_filter_by_date_range_date_variant_attributes(
+ api_client,
+ product_list,
+ date_attribute,
+ channel_USD,
+):
+ """Ensure both products will be returned when filtering attributes by date range,
+ variants with the same date attribute value."""
+
+ # given
+ product_type = product_list[0].product_type
+ date_value = timezone.now()
+ product_type.variant_attributes.add(date_attribute)
+ attr_value_1 = AttributeValue.objects.create(
+ attribute=date_attribute,
+ name="First",
+ slug="first",
+ date_time=date_value - timedelta(days=1),
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=date_attribute, name="Second", slug="second", date_time=date_value
+ )
+ attr_value_3 = AttributeValue.objects.create(
+ attribute=date_attribute, name="Third", slug="third", date_time=date_value
+ )
+
+ associate_attribute_values_to_instance(
+ product_list[0].variants.first(), date_attribute, attr_value_1
+ )
+ associate_attribute_values_to_instance(
+ product_list[1].variants.first(), date_attribute, attr_value_2
+ )
+ associate_attribute_values_to_instance(
+ product_list[2].variants.first(), date_attribute, attr_value_3
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {
+ "slug": date_attribute.slug,
+ "date": {"gte": date_value.date(), "lte": date_value.date()},
+ }
+ ],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert {node["node"]["id"] for node in products} == {
+ graphene.Node.to_global_id("Product", instance.id)
+ for instance in product_list[1:]
+ }
+
+
+def test_products_filter_by_date_range_date_time_attributes(
+ api_client,
+ product_list,
+ date_time_attribute,
+ channel_USD,
+):
+ """Ensure both products will be returned when filtering attributes by date time
+ range, products with the same date time attribute value."""
+
+ # given
+ product_type = product_list[0].product_type
+ date_value = timezone.now()
+ product_type.product_attributes.add(date_time_attribute)
+ attr_value_1 = AttributeValue.objects.create(
+ attribute=date_time_attribute, name="First", slug="first", date_time=date_value
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="Second",
+ slug="second",
+ date_time=date_value,
+ )
+ attr_value_3 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="Third",
+ slug="third",
+ date_time=date_value - timedelta(days=1),
+ )
+
+ associate_attribute_values_to_instance(
+ product_list[0], date_time_attribute, attr_value_1
+ )
+ associate_attribute_values_to_instance(
+ product_list[1], date_time_attribute, attr_value_2
+ )
+ associate_attribute_values_to_instance(
+ product_list[2], date_time_attribute, attr_value_3
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {
+ "slug": date_time_attribute.slug,
+ "date": {"gte": date_value.date(), "lte": date_value.date()},
+ }
+ ],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert {node["node"]["id"] for node in products} == {
+ graphene.Node.to_global_id("Product", instance.id)
+ for instance in product_list[:2]
+ }
+
+
+def test_products_filter_by_date_range_date_time_variant_attributes(
+ api_client,
+ product_list,
+ date_time_attribute,
+ channel_USD,
+):
+ """Ensure both products will be returned when filtering attributes by date time
+ range, variant and product with the same date time attribute value."""
+
+ # given
+ product_type = product_list[0].product_type
+ date_value = timezone.now()
+ product_type.variant_attributes.add(date_time_attribute)
+ attr_value_1 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="First",
+ slug="first",
+ date_time=date_value - timedelta(days=1),
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="Second",
+ slug="second",
+ date_time=date_value,
+ )
+ attr_value_3 = AttributeValue.objects.create(
+ attribute=date_time_attribute, name="Third", slug="third", date_time=date_value
+ )
+
+ associate_attribute_values_to_instance(
+ product_list[0].variants.first(), date_time_attribute, attr_value_1
+ )
+ associate_attribute_values_to_instance(
+ product_list[1].variants.first(), date_time_attribute, attr_value_2
+ )
+ associate_attribute_values_to_instance(
+ product_list[2].variants.first(), date_time_attribute, attr_value_3
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {
+ "slug": date_time_attribute.slug,
+ "date": {"gte": date_value.date(), "lte": date_value.date()},
+ }
+ ],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert {node["node"]["id"] for node in products} == {
+ graphene.Node.to_global_id("Product", instance.id)
+ for instance in product_list[1:]
+ }
+
+
+def test_products_filter_by_date_time_range_date_time_attributes(
+ api_client,
+ product_list,
+ date_time_attribute,
+ channel_USD,
+):
+ """Ensure both products will be returned when filtering by attributes by date range
+ variants with the same date attribute value."""
+
+ # given
+ product_type = product_list[0].product_type
+ date_value = timezone.now()
+ product_type.product_attributes.add(date_time_attribute)
+ product_type.variant_attributes.add(date_time_attribute)
+ attr_value_1 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="First",
+ slug="first",
+ date_time=date_value - timedelta(hours=2),
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="Second",
+ slug="second",
+ date_time=date_value + timedelta(hours=3),
+ )
+ attr_value_3 = AttributeValue.objects.create(
+ attribute=date_time_attribute,
+ name="Third",
+ slug="third",
+ date_time=date_value - timedelta(hours=6),
+ )
+
+ associate_attribute_values_to_instance(
+ product_list[0], date_time_attribute, attr_value_1
+ )
+ associate_attribute_values_to_instance(
+ product_list[1].variants.first(), date_time_attribute, attr_value_2
+ )
+ associate_attribute_values_to_instance(
+ product_list[2].variants.first(), date_time_attribute, attr_value_3
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [
+ {
+ "slug": date_time_attribute.slug,
+ "dateTime": {
+ "gte": date_value - timedelta(hours=4),
+ "lte": date_value + timedelta(hours=4),
+ },
+ }
+ ],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert {node["node"]["id"] for node in products} == {
+ graphene.Node.to_global_id("Product", instance.id)
+ for instance in product_list[:2]
+ }
+
+
+def test_products_filter_by_non_existing_attribute(
+ api_client, product_list, channel_USD
+):
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"attributes": [{"slug": "i-do-not-exist", "values": ["red"]}]},
+ }
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 0
+
+
+ "where, indexes",
+ [
+ ({"stockAvailability": "OUT_OF_STOCK"}, [0, 1, 2]),
+ ({"stockAvailability": "IN_STOCK"}, [3]),
+ ],
+)
+def test_products_filter_by_stock_availability(
+ where, indexes, api_client, product_list, order_line, channel_USD, product
+):
+ # given
+ for prod in product_list:
+ stock = prod.variants.first().stocks.first()
+ Allocation.objects.create(
+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity
+ )
+ product_list.append(product)
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": where,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ data = get_graphql_content(response)
+
+ # then
+ nodes = data["data"]["products"]["edges"]
+ assert len(nodes) == len(indexes)
+ returned_slugs = {node["node"]["slug"] for node in nodes}
+ assert returned_slugs == {product_list[index].slug for index in indexes}
+
+
+def test_products_filter_by_stock_availability_including_reservations(
+ api_client,
+ product_list,
+ order_line,
+ checkout_line,
+ channel_USD,
+ warehouse_JPY,
+ stock,
+):
+ # given
+ stocks = [product.variants.first().stocks.first() for product in product_list]
+ stock.quantity = 50
+ stock.product_variant = stocks[2].product_variant
+ stock.warehouse_id = warehouse_JPY.id
+ stocks[2].quantity = 50
+
+ Allocation.objects.create(
+ order_line=order_line, stock=stocks[0], quantity_allocated=50
+ )
+ Reservation.objects.bulk_create(
+ [
+ Reservation(
+ checkout_line=checkout_line,
+ stock=stocks[0],
+ quantity_reserved=50,
+ reserved_until=timezone.now() + timedelta(minutes=5),
+ ),
+ Reservation(
+ checkout_line=checkout_line,
+ stock=stocks[1],
+ quantity_reserved=100,
+ reserved_until=timezone.now() - timedelta(minutes=5),
+ ),
+ Reservation(
+ checkout_line=checkout_line,
+ stock=stocks[2],
+ quantity_reserved=50,
+ reserved_until=timezone.now() + timedelta(minutes=5),
+ ),
+ ]
+ )
+ variables = {
+ "where": {"stockAvailability": "OUT_OF_STOCK"},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product_list[0].id
+ )
+
+
+def test_products_filter_by_stock_availability_as_user(
+ user_api_client,
+ product_list,
+ order_line,
+ channel_USD,
+):
+ # given
+ for product in product_list:
+ stock = product.variants.first().stocks.first()
+ Allocation.objects.create(
+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity
+ )
+ product = product_list[0]
+ product.variants.first().channel_listings.filter(channel=channel_USD).update(
+ price_amount=None
+ )
+ variables = {
+ "where": {"stockAvailability": "OUT_OF_STOCK"},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ product_id = graphene.Node.to_global_id("Product", product_list[1].id)
+ second_product_id = graphene.Node.to_global_id("Product", product_list[2].id)
+
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 2
+ assert products[0]["node"]["id"] == product_id
+ assert products[0]["node"]["name"] == product_list[1].name
+ assert products[1]["node"]["id"] == second_product_id
+ assert products[1]["node"]["name"] == product_list[2].name
+
+
+def test_products_filter_by_stock_availability_channel_without_shipping_zones(
+ api_client,
+ product,
+ channel_USD,
+):
+ # given
+ channel_USD.shipping_zones.clear()
+ variables = {
+ "where": {"stockAvailability": "OUT_OF_STOCK"},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+ product_id = graphene.Node.to_global_id("Product", product.id)
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == product_id
+
+
+def test_products_filter_by_stock_availability_only_stock_in_cc_warehouse(
+ api_client,
+ product,
+ order_line,
+ channel_USD,
+ warehouse_for_cc,
+):
+ # given
+ variant = product.variants.first()
+ variant.stocks.all().delete()
+
+ Stock.objects.create(
+ warehouse=warehouse_for_cc, product_variant=variant, quantity=10
+ )
+
+ variables = {
+ "where": {"stockAvailability": "IN_STOCK"},
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product.id
+ )
+
+
+ "quantity_input, warehouse_indexes, count, indexes_of_products_in_result",
+ [
+ ({"lte": "80", "gte": "20"}, [1, 2], 1, [1]),
+ ({"lte": "120", "gte": "40"}, [1, 2], 1, [0]),
+ ({"gte": "10"}, [1], 1, [1]),
+ ({"gte": "110"}, [2], 0, []),
+ (None, [1], 1, [1]),
+ (None, [2], 2, [0, 1]),
+ ({"lte": "210", "gte": "70"}, [], 1, [0]),
+ ({"lte": "90"}, [], 1, [1]),
+ ({"lte": "90", "gte": "75"}, [], 0, []),
+ ],
+)
+def test_products_filter_by_stocks(
+ quantity_input,
+ warehouse_indexes,
+ count,
+ indexes_of_products_in_result,
+ api_client,
+ product_with_single_variant,
+ product_with_two_variants,
+ warehouse,
+ channel_USD,
+):
+ # given
+ product1 = product_with_single_variant
+ product2 = product_with_two_variants
+ products = [product1, product2]
+
+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ second_warehouse.slug = "second warehouse"
+ second_warehouse.pk = None
+ second_warehouse.save()
+
+ third_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ third_warehouse.slug = "third warehouse"
+ third_warehouse.pk = None
+ third_warehouse.save()
+
+ warehouses = [warehouse, second_warehouse, third_warehouse]
+ warehouse_pks = [
+ graphene.Node.to_global_id("Warehouse", warehouses[index].pk)
+ for index in warehouse_indexes
+ ]
+
+ Stock.objects.bulk_create(
+ [
+ Stock(
+ warehouse=third_warehouse,
+ product_variant=product1.variants.first(),
+ quantity=100,
+ ),
+ Stock(
+ warehouse=second_warehouse,
+ product_variant=product2.variants.first(),
+ quantity=10,
+ ),
+ Stock(
+ warehouse=third_warehouse,
+ product_variant=product2.variants.first(),
+ quantity=25,
+ ),
+ Stock(
+ warehouse=third_warehouse,
+ product_variant=product2.variants.last(),
+ quantity=30,
+ ),
+ ]
+ )
+
+ variables = {
+ "where": {
+ "stocks": {"quantity": quantity_input, "warehouseIds": warehouse_pks}
+ },
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products_data = content["data"]["products"]["edges"]
+ product_ids = {
+ graphene.Node.to_global_id("Product", products[index].pk)
+ for index in indexes_of_products_in_result
+ }
+
+ assert len(products_data) == count
+ assert {node["node"]["id"] for node in products_data} == product_ids
+
+
[email protected]("filter,index", [(False, 0), (True, 1)])
+def test_products_filter_by_gift_card(
+ filter,
+ index,
+ api_client,
+ product,
+ shippable_gift_card_product,
+ channel_USD,
+):
+ # given
+ variables = {"channel": channel_USD.slug, "where": {"giftCard": filter}}
+ product_list = [product, shippable_gift_card_product]
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product_list[index].pk
+ )
+
+
[email protected]("filter,index", [(False, 0), (True, 1)])
+def test_products_query_with_filter_has_preordered_variants(
+ filter,
+ index,
+ api_client,
+ preorder_variant_global_threshold,
+ product_without_shipping,
+ channel_USD,
+):
+ # given
+ product_list = [product_without_shipping, preorder_variant_global_threshold.product]
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {"hasPreorderedVariants": filter},
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ product_id = graphene.Node.to_global_id("Product", product_list[index].id)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == product_id
+
+
+def test_products_filter_by_has_preordered_variants_before_end_date(
+ api_client, preorder_variant_global_threshold, channel_USD
+):
+ # given
+ variant = preorder_variant_global_threshold
+ variant.preorder_end_date = timezone.now() + timedelta(days=3)
+ variant.save(update_fields=["preorder_end_date"])
+
+ product = preorder_variant_global_threshold.product
+ variables = {"channel": channel_USD.slug, "where": {"hasPreorderedVariants": True}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == product_id
+
+
+def test_products_filter_by_has_preordered_variants_after_end_date(
+ api_client, preorder_variant_global_threshold, channel_USD
+):
+ # given
+ variant = preorder_variant_global_threshold
+ variant.preorder_end_date = timezone.now() - timedelta(days=3)
+ variant.save(update_fields=["preorder_end_date"])
+
+ variables = {"channel": channel_USD.slug, "where": {"hasPreorderedVariants": True}}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 0
+
+
+def test_product_filter_by_updated_at(api_client, product_list, channel_USD):
+ # given
+ timestamp = timezone.now()
+ product_list[0].save()
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "updatedAt": {
+ "gte": timestamp,
+ "lte": timezone.now() + timedelta(days=1),
+ }
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 1
+ assert product_list[0].slug == products[0]["node"]["slug"]
+
+
+def test_product_filter_with_operators(
+ api_client, product_list, channel_USD, product_type_list
+):
+ # given
+ product_list[1].product_type = product_type_list[1]
+ Product.objects.bulk_update(product_list, ["product_type"])
+ type_ids = [
+ graphene.Node.to_global_id("ProductType", type.pk) for type in product_type_list
+ ]
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "OR": [
+ {"name": {"eq": "Test product 1"}},
+ {
+ "AND": [
+ {"productType": {"oneOf": type_ids}},
+ {"slug": {"eq": "test-product-b"}},
+ ]
+ },
+ ]
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ data = get_graphql_content(response)
+
+ # then
+ products = data["data"]["products"]["edges"]
+ assert len(products) == 2
+ assert product_list[0].slug == products[0]["node"]["slug"]
+ assert product_list[1].slug == products[1]["node"]["slug"]
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 5d6aad5291..ce30590368 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -13,7 +13,6 @@ from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quant
from ....order import OrderEvents, OrderStatus
from ....order.models import OrderEvent, OrderLine
from ....plugins.manager import get_plugins_manager
-from ....product import ProductTypeKind
from ....product.error_codes import ProductErrorCode
from ....product.models import (
Category,
@@ -30,29 +29,6 @@ from ....tests.utils import flush_post_commit_hooks
from ....thumbnail.models import Thumbnail
from ...tests.utils import get_graphql_content
-
-def category_list():
- category_1 = Category.objects.create(name="Category 1", slug="category-1")
- category_2 = Category.objects.create(name="Category 2", slug="category-2")
- category_3 = Category.objects.create(name="Category 3", slug="category-3")
- return category_1, category_2, category_3
-
-
-def product_type_list():
- product_type_1 = ProductType.objects.create(
- name="Type 1", slug="type-1", kind=ProductTypeKind.NORMAL
- )
- product_type_2 = ProductType.objects.create(
- name="Type 2", slug="type-2", kind=ProductTypeKind.NORMAL
- )
- product_type_3 = ProductType.objects.create(
- name="Type 3", slug="type-3", kind=ProductTypeKind.NORMAL
- )
- return product_type_1, product_type_2, product_type_3
-
-
MUTATION_CATEGORY_BULK_DELETE = """
mutation categoryBulkDelete($ids: [ID!]!) {
categoryBulkDelete(ids: $ids) {
diff --git a/saleor/graphql/product/tests/test_category_filtering.py b/saleor/graphql/product/tests/test_category_filtering.py
index 4f02f6e59e..ddd451d4f4 100644
--- a/saleor/graphql/product/tests/test_category_filtering.py
+++ b/saleor/graphql/product/tests/test_category_filtering.py
@@ -513,13 +513,22 @@ def test_category_filter_products_by_ids(
GET_SORTED_PRODUCTS_CATEGORY_QUERY = """
-query ($id: ID!, $channel: String, $filters: ProductFilterInput, $sortBy: ProductOrder){
+query (
+ $id: ID!,
+ $channel: String,
+ $filters: ProductFilterInput,
+ $sortBy: ProductOrder,
+ $where: ProductWhereInput,
+){
category(id: $id) {
id
- products(first: 10, channel: $channel, sortBy: $sortBy, filter: $filters) {
+ products(
+ first: 10, channel: $channel, sortBy: $sortBy, filter: $filters, where: $where
+ ) {
edges {
node {
id
+ slug
}
}
}
@@ -556,3 +565,34 @@ def test_category_sort_products_by_name(
graphene.Node.to_global_id("Product", product.pk)
for product in Product.objects.order_by("-name")
]
+
+
+def test_category_products_where_filter(
+ user_api_client,
+ category,
+ product_list,
+ channel_USD,
+):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ "where": {
+ "AND": [
+ {"slug": {"oneOf": ["test-product-a", "test-product-b"]}},
+ {"price": {"range": {"gte": 15}}},
+ ]
+ },
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ GET_SORTED_PRODUCTS_CATEGORY_QUERY,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["category"]["products"]["edges"]
+ assert len(products) == 1
+ assert products[0]["node"]["slug"] == "test-product-b"
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index 983e18abce..214376f814 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -293,9 +293,14 @@ def test_collections_query_as_staff_without_channel(
GET_FILTERED_PRODUCTS_COLLECTION_QUERY = """
-query CollectionProducts($id: ID!,$channel: String, $filters: ProductFilterInput) {
+query CollectionProducts(
+ $id: ID!,
+ $channel: String,
+ $filters: ProductFilterInput,
+ $where: ProductWhereInput,
+) {
collection(id: $id, channel: $channel) {
- products(first: 10, filter: $filters) {
+ products(first: 10, filter: $filters, where: $where) {
edges {
node {
id
@@ -430,6 +435,38 @@ def test_filter_collection_products_by_multiple_attributes(
]
+def test_filter_where_collection_products(
+ user_api_client, product_list, published_collection, channel_USD, channel_PLN
+):
+ # given
+ query = GET_FILTERED_PRODUCTS_COLLECTION_QUERY
+
+ for product in product_list:
+ published_collection.products.add(product)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
+ "where": {
+ "AND": [
+ {"slug": {"oneOf": ["test-product-a", "test-product-b"]}},
+ {"price": {"range": {"gte": 15}}},
+ ]
+ },
+ }
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ products = content["data"]["collection"]["products"]["edges"]
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product_list[1].pk
+ )
+
+
CREATE_COLLECTION_MUTATION = """
mutation createCollection(
$name: String!, $slug: String,
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index a96047b645..5ac4e2112b 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -18,7 +18,13 @@ from ...core.connection import (
create_connection_slice,
filter_connection_queryset,
)
-from ...core.descriptions import ADDED_IN_310, DEPRECATED_IN_3X_FIELD, RICH_CONTENT
+from ...core.descriptions import (
+ ADDED_IN_310,
+ ADDED_IN_314,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+ RICH_CONTENT,
+)
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.federation import federated_entity, resolve_federation_references
from ...core.fields import ConnectionField, FilterConnectionField, JSONString
@@ -32,7 +38,7 @@ from ..dataloaders import (
CategoryChildrenByCategoryIdLoader,
ThumbnailByCategoryIdSizeAndFormatLoader,
)
-from ..filters import ProductFilterInput
+from ..filters import ProductFilterInput, ProductWhereInput
from ..sorters import ProductOrder
from .products import ProductCountableConnection
@@ -62,6 +68,11 @@ class Category(ModelObjectType[models.Category]):
filter=ProductFilterInput(
description="Filtering options for products." + ADDED_IN_310
),
+ where=ProductWhereInput(
+ description="Filtering options for products."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ ),
sort_by=ProductOrder(description="Sort products." + ADDED_IN_310),
channel=graphene.String(
description="Slug of a channel for which the data should be returned."
diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.py
index 8f43cf976f..13fa672a92 100644
--- a/saleor/graphql/product/types/collections.py
+++ b/saleor/graphql/product/types/collections.py
@@ -19,7 +19,12 @@ from ...core.connection import (
create_connection_slice,
filter_connection_queryset,
)
-from ...core.descriptions import DEPRECATED_IN_3X_FIELD, RICH_CONTENT
+from ...core.descriptions import (
+ ADDED_IN_314,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+ RICH_CONTENT,
+)
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.federation import federated_entity
from ...core.fields import FilterConnectionField, JSONString, PermissionsField
@@ -33,7 +38,7 @@ from ..dataloaders import (
CollectionChannelListingByCollectionIdLoader,
ThumbnailByCollectionIdSizeAndFormatLoader,
)
-from ..filters import ProductFilterInput
+from ..filters import ProductFilterInput, ProductWhereInput
from ..sorters import ProductOrder
from .channels import CollectionChannelListing
from .products import ProductCountableConnection
@@ -64,6 +69,11 @@ class Collection(ChannelContextTypeWithMetadata[models.Collection]):
products = FilterConnectionField(
ProductCountableConnection,
filter=ProductFilterInput(description="Filtering options for products."),
+ where=ProductWhereInput(
+ description="Filtering options for products."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ ),
sort_by=ProductOrder(description="Sort products."),
description="List of products in this collection.",
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 00a287ce44..572f0d88ca 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -448,9 +448,25 @@ type Query {
"""Filtering options for products."""
filter: ProductFilterInput
+ """
+ Where filtering options.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ where: ProductWhereInput
+
"""Sort products."""
sortBy: ProductOrder
+ """
+ Search products.
+
+ Added in Saleor 3.14.
+ """
+ search: String
+
"""Slug of a channel for which the data should be returned."""
channel: String
@@ -6352,6 +6368,15 @@ type Category implements Node & ObjectWithMetadata @doc(category: "Products") {
"""
filter: ProductFilterInput
+ """
+ Filtering options for products.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ where: ProductWhereInput
+
"""
Sort products.
@@ -6562,6 +6587,123 @@ input PriceRangeInput {
lte: Float
}
+input ProductWhereInput @doc(category: "Products") {
+ metadata: [MetadataFilter!]
+ ids: [ID!]
+
+ """Filter by product name."""
+ name: StringFilterInput
+
+ """Filter by product slug."""
+ slug: StringFilterInput
+
+ """Filter by product type."""
+ productType: GlobalIDFilterInput
+
+ """Filter by product category."""
+ category: GlobalIDFilterInput
+
+ """Filter by collection."""
+ collection: GlobalIDFilterInput
+
+ """Filter by availability for purchase."""
+ isAvailable: Boolean
+
+ """Filter by public visibility."""
+ isPublished: Boolean
+
+ """Filter by visibility on the channel."""
+ isVisibleInListing: Boolean
+
+ """Filter by the publication date."""
+ publishedFrom: DateTime
+
+ """Filter by the date of availability for purchase."""
+ availableFrom: DateTime
+
+ """Filter by product with category assigned."""
+ hasCategory: Boolean
+
+ """Filter by product variant price."""
+ price: DecimalFilterInput
+
+ """Filter by the lowest variant price after discounts."""
+ minimalPrice: DecimalFilterInput
+
+ """Filter by attributes associated with the product."""
+ attributes: [AttributeInput!]
+
+ """Filter by variants having specific stock status."""
+ stockAvailability: StockAvailability
+
+ """Filter by stock of the product variant."""
+ stocks: ProductStockFilterInput
+
+ """Filter on whether product is a gift card or not."""
+ giftCard: Boolean
+
+ """Filter by product with preordered variants."""
+ hasPreorderedVariants: Boolean
+
+ """Filter by when was the most recent update."""
+ updatedAt: DateTimeRangeInput
+
+ """List of conditions that must be met."""
+ AND: [ProductWhereInput!]
+
+ """A list of conditions of which at least one must be met."""
+ OR: [ProductWhereInput!]
+}
+
+"""
+Define the filtering options for foreign key fields.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+input GlobalIDFilterInput {
+ """The value equal to."""
+ eq: ID
+
+ """The value included in."""
+ oneOf: [ID!]
+}
+
+"""
+Define the filtering options for decimal fields.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+input DecimalFilterInput {
+ """The value equal to."""
+ eq: Decimal
+
+ """The value included in."""
+ oneOf: [Decimal!]
+
+ """The value in range."""
+ range: DecimalRangeInput
+}
+
+"""
+Custom Decimal implementation.
+
+Returns Decimal as a float in the API,
+parses float to the Decimal on the way back.
+"""
+scalar Decimal
+
+input DecimalRangeInput {
+ """Decimal value greater than or equal to."""
+ gte: Decimal
+
+ """Decimal value less than or equal to."""
+ lte: Decimal
+}
+
input ProductOrder @doc(category: "Products") {
"""Specifies the direction in which to sort products."""
direction: OrderDirection!
@@ -7431,6 +7573,15 @@ type Collection implements Node & ObjectWithMetadata @doc(category: "Products")
"""Filtering options for products."""
filter: ProductFilterInput
+ """
+ Filtering options for products.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ where: ProductWhereInput
+
"""Sort products."""
sortBy: ProductOrder
@@ -22235,14 +22386,6 @@ input OrderGrantRefundCreateInput @doc(category: "Orders") {
reason: String
}
-"""
-Custom Decimal implementation.
-
-Returns Decimal as a float in the API,
-parses float to the Decimal on the way back.
-"""
-scalar Decimal
-
"""
Updates granted refund.
diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.py
index 19aa271ba1..c54d3a2985 100644
--- a/saleor/graphql/utils/filters.py
+++ b/saleor/graphql/utils/filters.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from typing import TYPE_CHECKING, Dict, List, Union
from django.utils import timezone
@@ -7,6 +8,8 @@ from ..core.enums import ReportingPeriod
if TYPE_CHECKING:
from django.db.models import QuerySet
+Number = Union[float, int, Decimal]
+
def reporting_period_to_date(period):
now = timezone.now()
@@ -57,3 +60,42 @@ def filter_by_string_field(
if one_of:
qs = qs.filter(**{f"{field}__in": one_of})
return qs
+
+
+def filter_where_by_id_field(
+ qs: "QuerySet", field: str, value: Dict[str, Union[str, List[str]]], type: str
+):
+ from . import resolve_global_ids_to_primary_keys
+
+ eq = value.get("eq")
+ one_of = value.get("one_of")
+ if eq and isinstance(eq, str):
+ _, pks = resolve_global_ids_to_primary_keys([eq], type, True)
+ qs = qs.filter(**{field: pks[0]})
+ if one_of:
+ _, pks = resolve_global_ids_to_primary_keys(one_of, type, True)
+ qs = qs.filter(**{f"{field}__in": pks})
+ return qs
+
+
+def filter_where_by_numeric_field(
+ qs: "QuerySet",
+ field: str,
+ value: Dict[str, Union[Number, List[Number], Dict[str, Number]]],
+):
+ eq = value.get("eq")
+ one_of = value.get("one_of")
+ range = value.get("range")
+
+ if eq:
+ qs = qs.filter(**{field: eq})
+ if one_of:
+ qs = qs.filter(**{f"{field}__in": one_of})
+ if range and isinstance(range, dict):
+ lte = range.get("lte")
+ gte = range.get("gte")
+ if lte is not None:
+ qs = qs.filter(**{f"{field}__lte": lte})
+ if gte is not None:
+ qs = qs.filter(**{f"{field}__gte": gte})
+ return qs
diff --git a/saleor/product/migrations/0184_product_product_gin.py b/saleor/product/migrations/0184_product_product_gin.py
new file mode 100644
index 0000000000..49998f8b37
--- /dev/null
+++ b/saleor/product/migrations/0184_product_product_gin.py
@@ -0,0 +1,24 @@
+# Generated by Django 3.2.18 on 2023-05-29 11:25
+
+import django.contrib.postgres.indexes
+from django.db import migrations
+from django.contrib.postgres.operations import AddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0183_calculate_discounted_prices"),
+ ]
+
+ atomic = False
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="product",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["name", "slug"],
+ name="product_gin",
+ opclasses=["gin_trgm_ops", "gin_trgm_ops"],
+ ),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 0d9fe487ab..6cc95fb0b8 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -463,6 +463,11 @@ class Product(SeoModel, ModelWithMetadata, ModelWithExternalReference):
name="product_tsearch",
fields=["search_vector"],
),
+ GinIndex(
+ name="product_gin",
+ fields=["name", "slug"],
+ opclasses=["gin_trgm_ops"] * 2,
+ ),
]
indexes.extend(ModelWithMetadata.Meta.indexes)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 4f91c9af8e..16befc3677 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2027,6 +2027,14 @@ def categories(db):
return [category1, category2]
+def category_list():
+ category_1 = Category.objects.create(name="Category 1", slug="category-1")
+ category_2 = Category.objects.create(name="Category 2", slug="category-2")
+ category_3 = Category.objects.create(name="Category 3", slug="category-3")
+ return category_1, category_2, category_3
+
+
@pytest.fixture
def categories_tree(db, product_type, channel_USD): # pylint: disable=W0613
parent = Category.objects.create(name="Parent", slug="parent")
@@ -2167,6 +2175,20 @@ def product_type(color_attribute, size_attribute, default_tax_class):
return product_type
+def product_type_list():
+ product_type_1 = ProductType.objects.create(
+ name="Type 1", slug="type-1", kind=ProductTypeKind.NORMAL
+ )
+ product_type_2 = ProductType.objects.create(
+ name="Type 2", slug="type-2", kind=ProductTypeKind.NORMAL
+ )
+ product_type_3 = ProductType.objects.create(
+ name="Type 3", slug="type-3", kind=ProductTypeKind.NORMAL
+ )
+ return product_type_1, product_type_2, product_type_3
+
+
@pytest.fixture
def non_shippable_gift_card_product_type(db):
product_type = ProductType.objects.create(