Skip to content

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

Use root level channel argument for filtering and sorting (#7374)

Iga Karbowiakef275083b09f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5b8399a4e..510193a7c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -219,6 +219,8 @@ All notable, unreleased changes to this project will be documented in this file.
- attributes with choices - `DROPDOWN` and `MULTISELECT`
- attributes without choices - `FILE`, `REFERENCE`, `NUMERIC` and `RICH_TEXT`
- Unify checkout identifier in checkout mutations and queries - #7511 by @IKarbowiak
+- Use root level channel argument for filtering and sorting - #7374 by @IKarbowiak
+ - drop `channel` field from filters and sorters
### Other
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
index ee563337cd..fcf37c9616 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -8,7 +8,7 @@ from ...product import models
from ..attribute.enums import AttributeTypeEnum
from ..channel.filters import get_channel_slug_from_filter_data
from ..core.filters import EnumFilter, MetadataFilterBase
-from ..core.types import ChannelFilterInputObjectType, FilterInputObjectType
+from ..core.types import FilterInputObjectType
from ..core.utils import from_global_id_or_error
from ..utils import get_user_or_app_from_context
from ..utils.filters import filter_fields_containing_value
@@ -107,7 +107,7 @@ class AttributeFilter(MetadataFilterBase):
)
-class AttributeFilterInput(ChannelFilterInputObjectType):
+class AttributeFilterInput(FilterInputObjectType):
class Meta:
filterset_class = AttributeFilter
diff --git a/saleor/graphql/attribute/schema.py b/saleor/graphql/attribute/schema.py
index 2c8b7ef714..7fb121c0b3 100644
--- a/saleor/graphql/attribute/schema.py
+++ b/saleor/graphql/attribute/schema.py
@@ -30,6 +30,9 @@ class AttributeQueries(graphene.ObjectType):
description="List of the shop's attributes.",
filter=AttributeFilterInput(description="Filtering options for attributes."),
sort_by=AttributeSortingInput(description="Sorting options for attributes."),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
)
attribute = graphene.Field(
Attribute,
diff --git a/saleor/graphql/attribute/tests/deprecated/__init__.py b/saleor/graphql/attribute/tests/deprecated/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/tests/deprecated/test_attributes.py b/saleor/graphql/attribute/tests/deprecated/test_attributes.py
new file mode 100644
index 0000000000..fb700c044a
--- /dev/null
+++ b/saleor/graphql/attribute/tests/deprecated/test_attributes.py
@@ -0,0 +1,69 @@
+import warnings
+
+import graphene
+from django.db.models import Q
+
+from .....attribute.models import Attribute
+from .....channel.models import Channel
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from .....product.models import Category, Product, ProductType
+from ....tests.utils import get_graphql_content
+
+QUERY_ATTRIBUTES_WITH_FILTER = """
+ query ($filter: AttributeFilterInput!) {
+ attributes(first: 5, filter: $filter) {
+ edges {
+ node {
+ id
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_attributes_query_with_filter(
+ user_api_client,
+ product_type,
+ category,
+ published_collection,
+ collection_with_products,
+ channel_USD,
+):
+ Channel.objects.exclude(pk=channel_USD.pk).delete()
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ # Create another product type and attribute that shouldn't get matched
+ other_category = Category.objects.create(name="Other Category", slug="other-cat")
+ other_attribute = Attribute.objects.create(name="Other", slug="other")
+ other_product_type = ProductType.objects.create(
+ name="Other type", has_variants=True, is_shipping_required=True
+ )
+ other_product_type.product_attributes.add(other_attribute)
+
+ # other product
+ Product.objects.create(
+ name="Another Product", product_type=other_product_type, category=other_category
+ )
+
+ expected_qs = Attribute.objects.filter(
+ Q(attributeproduct__product_type_id=product_type.pk)
+ | Q(attributevariant__product_type_id=product_type.pk)
+ )
+
+ variables = {"filter": {"inCategory": category_id}}
+ with warnings.catch_warnings(record=True) as warns:
+ content = get_graphql_content(
+ user_api_client.post_graphql(QUERY_ATTRIBUTES_WITH_FILTER, variables)
+ )
+ attributes_data = content["data"]["attributes"]["edges"]
+
+ flat_attributes_data = [attr["node"]["slug"] for attr in attributes_data]
+ expected_flat_attributes_data = list(expected_qs.values_list("slug", flat=True))
+
+ assert flat_attributes_data == expected_flat_attributes_data
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
index 64065ff6d0..c0feac1468 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
@@ -10,8 +10,8 @@ from ....tests.utils import get_graphql_content, get_graphql_content_from_respon
from ...filters import filter_attributes_by_product_types
ATTRIBUTES_FILTER_QUERY = """
- query($filters: AttributeFilterInput!) {
- attributes(first: 10, filter: $filters) {
+ query($filters: AttributeFilterInput!, $channel: String) {
+ attributes(first: 10, filter: $filters, channel: $channel) {
edges {
node {
name
@@ -151,8 +151,8 @@ def test_filter_attributes_in_category_invalid_category_id(
variables = {
"filters": {
"inCategory": "xyz",
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -192,8 +192,8 @@ def test_filter_attributes_in_category_object_with_given_id_does_not_exist(
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Product", -1),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -231,8 +231,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -280,8 +280,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_per
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -323,8 +323,8 @@ def test_filter_attributes_in_category_not_in_listings_by_staff_without_manage_p
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -369,8 +369,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -412,8 +412,8 @@ def test_filter_attributes_in_category_not_in_listings_by_app_without_manage_pro
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -452,8 +452,8 @@ def test_filter_attributes_in_category_not_published_by_customer(
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
},
+ "channel": channel_USD.slug,
}
# when
@@ -501,8 +501,8 @@ def test_filter_attributes_in_category_not_published_by_staff_with_perm(
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -544,8 +544,8 @@ def test_filter_attributes_in_category_not_published_by_staff_without_manage_pro
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -590,8 +590,8 @@ def test_filter_attributes_in_category_not_published_by_app_with_perm(
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -633,8 +633,8 @@ def test_filter_attributes_in_category_not_published_by_app_without_manage_produ
variables = {
"filters": {
"inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -673,8 +673,8 @@ def test_filter_attributes_in_collection_invalid_category_id(
variables = {
"filters": {
"inCollection": "xnd",
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -717,8 +717,8 @@ def test_filter_attributes_in_collection_object_with_given_id_does_not_exist(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Product", -1),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -758,8 +758,8 @@ def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -800,8 +800,8 @@ def test_filter_in_collection_not_published_by_customer(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -852,8 +852,8 @@ def test_filter_in_collection_not_published_by_staff_with_perm(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -898,8 +898,8 @@ def test_filter_in_collection_not_published_by_staff_without_manage_products(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -947,8 +947,8 @@ def test_filter_in_collection_not_published_by_app_with_perm(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
@@ -993,8 +993,8 @@ def test_filter_in_collection_not_published_by_app_without_manage_products(
variables = {
"filters": {
"inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
+ },
+ "channel": channel_USD.slug,
}
# when
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py b/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
index cadb8455fd..356d9ef823 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
@@ -11,7 +11,6 @@ from .....product.models import (
ProductVariant,
ProductVariantChannelListing,
)
-from ....channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
from ....tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -141,10 +140,10 @@ def attributes_for_filtering_with_channels(
QUERY_ATTRIBUTES_FILTERING = """
query (
- $filter: AttributeFilterInput
+ $filter: AttributeFilterInput, $channel: String
){
attributes (
- first: 10, filter: $filter
+ first: 10, filter: $filter, channel: $channel
) {
edges {
node {
@@ -186,7 +185,7 @@ def test_attributes_with_filtering_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_FILTERING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -210,9 +209,9 @@ def test_products_with_filtering_with_as_staff_user(
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": channel_USD.slug}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -248,9 +247,9 @@ def test_products_with_filtering_as_anonymous_client(
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": channel_USD.slug}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_USD.slug}
# when
response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
@@ -282,9 +281,9 @@ def test_products_with_filtering_with_not_visible_in_listings_as_staff_user(
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": channel_PLN.slug}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -324,9 +323,9 @@ def test_products_with_filtering_with_not_visible_in_listings_as_anonymous_clien
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": channel_PLN.slug}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_PLN.slug}
# when
response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
@@ -358,9 +357,9 @@ def test_products_with_filtering_with_not_published_as_staff_user(
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": other_channel_USD.slug}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": other_channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -396,9 +395,9 @@ def test_products_with_filtering_with_not_published_as_anonymous_client(
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": other_channel_USD.slug}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": other_channel_USD.slug}
# when
response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
@@ -427,9 +426,9 @@ def test_products_with_filtering_not_existing_channel(
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
- filter_by = {tested_field: filtered_by_node_id, "channel": "Not-existing"}
+ filter_by = {tested_field: filtered_by_node_id}
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": "Not-existing"}
# when
response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_pagination.py b/saleor/graphql/attribute/tests/queries/test_attribute_pagination.py
index 0683683b04..0671fc5b5f 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_pagination.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_pagination.py
@@ -127,12 +127,12 @@ def attributes_for_pagination(collection, category, channel_USD):
QUERY_ATTRIBUTES_PAGINATION = """
query (
- $first: Int, $last: Int, $after: String, $before: String,
+ $first: Int, $last: Int, $after: String, $before: String, $channel: String
$sortBy: AttributeSortingInput, $filter: AttributeFilterInput
){
attributes (
first: $first, last: $last, after: $after, before: $before,
- sortBy: $sortBy, filter: $filter
+ sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -219,9 +219,14 @@ def test_attributes_pagination_with_filtering_in_collection(
page_size = 2
attributes_order = ["Attr3", "AttrAttr2"]
collection_id = graphene.Node.to_global_id("Collection", collection.id)
- filter_by = {"inCollection": collection_id, "channel": channel_USD.slug}
+ filter_by = {"inCollection": collection_id}
- variables = {"first": page_size, "after": None, "filter": filter_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": filter_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(QUERY_ATTRIBUTES_PAGINATION, variables)
content = get_graphql_content(response)
attributes_nodes = content["data"]["attributes"]["edges"]
@@ -236,9 +241,14 @@ def test_attributes_pagination_with_filtering_in_category(
page_size = 2
attributes_order = ["Attr3", "AttrAttr2"]
category_id = graphene.Node.to_global_id("Category", category.id)
- filter_by = {"inCategory": category_id, "channel": channel_USD.slug}
+ filter_by = {"inCategory": category_id}
- variables = {"first": page_size, "after": None, "filter": filter_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": filter_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(QUERY_ATTRIBUTES_PAGINATION, variables)
content = get_graphql_content(response)
attributes_nodes = content["data"]["attributes"]["edges"]
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
index 00797bee3f..5c49d83ef0 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
@@ -561,7 +561,7 @@ def test_attributes_in_collection_query(
"""
query = query % {
- "filter_input": "filter: { %s: $nodeID, channel: $channel }" % tested_field
+ "filter_input": "filter: { %s: $nodeID } channel: $channel" % tested_field
}
variables = {"nodeID": filtered_by_node_id, "channel": channel_USD.slug}
diff --git a/saleor/graphql/channel/filters.py b/saleor/graphql/channel/filters.py
index a5f07ec740..ec27fa9777 100644
--- a/saleor/graphql/channel/filters.py
+++ b/saleor/graphql/channel/filters.py
@@ -1,14 +1,6 @@
from typing import Dict
-from graphql.error import GraphQLError
-
-LACK_OF_CHANNEL_IN_FILTERING_MSG = (
- "You must provide a `channel` filter parameter to properly filter data."
-)
-
def get_channel_slug_from_filter_data(filter_data: Dict):
- channel_slug = filter_data.get("channel", None)
- if not channel_slug:
- raise GraphQLError(LACK_OF_CHANNEL_IN_FILTERING_MSG)
+ channel_slug = str(filter_data["channel"])
return channel_slug
diff --git a/saleor/graphql/channel/sorters.py b/saleor/graphql/channel/sorters.py
deleted file mode 100644
index bbd782b886..0000000000
--- a/saleor/graphql/channel/sorters.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from graphql.error import GraphQLError
-
-LACK_OF_CHANNEL_IN_SORTING_MSG = "You must provide a `channel` as a sorting parameter."
-
-
-def validate_channel_slug(channel_slug: str):
- if not channel_slug:
- raise GraphQLError(LACK_OF_CHANNEL_IN_SORTING_MSG)
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.py
index aebbbd6228..4043f5fb6e 100644
--- a/saleor/graphql/core/fields.py
+++ b/saleor/graphql/core/fields.py
@@ -9,6 +9,7 @@ from graphql_relay.connection.arrayconnection import connection_from_list_slice
from promise import Promise
from ..channel import ChannelContext, ChannelQsContext
+from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..utils.sorting import sort_queryset_for_connection
from .connection import connection_from_queryset_slice
@@ -185,6 +186,10 @@ class FilterInputConnectionField(BaseDjangoConnectionField):
@classmethod
def filter_iterable(cls, iterable, filterset_class, filters_name, info, **args):
filter_input = args.get(filters_name)
+ if filter_input:
+ filter_input["channel"] = (
+ args.get("channel") or get_default_channel_slug_or_graphql_error()
+ )
if filter_input and filterset_class:
instance = filterset_class(
data=dict(filter_input), queryset=iterable, request=info.context
diff --git a/saleor/graphql/core/tests/test_graphql.py b/saleor/graphql/core/tests/test_graphql.py
index 265a333375..f70933ecf2 100644
--- a/saleor/graphql/core/tests/test_graphql.py
+++ b/saleor/graphql/core/tests/test_graphql.py
@@ -87,12 +87,12 @@ def test_real_query(user_api_client, product, channel_USD):
__typename
}
products(first: $first, sortBy: $sortBy, filter: {categories: [$categoryId],
- attributes: $attributesFilter, channel: $channel}, channel: $channel) {
+ attributes: $attributesFilter}, channel: $channel) {
...ProductListFragmentQuery
__typename
}
- attributes(first: 20, filter: {inCategory: $categoryId, channel: $channel}) {
+ attributes(first: 20, filter: {inCategory: $categoryId}, channel: $channel) {
edges {
node {
...ProductFiltersFragmentQuery
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index fbec73b59f..2032bf6c18 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -10,7 +10,7 @@ from .common import (
TaxType,
Weight,
)
-from .filter_input import ChannelFilterInputObjectType, FilterInputObjectType
+from .filter_input import FilterInputObjectType
from .money import VAT, Money, MoneyRange, ReducedRate, TaxedMoney, TaxedMoneyRange
-from .sort_input import ChannelSortInputObjectType, SortInputObjectType
+from .sort_input import SortInputObjectType
from .upload import Upload
diff --git a/saleor/graphql/core/types/filter_input.py b/saleor/graphql/core/types/filter_input.py
index f9e2dd56a1..1690ee0577 100644
--- a/saleor/graphql/core/types/filter_input.py
+++ b/saleor/graphql/core/types/filter_input.py
@@ -1,4 +1,4 @@
-from graphene import Argument, InputField, InputObjectType, String
+from graphene import InputField, InputObjectType
from graphene.types.inputobjecttype import InputObjectTypeOptions
from graphene.types.utils import yank_fields_from_attrs
from graphene_django.filter.utils import get_filterset_class
@@ -62,13 +62,3 @@ class FilterInputObjectType(InputObjectType):
field_type.kwargs = kwargs
args[name] = field_type
return args
-
-
-class ChannelFilterInputObjectType(FilterInputObjectType):
- channel = Argument(
- String,
- description="Specifies the channel by which the data should be sorted.",
- )
-
- class Meta:
- abstract = True
diff --git a/saleor/graphql/core/types/sort_input.py b/saleor/graphql/core/types/sort_input.py
index 7ebd9f341e..31a8a35ef1 100644
--- a/saleor/graphql/core/types/sort_input.py
+++ b/saleor/graphql/core/types/sort_input.py
@@ -35,13 +35,3 @@ class SortInputObjectType(graphene.InputObjectType):
description=f"Sort {type_name} by the selected field.",
)
cls._meta.fields.update({"field": field})
-
-
-class ChannelSortInputObjectType(SortInputObjectType):
- channel = graphene.Argument(
- graphene.String,
- description="Specifies the channel in which to sort the data.",
- )
-
- class Meta:
- abstract = True
diff --git a/saleor/graphql/discount/sorters.py b/saleor/graphql/discount/sorters.py
index 99cb7021f1..41cbd5ab08 100644
--- a/saleor/graphql/discount/sorters.py
+++ b/saleor/graphql/discount/sorters.py
@@ -1,8 +1,7 @@
import graphene
from django.db.models import Min, Q, QuerySet
-from ..channel.sorters import validate_channel_slug
-from ..core.types import ChannelSortInputObjectType
+from ..core.types import SortInputObjectType
class SaleSortField(graphene.Enum):
@@ -21,16 +20,15 @@ class SaleSortField(graphene.Enum):
@staticmethod
def qs_with_value(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
return queryset.annotate(
value=Min(
"channel_listings__discount_value",
- filter=Q(channel_listings__channel__slug=channel_slug),
+ filter=Q(channel_listings__channel__slug=str(channel_slug)),
)
)
-class SaleSortingInput(ChannelSortInputObjectType):
+class SaleSortingInput(SortInputObjectType):
class Meta:
sort_enum = SaleSortField
type_name = "sales"
@@ -54,26 +52,24 @@ class VoucherSortField(graphene.Enum):
@staticmethod
def qs_with_minimum_spent_amount(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
return queryset.annotate(
min_spent_amount=Min(
"channel_listings__min_spent_amount",
- filter=Q(channel_listings__channel__slug=channel_slug),
+ filter=Q(channel_listings__channel__slug=str(channel_slug)),
)
)
@staticmethod
def qs_with_value(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
return queryset.annotate(
discount_value=Min(
"channel_listings__discount_value",
- filter=Q(channel_listings__channel__slug=channel_slug),
+ filter=Q(channel_listings__channel__slug=str(channel_slug)),
)
)
-class VoucherSortingInput(ChannelSortInputObjectType):
+class VoucherSortingInput(SortInputObjectType):
class Meta:
sort_enum = VoucherSortField
type_name = "vouchers"
diff --git a/saleor/graphql/discount/tests/deprecated/__init__.py b/saleor/graphql/discount/tests/deprecated/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/discount/tests/deprecated/test_discount.py b/saleor/graphql/discount/tests/deprecated/test_discount.py
new file mode 100644
index 0000000000..8355c1de10
--- /dev/null
+++ b/saleor/graphql/discount/tests/deprecated/test_discount.py
@@ -0,0 +1,86 @@
+import warnings
+
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from ....tests.utils import get_graphql_content
+
+QUERY_SALES_WITH_SORTING_AND_FILTERING = """
+ query (
+ $sortBy: SaleSortingInput
+ ){
+ sales (
+ first: 10, sortBy: $sortBy
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+def test_sales_with_sorting_and_without_channel(
+ staff_api_client, permission_manage_discounts, new_sale, sale, channel_USD
+):
+ # given
+ listing = new_sale.channel_listings.first()
+ listing.discount_value = 10
+ listing.save(update_fields=["discount_value"])
+ variables = {"sortBy": {"field": "VALUE", "direction": "ASC"}}
+
+ # when
+ with warnings.catch_warnings(record=True) as warns:
+ response = staff_api_client.post_graphql(
+ QUERY_SALES_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ sales_nodes = content["data"]["sales"]["edges"]
+ assert [node["node"]["name"] for node in sales_nodes] == [sale.name, new_sale.name]
+
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+QUERY_VOUCHERS_WITH_SORT = """
+ query ($sort_by: VoucherSortingInput!) {
+ vouchers(first:5, sortBy: $sort_by) {
+ edges{
+ node{
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+def test_query_vouchers_with_sort(
+ staff_api_client,
+ permission_manage_discounts,
+ voucher_with_high_min_spent_amount,
+ voucher_percentage,
+):
+
+ variables = {"sort_by": {"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"}}
+ staff_api_client.user.user_permissions.add(permission_manage_discounts)
+
+ with warnings.catch_warnings(record=True) as warns:
+ response = staff_api_client.post_graphql(QUERY_VOUCHERS_WITH_SORT, variables)
+
+ content = get_graphql_content(response)
+ vouchers = content["data"]["vouchers"]["edges"]
+
+ assert [node["node"]["name"] for node in vouchers] == [
+ voucher_percentage.name,
+ voucher_with_high_min_spent_amount.name,
+ ]
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
diff --git a/saleor/graphql/discount/tests/test_pagination.py b/saleor/graphql/discount/tests/test_pagination.py
index 96169d16f7..fbe1de7fbd 100644
--- a/saleor/graphql/discount/tests/test_pagination.py
+++ b/saleor/graphql/discount/tests/test_pagination.py
@@ -58,12 +58,12 @@ def sales_for_pagination(channel_USD):
QUERY_SALES_PAGINATION = """
query (
- $first: Int, $last: Int, $after: String, $before: String,
+ $first: Int, $last: Int, $after: String, $before: String,, $channel: String
$sortBy: SaleSortingInput, $filter: SaleFilterInput
){
sales(
first: $first, last: $last, after: $after, before: $before,
- sortBy: $sortBy, filter: $filter
+ sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -123,9 +123,14 @@ def test_sales_pagination_with_sorting_and_channel(
):
page_size = 3
sales_order = ["Sale1", "Sale3", "Sale4"]
- sort_by = {"field": "VALUE", "direction": "ASC", "channel": channel_USD.slug}
+ sort_by = {"field": "VALUE", "direction": "ASC"}
- variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "sortBy": sort_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_SALES_PAGINATION,
variables,
@@ -268,12 +273,12 @@ def vouchers_for_pagination(db, channel_USD):
QUERY_VOUCHERS_PAGINATION = """
query (
- $first: Int, $last: Int, $after: String, $before: String,
+ $first: Int, $last: Int, $after: String, $before: String, $channel: String
$sortBy: VoucherSortingInput, $filter: VoucherFilterInput
){
vouchers(
first: $first, last: $last, after: $after, before: $before,
- sortBy: $sortBy, filter: $filter
+ sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -355,8 +360,12 @@ def test_vouchers_pagination_with_sorting_and_channel(
):
page_size = 3
- sort_by["channel"] = channel_USD.slug
- variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "sortBy": sort_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_VOUCHERS_PAGINATION,
variables,
diff --git a/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py b/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py
index 35e5709685..a93d3cc06a 100644
--- a/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py
+++ b/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py
@@ -2,7 +2,6 @@ import pytest
from ....discount import DiscountValueType
from ....discount.models import Sale, SaleChannelListing
-from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -81,10 +80,10 @@ def sales_for_sorting_with_channels(db, channel_USD, channel_PLN):
QUERY_SALES_WITH_SORTING_AND_FILTERING = """
query (
- $sortBy: SaleSortingInput, $filter: SaleFilterInput
+ $sortBy: SaleSortingInput, $filter: SaleFilterInput, $channel: String
){
sales (
- first: 10, sortBy: $sortBy, filter: $filter
+ first: 10, sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -112,7 +111,7 @@ def test_sales_with_sorting_and_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -120,11 +119,11 @@ def test_sales_with_sorting_and_without_channel(
[
(
{"field": "VALUE", "direction": "ASC"},
- ["Sale1", "Sale15", "Sale3", "Sale2", "Sale4"],
+ ["Sale1", "Sale15", "Sale3", "Sale2"],
),
(
{"field": "VALUE", "direction": "DESC"},
- ["Sale4", "Sale2", "Sale3", "Sale15", "Sale1"],
+ ["Sale2", "Sale3", "Sale15", "Sale1"],
),
],
)
@@ -137,8 +136,7 @@ def test_sales_with_sorting_and_channel_USD(
channel_USD,
):
# given
- sort_by["channel"] = channel_USD.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -160,11 +158,11 @@ def test_sales_with_sorting_and_channel_USD(
[
(
{"field": "VALUE", "direction": "ASC"},
- ["Sale2", "Sale4", "Sale15", "Sale1", "Sale3"],
+ ["Sale2", "Sale4", "Sale15", "Sale1"],
),
(
{"field": "VALUE", "direction": "DESC"},
- ["Sale3", "Sale1", "Sale15", "Sale4", "Sale2"],
+ ["Sale1", "Sale15", "Sale4", "Sale2"],
),
],
)
@@ -177,8 +175,7 @@ def test_sales_with_sorting_and_channel_PLN(
channel_PLN,
):
# given
- sort_by["channel"] = channel_PLN.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -202,15 +199,9 @@ def test_vouchers_with_sorting_and_not_existing_channel_asc(
channel_USD,
):
# given
- sales_order = [
- "Sale1",
- "Sale15",
- "Sale2",
- "Sale3",
- "Sale4",
- ]
variables = {
- "sortBy": {"field": "VALUE", "direction": "ASC", "channel": "Not-existing"}
+ "sortBy": {"field": "VALUE", "direction": "ASC"},
+ "channel": "Not-existing",
}
# when
@@ -223,6 +214,4 @@ def test_vouchers_with_sorting_and_not_existing_channel_asc(
# then
content = get_graphql_content(response)
- sales_nodes = content["data"]["sales"]["edges"]
- for index, sale_name in enumerate(sales_order):
- assert sale_name == sales_nodes[index]["node"]["name"]
+ assert not content["data"]["sales"]["edges"]
diff --git a/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py b/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py
index 7c24cf24fd..11ccd666a6 100644
--- a/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py
+++ b/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py
@@ -2,7 +2,6 @@ import pytest
from ....discount import DiscountValueType, VoucherType
from ....discount.models import Voucher, VoucherChannelListing
-from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -110,10 +109,10 @@ def vouchers_for_sorting_with_channels(db, channel_USD, channel_PLN):
QUERY_VOUCHERS_WITH_SORTING_AND_FILTERING = """
query (
- $sortBy: VoucherSortingInput, $filter: VoucherFilterInput
+ $sortBy: VoucherSortingInput, $filter: VoucherFilterInput, $channel: String
){
vouchers(
- first: 10, sortBy: $sortBy, filter: $filter
+ first: 10, sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -149,7 +148,7 @@ def test_voucher_with_sorting_and_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -157,19 +156,19 @@ def test_voucher_with_sorting_and_without_channel(
[
(
{"field": "VALUE", "direction": "ASC"},
- ["Voucher1", "Voucher15", "Voucher3", "Voucher2", "Voucher4"],
+ ["Voucher1", "Voucher15", "Voucher3", "Voucher2"],
),
(
{"field": "VALUE", "direction": "DESC"},
- ["Voucher4", "Voucher2", "Voucher3", "Voucher15", "Voucher1"],
+ ["Voucher2", "Voucher3", "Voucher15", "Voucher1"],
),
(
{"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
- ["Voucher1", "Voucher3", "Voucher15", "Voucher2", "Voucher4"],
+ ["Voucher1", "Voucher3", "Voucher15", "Voucher2"],
),
(
{"field": "MINIMUM_SPENT_AMOUNT", "direction": "DESC"},
- ["Voucher4", "Voucher2", "Voucher15", "Voucher3", "Voucher1"],
+ ["Voucher2", "Voucher15", "Voucher3", "Voucher1"],
),
],
)
@@ -182,8 +181,7 @@ def test_vouchers_with_sorting_and_channel_USD(
channel_USD,
):
# given
- sort_by["channel"] = channel_USD.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -205,19 +203,19 @@ def test_vouchers_with_sorting_and_channel_USD(
[
(
{"field": "VALUE", "direction": "ASC"},
- ["Voucher2", "Voucher4", "Voucher15", "Voucher1", "Voucher3"],
+ ["Voucher2", "Voucher4", "Voucher15", "Voucher1"],
),
(
{"field": "VALUE", "direction": "DESC"},
- ["Voucher3", "Voucher1", "Voucher15", "Voucher4", "Voucher2"],
+ ["Voucher1", "Voucher15", "Voucher4", "Voucher2"],
),
(
{"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
- ["Voucher1", "Voucher4", "Voucher2", "Voucher15", "Voucher3"],
+ ["Voucher1", "Voucher4", "Voucher2", "Voucher15"],
),
(
{"field": "MINIMUM_SPENT_AMOUNT", "direction": "DESC"},
- ["Voucher3", "Voucher15", "Voucher2", "Voucher4", "Voucher1"],
+ ["Voucher15", "Voucher2", "Voucher4", "Voucher1"],
),
],
)
@@ -230,8 +228,7 @@ def test_vouchers_with_sorting_and_channel_PLN(
channel_PLN,
):
# given
- sort_by["channel"] = channel_PLN.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -263,15 +260,7 @@ def test_vouchers_with_sorting_and_not_existing_channel_asc(
channel_USD,
):
# given
- vouchers_order = [
- "Voucher1",
- "Voucher15",
- "Voucher2",
- "Voucher3",
- "Voucher4",
- ]
- sort_by["channel"] = "Not-existing"
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
@@ -283,6 +272,4 @@ def test_vouchers_with_sorting_and_not_existing_channel_asc(
# then
content = get_graphql_content(response)
- vouchers_nodes = content["data"]["vouchers"]["edges"]
- for index, voucher_name in enumerate(vouchers_order):
- assert voucher_name == vouchers_nodes[index]["node"]["name"]
+ assert not content["data"]["vouchers"]["edges"]
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 687c855cf4..51762e53b1 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -38,7 +38,7 @@ from ..core.filters import (
MetadataFilterBase,
ObjectTypeFilter,
)
-from ..core.types import ChannelFilterInputObjectType, FilterInputObjectType
+from ..core.types import FilterInputObjectType
from ..core.types.common import IntRangeInput, PriceRangeInput
from ..utils import resolve_global_ids_to_primary_keys
from ..utils.filters import filter_fields_containing_value, filter_range_field
@@ -589,7 +589,7 @@ class ProductTypeFilter(MetadataFilterBase):
fields = ["search", "configurable", "product_type"]
-class ProductFilterInput(ChannelFilterInputObjectType):
+class ProductFilterInput(FilterInputObjectType):
class Meta:
filterset_class = ProductFilter
@@ -599,7 +599,7 @@ class ProductVariantFilterInput(FilterInputObjectType):
filterset_class = ProductVariantFilter
-class CollectionFilterInput(ChannelFilterInputObjectType):
+class CollectionFilterInput(FilterInputObjectType):
class Meta:
filterset_class = CollectionFilter
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index fafaa0fab5..a769a69493 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -21,8 +21,7 @@ from ...product.models import (
Product,
ProductChannelListing,
)
-from ..channel.sorters import validate_channel_slug
-from ..core.types import ChannelSortInputObjectType, SortInputObjectType
+from ..core.types import SortInputObjectType
class CategorySortField(graphene.Enum):
@@ -63,7 +62,7 @@ class CategorySortField(graphene.Enum):
return queryset.annotate(subcategory_count=Count("children__id"))
-class CategorySortingInput(ChannelSortInputObjectType):
+class CategorySortingInput(SortInputObjectType):
class Meta:
sort_enum = CategorySortField
type_name = "categories"
@@ -94,10 +93,9 @@ class CollectionSortField(graphene.Enum):
@staticmethod
def qs_with_availability(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
subquery = Subquery(
CollectionChannelListing.objects.filter(
- collection_id=OuterRef("pk"), channel__slug=channel_slug
+ collection_id=OuterRef("pk"), channel__slug=str(channel_slug)
).values_list("is_published")[:1]
)
return queryset.annotate(
@@ -106,10 +104,9 @@ class CollectionSortField(graphene.Enum):
@staticmethod
def qs_with_publication_date(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
subquery = Subquery(
CollectionChannelListing.objects.filter(
- collection_id=OuterRef("pk"), channel__slug=channel_slug
+ collection_id=OuterRef("pk"), channel__slug=str(channel_slug)
).values_list("publication_date")[:1]
)
return queryset.annotate(
@@ -117,7 +114,7 @@ class CollectionSortField(graphene.Enum):
)
-class CollectionSortingInput(ChannelSortInputObjectType):
+class CollectionSortingInput(SortInputObjectType):
class Meta:
sort_enum = CollectionSortField
type_name = "collections"
@@ -163,31 +160,28 @@ class ProductOrderField(graphene.Enum):
@staticmethod
def qs_with_price(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
return queryset.annotate(
min_variants_price_amount=Min(
"variants__channel_listings__price_amount",
- filter=Q(variants__channel_listings__channel__slug=channel_slug)
+ filter=Q(variants__channel_listings__channel__slug=str(channel_slug))
& Q(variants__channel_listings__price_amount__isnull=False),
)
)
@staticmethod
def qs_with_minimal_price(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
return queryset.annotate(
discounted_price_amount=Min(
"channel_listings__discounted_price_amount",
- filter=Q(channel_listings__channel__slug=channel_slug),
+ filter=Q(channel_listings__channel__slug=str(channel_slug)),
)
)
@staticmethod
def qs_with_published(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
subquery = Subquery(
ProductChannelListing.objects.filter(
- product_id=OuterRef("pk"), channel__slug=channel_slug
+ product_id=OuterRef("pk"), channel__slug=str(channel_slug)
).values_list("is_published")[:1]
)
return queryset.annotate(
@@ -196,10 +190,9 @@ class ProductOrderField(graphene.Enum):
@staticmethod
def qs_with_publication_date(queryset: QuerySet, channel_slug: str) -> QuerySet:
- validate_channel_slug(channel_slug)
subquery = Subquery(
ProductChannelListing.objects.filter(
- product_id=OuterRef("pk"), channel__slug=channel_slug
+ product_id=OuterRef("pk"), channel__slug=str(channel_slug)
).values_list("publication_date")[:1]
)
return queryset.annotate(
@@ -219,7 +212,7 @@ class ProductOrderField(graphene.Enum):
)
-class ProductOrder(ChannelSortInputObjectType):
+class ProductOrder(SortInputObjectType):
attribute_id = graphene.Argument(
graphene.ID,
description=(
diff --git a/saleor/graphql/product/tests/benchmark/test_category.py b/saleor/graphql/product/tests/benchmark/test_category.py
index 8a84f2e468..1d188a1a22 100644
--- a/saleor/graphql/product/tests/benchmark/test_category.py
+++ b/saleor/graphql/product/tests/benchmark/test_category.py
@@ -102,7 +102,7 @@ def test_category_view(api_client, category_with_products, count_queries, channe
}
}
}
- attributes(filter: {inCategory: $id, channel: $channel}, first: 100) {
+ attributes(filter: {inCategory: $id}, channel: $channel, first: 100) {
edges {
node {
id
diff --git a/saleor/graphql/product/tests/benchmark/test_collection.py b/saleor/graphql/product/tests/benchmark/test_collection.py
index a0c9700f57..37158493e5 100644
--- a/saleor/graphql/product/tests/benchmark/test_collection.py
+++ b/saleor/graphql/product/tests/benchmark/test_collection.py
@@ -87,7 +87,7 @@ def test_collection_view(api_client, published_collection, count_queries, channe
startCursor
}
}
- attributes(filter: {inCollection: $id, channel: $channel}, first: 100) {
+ attributes(filter: {inCollection: $id}, channel: $channel, first: 100) {
edges {
node {
id
diff --git a/saleor/graphql/product/tests/deprecated/test_product.py b/saleor/graphql/product/tests/deprecated/test_product.py
index 73767fc9ef..d389bbe712 100644
--- a/saleor/graphql/product/tests/deprecated/test_product.py
+++ b/saleor/graphql/product/tests/deprecated/test_product.py
@@ -2,8 +2,10 @@ import warnings
import graphene
+from .....channel.models import Channel
from .....channel.utils import DEPRECATION_WARNING_MESSAGE
-from .....product.models import Product
+from .....product.models import Collection, CollectionChannelListing, Product
+from .....tests.utils import dummy_editorjs
from ....tests.utils import get_graphql_content
QUERY_PRODUCT = """
@@ -37,6 +39,38 @@ QUERY_FETCH_ALL_PRODUCTS = """
}
"""
+QUERY_PRODUCTS_WITH_FILTER = """
+ query ($filter: ProductFilterInput!) {
+ products(first:5, filter: $filter) {
+ edges{
+ node{
+ id
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+SORT_PRODUCTS_QUERY = """
+ query {
+ products (
+ sortBy: %(sort_by_product_order)s, first: 3
+ ) {
+ edges {
+ node {
+ name
+ productType{
+ name
+ }
+ updatedAt
+ }
+ }
+ }
+ }
+"""
+
def test_product_query_by_id_with_default_channel(user_api_client, product):
variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
@@ -85,6 +119,66 @@ def test_fetch_all_products(user_api_client, product):
)
+def test_products_query_with_price_filter(
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ channel_PLN.delete()
+ assert Channel.objects.count() == 1
+ product = product_list[0]
+ product.variants.first().channel_listings.filter().update(price_amount=None)
+
+ variables = {
+ "filter": {"price": {"gte": 9, "lte": 31}},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ with warnings.catch_warnings(record=True) as warns:
+ response = staff_api_client.post_graphql(QUERY_PRODUCTS_WITH_FILTER, variables)
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 3
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_sort_products_product_type_name(
+ user_api_client, product, product_with_default_variant, channel_USD
+):
+ # Test sorting by TYPE, ascending
+ asc_published_query = SORT_PRODUCTS_QUERY % {
+ "sort_by_product_order": "{field: TYPE, direction:ASC}"
+ }
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(asc_published_query, {})
+ content = get_graphql_content(response)
+ edges = content["data"]["products"]["edges"]
+ product_type_name_0 = edges[0]["node"]["productType"]["name"]
+ product_type_name_1 = edges[1]["node"]["productType"]["name"]
+ assert product_type_name_0 < product_type_name_1
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+ # Test sorting by PUBLISHED, descending
+ desc_published_query = SORT_PRODUCTS_QUERY % {
+ "sort_by_product_order": "{field: TYPE, direction:DESC}"
+ }
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(desc_published_query, {})
+ content = get_graphql_content(response)
+ product_type_name_0 = edges[0]["node"]["productType"]["name"]
+ product_type_name_1 = edges[1]["node"]["productType"]["name"]
+ assert product_type_name_0 < product_type_name_1
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
QUERY_COLLECTION_FROM_PRODUCT = """
query ($id: ID, $channel:String){
product(
@@ -96,7 +190,34 @@ QUERY_COLLECTION_FROM_PRODUCT = """
}
}
}
- """
+"""
+
+
+QUERY_COLLECTIONS_WITH_FILTER = """
+ query ($filter: CollectionFilterInput!) {
+ collections(first:5, filter: $filter) {
+ edges{
+ node{
+ id
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+QUERY_COLLECTIONS_WITH_SORT = """
+ query ($sort_by: CollectionSortingInput!) {
+ collections(first:5, sortBy: $sort_by) {
+ edges{
+ node{
+ name
+ }
+ }
+ }
+ }
+"""
def test_get_collections_from_product_as_customer(
@@ -151,6 +272,99 @@ def test_get_collections_from_product_as_anonymous(
)
+def test_collections_query_with_filter(
+ channel_USD,
+ staff_api_client,
+ permission_manage_products,
+):
+ # given
+ collections = Collection.objects.bulk_create(
+ [
+ Collection(
+ id=1,
+ name="Collection1",
+ slug="collection-published1",
+ description=dummy_editorjs("Test description"),
+ ),
+ Collection(
+ id=2,
+ name="Collection2",
+ slug="collection-published2",
+ description=dummy_editorjs("Test description"),
+ ),
+ Collection(
+ id=3,
+ name="Collection3",
+ slug="collection-unpublished",
+ description=dummy_editorjs("Test description"),
+ ),
+ ]
+ )
+ published = (True, True, False)
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ channel=channel_USD, collection=collection, is_published=published[num]
+ )
+ for num, collection in enumerate(collections)
+ ]
+ )
+ variables = {"filter": {"published": "PUBLISHED"}}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ with warnings.catch_warnings(record=True) as warns:
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_FILTER, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections = content["data"]["collections"]["edges"]
+
+ assert len(collections) == 2
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_collections_query_with_sort(
+ staff_api_client,
+ permission_manage_products,
+ product,
+ channel_USD,
+):
+ collections = Collection.objects.bulk_create(
+ [
+ Collection(name="Coll1", slug="collection-published1"),
+ Collection(name="Coll2", slug="collection-unpublished2"),
+ Collection(name="Coll3", slug="collection-published"),
+ ]
+ )
+ published = (True, False, True)
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ channel=channel_USD, collection=collection, is_published=published[num]
+ )
+ for num, collection in enumerate(collections)
+ ]
+ )
+ product.collections.add(Collection.objects.get(name="Coll2"))
+ variables = {"sort_by": {"field": "AVAILABILITY", "direction": "ASC"}}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ with warnings.catch_warnings(record=True) as warns:
+ response = staff_api_client.post_graphql(QUERY_COLLECTIONS_WITH_SORT, variables)
+
+ content = get_graphql_content(response)
+ collections = content["data"]["collections"]["edges"]
+ for order, collection_name in enumerate(["Coll2", "Coll1", "Coll3"]):
+ assert collections[order]["node"]["name"] == collection_name
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
QUERY_FETCH_ALL_VARIANTS = """
query fetchAllVariants {
productVariants(first: 10) {
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index 67a71d6240..0ae8c86bd4 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -355,7 +355,6 @@ def test_filter_collection_products_by_multiple_attributes(
filters = {
"attributes": [{"slug": "modes", "values": ["eco"]}],
- "channel": channel_USD.slug,
}
variables = {
"id": graphene.Node.to_global_id("Collection", published_collection.pk),
diff --git a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
index c251b5e772..f593dc5224 100644
--- a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
@@ -3,8 +3,6 @@ import datetime
import pytest
from ....product.models import Collection, CollectionChannelListing
-from ...channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
-from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -75,9 +73,12 @@ def collections_for_sorting_with_channels(channel_USD, channel_PLN):
QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING = """
- query ($sortBy: CollectionSortingInput, $filter: CollectionFilterInput){
+ query (
+ $sortBy: CollectionSortingInput,
+ $filter: CollectionFilterInput, $channel: String
+ ){
collections (
- first: 10, sortBy: $sortBy, filter: $filter
+ first: 10, sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -114,7 +115,7 @@ def test_collections_with_sorting_and_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -122,19 +123,19 @@ def test_collections_with_sorting_and_without_channel(
[
(
{"field": "AVAILABILITY", "direction": "ASC"},
- ["Collection2", "Collection3", "Collection4", "Collection1", "Collection5"],
+ ["Collection2", "Collection3", "Collection4", "Collection1"],
),
(
{"field": "AVAILABILITY", "direction": "DESC"},
- ["Collection5", "Collection1", "Collection4", "Collection3", "Collection2"],
+ ["Collection1", "Collection4", "Collection3", "Collection2"],
),
(
{"field": "PUBLICATION_DATE", "direction": "ASC"},
- ["Collection4", "Collection3", "Collection1", "Collection2", "Collection5"],
+ ["Collection4", "Collection3", "Collection1", "Collection2"],
),
(
{"field": "PUBLICATION_DATE", "direction": "DESC"},
- ["Collection5", "Collection2", "Collection1", "Collection3", "Collection4"],
+ ["Collection2", "Collection1", "Collection3", "Collection4"],
),
],
)
@@ -147,8 +148,7 @@ def test_collections_with_sorting_and_channel_USD(
channel_USD,
):
# given
- sort_by["channel"] = channel_USD.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -170,19 +170,19 @@ def test_collections_with_sorting_and_channel_USD(
[
(
{"field": "AVAILABILITY", "direction": "ASC"},
- ["Collection1", "Collection3", "Collection5", "Collection2", "Collection4"],
+ ["Collection1", "Collection3", "Collection5", "Collection2"],
),
(
{"field": "AVAILABILITY", "direction": "DESC"},
- ["Collection4", "Collection2", "Collection5", "Collection3", "Collection1"],
+ ["Collection2", "Collection5", "Collection3", "Collection1"],
),
(
{"field": "PUBLICATION_DATE", "direction": "ASC"},
- ["Collection5", "Collection3", "Collection1", "Collection2", "Collection4"],
+ ["Collection5", "Collection3", "Collection1", "Collection2"],
),
(
{"field": "PUBLICATION_DATE", "direction": "DESC"},
- ["Collection4", "Collection2", "Collection1", "Collection3", "Collection5"],
+ ["Collection2", "Collection1", "Collection3", "Collection5"],
),
],
)
@@ -195,8 +195,7 @@ def test_collections_with_sorting_and_channel_PLN(
channel_PLN,
):
# given
- sort_by["channel"] = channel_PLN.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -229,15 +228,7 @@ def test_collections_with_sorting_and_not_existing_channel_asc(
channel_USD,
):
# given
- collections_order = [
- "Collection1",
- "Collection2",
- "Collection3",
- "Collection4",
- "Collection5",
- ]
- sort_by["channel"] = "Not-existing"
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
@@ -249,9 +240,7 @@ def test_collections_with_sorting_and_not_existing_channel_asc(
# then
content = get_graphql_content(response)
- collections_nodes = content["data"]["collections"]["edges"]
- for index, collection_name in enumerate(collections_order):
- assert collection_name == collections_nodes[index]["node"]["name"]
+ assert not content["data"]["collections"]["edges"]
@pytest.mark.parametrize(
@@ -268,16 +257,8 @@ def test_collections_with_sorting_and_not_existing_channel_desc(
collections_for_sorting_with_channels,
channel_USD,
):
- collections_order = [
- "Collection5",
- "Collection4",
- "Collection3",
- "Collection2",
- "Collection1",
- ]
# given
- sort_by["channel"] = "Not-existing"
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
@@ -289,9 +270,7 @@ def test_collections_with_sorting_and_not_existing_channel_desc(
# then
content = get_graphql_content(response)
- collections_nodes = content["data"]["collections"]["edges"]
- for index, collection_name in enumerate(collections_order):
- assert collection_name == collections_nodes[index]["node"]["name"]
+ assert not content["data"]["collections"]["edges"]
def test_collections_with_filtering_without_channel(
@@ -309,7 +288,7 @@ def test_collections_with_filtering_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_FILTERING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -325,8 +304,7 @@ def test_collections_with_filtering_with_channel_USD(
channel_USD,
):
# given
- filter_by["channel"] = channel_USD.slug
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -355,8 +333,7 @@ def test_collections_with_filtering_with_channel_PLN(
channel_PLN,
):
# given
- filter_by["channel"] = channel_PLN.slug
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -384,8 +361,7 @@ def test_collections_with_filtering_and_not_existing_channel(
channel_USD,
):
# given
- filter_by["channel"] = "Not-existing"
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 19c7189562..781a915708 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -1703,8 +1703,7 @@ def test_products_query_with_filter_attributes(
variables = {
"filter": {
"attributes": [{"slug": attribute.slug, "values": [attr_value.slug]}],
- "channel": channel_USD.slug,
- }
+ },
}
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -2095,8 +2094,8 @@ def test_products_with_variants_query_as_app(
@pytest.mark.parametrize(
"products_filter",
[
- {"minimalPrice": {"gte": 1.0, "lte": 2.0}, "channel": "main"},
- {"isPublished": False, "channel": "main"},
+ {"minimalPrice": {"gte": 1.0, "lte": 2.0}},
+ {"isPublished": False},
{"search": "Juice1"},
],
)
@@ -2132,8 +2131,7 @@ def test_products_query_with_filter(
channel=channel_USD,
is_published=False,
)
- products_filter["channel"] = channel_USD.slug
- variables = {"filter": products_filter}
+ variables = {"filter": products_filter, "channel": channel_USD.slug}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_products_with_filter, variables)
content = get_graphql_content(response)
@@ -2156,7 +2154,7 @@ def test_products_query_with_price_filter_as_staff(
product.variants.first().channel_listings.filter().update(price_amount=None)
variables = {
- "filter": {"price": {"gte": 9, "lte": 31}, "channel": channel_USD.slug},
+ "filter": {"price": {"gte": 9, "lte": 31}},
"channel": channel_USD.slug,
}
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -2179,7 +2177,7 @@ def test_products_query_with_price_filter_as_user(
second_product_id = graphene.Node.to_global_id("Product", product_list[1].id)
third_product_id = graphene.Node.to_global_id("Product", product_list[2].id)
variables = {
- "filter": {"price": {"gte": 9, "lte": 31}, "channel": channel_USD.slug},
+ "filter": {"price": {"gte": 9, "lte": 31}},
"channel": channel_USD.slug,
}
user_api_client.user.user_permissions.add(permission_manage_products)
@@ -2236,7 +2234,8 @@ def test_products_query_with_filter_stock_availability_as_staff(
price_amount=None
)
variables = {
- "filter": {"stockAvailability": "OUT_OF_STOCK", "channel": channel_USD.slug}
+ "filter": {"stockAvailability": "OUT_OF_STOCK"},
+ "channel": channel_USD.slug,
}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_products_with_filter, variables)
@@ -2265,7 +2264,7 @@ def test_products_query_with_filter_stock_availability_as_user(
price_amount=None
)
variables = {
- "filter": {"stockAvailability": "OUT_OF_STOCK", "channel": channel_USD.slug},
+ "filter": {"stockAvailability": "OUT_OF_STOCK"},
"channel": channel_USD.slug,
}
response = user_api_client.post_graphql(query_products_with_filter, variables)
@@ -2296,7 +2295,8 @@ def test_products_query_with_filter_stock_availability_channel_without_shipping_
order_line=order_line, stock=stock, quantity_allocated=stock.quantity
)
variables = {
- "filter": {"stockAvailability": "OUT_OF_STOCK", "channel": channel_USD.slug}
+ "filter": {"stockAvailability": "OUT_OF_STOCK"},
+ "channel": channel_USD.slug,
}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_products_with_filter, variables)
@@ -2704,7 +2704,7 @@ def test_filter_products_with_unavailable_variants_attributes_as_user(
query Products($attributesFilter: [AttributeInput], $channel: String) {
products(
first: 5,
- filter: {attributes: $attributesFilter,channel: $channel},
+ filter: {attributes: $attributesFilter},
channel: $channel
) {
edges {
@@ -2746,7 +2746,7 @@ def test_filter_products_with_unavailable_variants_attributes_as_staff(
query Products($attributesFilter: [AttributeInput], $channel: String) {
products(
first: 5,
- filter: {attributes: $attributesFilter,channel: $channel},
+ filter: {attributes: $attributesFilter},
channel: $channel
) {
edges {
@@ -2852,7 +2852,7 @@ def test_sort_products(user_api_client, product, channel_USD):
query = SORT_PRODUCTS_QUERY
# Test sorting by PRICE, ascending
- sort_by = f'{{field: PRICE, direction: ASC, channel: "{channel_USD.slug}"}}'
+ sort_by = "{field: PRICE, direction: ASC}"
asc_price_query = query % {"sort_by_product_order": sort_by}
response = user_api_client.post_graphql(asc_price_query, variables)
content = get_graphql_content(response)
@@ -2867,7 +2867,7 @@ def test_sort_products(user_api_client, product, channel_USD):
assert price1 < price2
# Test sorting by PRICE, descending
- sort_by = f'{{field: PRICE, direction:DESC, channel: "{channel_USD.slug}"}}'
+ sort_by = "{field: PRICE, direction:DESC}"
desc_price_query = query % {"sort_by_product_order": sort_by}
response = user_api_client.post_graphql(desc_price_query, variables)
content = get_graphql_content(response)
@@ -2881,7 +2881,7 @@ def test_sort_products(user_api_client, product, channel_USD):
assert price1 > price2
# Test sorting by MINIMAL_PRICE, ascending
- sort_by = f'{{field: MINIMAL_PRICE, direction:ASC, channel: "{channel_USD.slug}"}}'
+ sort_by = "{field: MINIMAL_PRICE, direction:ASC}"
asc_price_query = query % {"sort_by_product_order": sort_by}
response = user_api_client.post_graphql(asc_price_query, variables)
content = get_graphql_content(response)
@@ -2891,7 +2891,7 @@ def test_sort_products(user_api_client, product, channel_USD):
assert price1 < price2
# Test sorting by MINIMAL_PRICE, descending
- sort_by = f'{{field: MINIMAL_PRICE, direction:DESC, channel: "{channel_USD.slug}"}}'
+ sort_by = "{field: MINIMAL_PRICE, direction:DESC}"
desc_price_query = query % {"sort_by_product_order": sort_by}
response = user_api_client.post_graphql(desc_price_query, variables)
content = get_graphql_content(response)
@@ -2959,7 +2959,7 @@ def test_sort_products_by_price_as_staff(staff_api_client, product, channel_USD)
query = SORT_PRODUCTS_QUERY
# Test sorting by PRICE, ascending
- sort_by = f'{{field: PRICE, direction: ASC, channel: "{channel_USD.slug}"}}'
+ sort_by = "{field: PRICE, direction: ASC}"
asc_price_query = query % {"sort_by_product_order": sort_by}
response = staff_api_client.post_graphql(asc_price_query, variables)
content = get_graphql_content(response)
@@ -2975,7 +2975,7 @@ def test_sort_products_by_price_as_staff(staff_api_client, product, channel_USD)
assert price1 < price2
# Test sorting by PRICE, descending
- sort_by = f'{{field: PRICE, direction:DESC, channel: "{channel_USD.slug}"}}'
+ sort_by = "{field: PRICE, direction:DESC}"
desc_price_query = query % {"sort_by_product_order": sort_by}
response = staff_api_client.post_graphql(desc_price_query, variables)
content = get_graphql_content(response)
@@ -8962,9 +8962,9 @@ def test_collections_query_with_filter(
for num, collection in enumerate(collections)
]
)
- collection_filter["channel"] = channel_USD.slug
variables = {
"filter": collection_filter,
+ "channel": channel_USD.slug,
}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_collections_with_filter, variables)
@@ -8975,8 +8975,8 @@ def test_collections_query_with_filter(
QUERY_COLLECTIONS_WITH_SORT = """
- query ($sort_by: CollectionSortingInput!) {
- collections(first:5, sortBy: $sort_by) {
+ query ($sort_by: CollectionSortingInput!, $channel: String) {
+ collections(first:5, sortBy: $sort_by, channel: $channel) {
edges{
node{
name
@@ -9023,8 +9023,7 @@ def test_collections_query_with_sort(
]
)
product.collections.add(Collection.objects.get(name="Coll2"))
- collection_sort["channel"] = channel_USD.slug
- variables = {"sort_by": collection_sort}
+ variables = {"sort_by": collection_sort, "channel": channel_USD.slug}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(QUERY_COLLECTIONS_WITH_SORT, variables)
content = get_graphql_content(response)
diff --git a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
index ae5efe8178..6b34b37c60 100644
--- a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
@@ -12,8 +12,6 @@ from ....product.models import (
ProductVariantChannelListing,
)
from ....tests.utils import dummy_editorjs
-from ...channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
-from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -204,9 +202,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING = """
- query ($sortBy: ProductOrder, $filter: ProductFilterInput){
+ query ($sortBy: ProductOrder, $filter: ProductFilterInput, $channel: String){
products (
- first: 10, sortBy: $sortBy, filter: $filter
+ first: 10, sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -245,7 +243,7 @@ def test_products_with_sorting_and_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -253,35 +251,35 @@ def test_products_with_sorting_and_without_channel(
[
(
{"field": "PUBLISHED", "direction": "ASC"},
- ["ProductProduct2", "Product1", "Product2", "ProductProduct1", "Product3"],
+ ["ProductProduct2", "Product1", "Product2", "ProductProduct1"],
),
(
{"field": "PUBLISHED", "direction": "DESC"},
- ["Product3", "ProductProduct1", "Product2", "Product1", "ProductProduct2"],
+ ["ProductProduct1", "Product2", "Product1", "ProductProduct2"],
),
(
{"field": "PRICE", "direction": "ASC"},
- ["Product2", "ProductProduct2", "Product1", "ProductProduct1", "Product3"],
+ ["Product2", "ProductProduct2", "Product1", "ProductProduct1"],
),
(
{"field": "PRICE", "direction": "DESC"},
- ["Product3", "ProductProduct1", "Product1", "ProductProduct2", "Product2"],
+ ["ProductProduct1", "Product1", "ProductProduct2", "Product2"],
),
(
{"field": "MINIMAL_PRICE", "direction": "ASC"},
- ["ProductProduct2", "Product1", "Product2", "ProductProduct1", "Product3"],
+ ["ProductProduct2", "Product1", "Product2", "ProductProduct1"],
),
(
{"field": "MINIMAL_PRICE", "direction": "DESC"},
- ["Product3", "ProductProduct1", "Product2", "Product1", "ProductProduct2"],
+ ["ProductProduct1", "Product2", "Product1", "ProductProduct2"],
),
(
{"field": "PUBLICATION_DATE", "direction": "ASC"},
- ["ProductProduct2", "ProductProduct1", "Product2", "Product1", "Product3"],
+ ["ProductProduct2", "ProductProduct1", "Product2", "Product1"],
),
(
{"field": "PUBLICATION_DATE", "direction": "DESC"},
- ["Product3", "Product1", "Product2", "ProductProduct1", "ProductProduct2"],
+ ["Product1", "Product2", "ProductProduct1", "ProductProduct2"],
),
],
)
@@ -294,8 +292,7 @@ def test_products_with_sorting_and_channel_USD(
channel_USD,
):
# given
- sort_by["channel"] = channel_USD.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -317,27 +314,27 @@ def test_products_with_sorting_and_channel_USD(
[
(
{"field": "PUBLISHED", "direction": "ASC"},
- ["Product1", "Product3", "ProductProduct1", "ProductProduct2", "Product2"],
+ ["Product1", "Product3", "ProductProduct1", "ProductProduct2"],
),
(
{"field": "PUBLISHED", "direction": "DESC"},
- ["Product2", "ProductProduct2", "ProductProduct1", "Product3", "Product1"],
+ ["ProductProduct2", "ProductProduct1", "Product3", "Product1"],
),
(
{"field": "PRICE", "direction": "ASC"},
- ["Product3", "ProductProduct1", "ProductProduct2", "Product1", "Product2"],
+ ["Product3", "ProductProduct1", "ProductProduct2", "Product1"],
),
(
{"field": "PRICE", "direction": "DESC"},
- ["Product2", "Product1", "ProductProduct2", "ProductProduct1", "Product3"],
+ ["Product1", "ProductProduct2", "ProductProduct1", "Product3"],
),
(
{"field": "MINIMAL_PRICE", "direction": "ASC"},
- ["ProductProduct1", "ProductProduct2", "Product3", "Product1", "Product2"],
+ ["ProductProduct1", "ProductProduct2", "Product3", "Product1"],
),
(
{"field": "MINIMAL_PRICE", "direction": "DESC"},
- ["Product2", "Product1", "Product3", "ProductProduct2", "ProductProduct1"],
+ ["Product1", "Product3", "ProductProduct2", "ProductProduct1"],
),
],
)
@@ -350,8 +347,7 @@ def test_products_with_sorting_and_channel_PLN(
channel_PLN,
):
# given
- sort_by["channel"] = channel_PLN.slug
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -384,15 +380,7 @@ def test_products_with_sorting_and_not_existing_channel_asc(
channel_USD,
):
# given
- products_order = [
- "Product1",
- "Product2",
- "Product3",
- "ProductProduct1",
- "ProductProduct2",
- ]
- sort_by["channel"] = "Not-existing"
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
@@ -404,9 +392,7 @@ def test_products_with_sorting_and_not_existing_channel_asc(
# then
content = get_graphql_content(response)
- products_nodes = content["data"]["products"]["edges"]
- for index, product_name in enumerate(products_order):
- assert product_name == products_nodes[index]["node"]["name"]
+ assert not content["data"]["products"]["edges"]
@pytest.mark.parametrize(
@@ -424,16 +410,8 @@ def test_products_with_sorting_and_not_existing_channel_desc(
products_for_sorting_with_channels,
channel_USD,
):
- products_order = [
- "ProductProduct2",
- "ProductProduct1",
- "Product3",
- "Product2",
- "Product1",
- ]
# given
- sort_by["channel"] = "Not-existing"
- variables = {"sortBy": sort_by}
+ variables = {"sortBy": sort_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
@@ -445,9 +423,7 @@ def test_products_with_sorting_and_not_existing_channel_desc(
# then
content = get_graphql_content(response)
- products_nodes = content["data"]["products"]["edges"]
- for index, product_name in enumerate(products_order):
- assert product_name == products_nodes[index]["node"]["name"]
+ assert not content["data"]["products"]["edges"]
@pytest.mark.parametrize(
@@ -469,7 +445,7 @@ def test_products_with_filtering_without_channel(
)
# then
- assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_FILTERING_MSG)
+ assert_graphql_error_with_message(response, "A default channel does not exist.")
@pytest.mark.parametrize(
@@ -492,8 +468,7 @@ def test_products_with_filtering_with_channel_USD(
channel_USD,
):
# given
- filter_by["channel"] = channel_USD.slug
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -529,8 +504,7 @@ def test_products_with_filtering_with_channel_PLN(
channel_PLN,
):
# given
- filter_by["channel"] = channel_PLN.slug
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": channel_PLN.slug}
# when
response = staff_api_client.post_graphql(
@@ -565,8 +539,7 @@ def test_products_with_filtering_and_not_existing_channel(
channel_USD,
):
# given
- filter_by["channel"] = "Not-existing"
- variables = {"filter": filter_by}
+ variables = {"filter": filter_by, "channel": "Not-existing"}
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/product/tests/test_product_pagination.py b/saleor/graphql/product/tests/test_product_pagination.py
index f5d488c115..96cfde3aa1 100644
--- a/saleor/graphql/product/tests/test_product_pagination.py
+++ b/saleor/graphql/product/tests/test_product_pagination.py
@@ -185,12 +185,12 @@ def collections_for_pagination(product, product_with_single_variant, channel_USD
QUERY_COLLECTIONS_PAGINATION = """
query (
- $first: Int, $last: Int, $after: String, $before: String,
+ $first: Int, $last: Int, $after: String, $before: String, $channel: String,
$sortBy: CollectionSortingInput, $filter: CollectionFilterInput
){
collections (
first: $first, last: $last, after: $after, before: $before,
- sortBy: $sortBy, filter: $filter
+ sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -241,8 +241,12 @@ def test_collections_pagination_with_sorting(
channel_USD,
):
page_size = 3
- sort_by["channel"] = channel_USD.slug
- variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "sortBy": sort_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_COLLECTIONS_PAGINATION,
variables,
@@ -278,8 +282,12 @@ def test_collections_pagination_with_filtering(
channel_USD,
):
page_size = 2
- filter_by["channel"] = channel_USD.slug
- variables = {"first": page_size, "after": None, "filter": filter_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": filter_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_COLLECTIONS_PAGINATION,
variables,
@@ -442,12 +450,12 @@ def products_for_pagination(
QUERY_PRODUCTS_PAGINATION = """
query (
- $first: Int, $last: Int, $after: String, $before: String,
+ $first: Int, $last: Int, $after: String, $before: String, $channel: String,
$sortBy: ProductOrder, $filter: ProductFilterInput
){
products (
first: $first, last: $last, after: $after, before: $before,
- sortBy: $sortBy, filter: $filter
+ sortBy: $sortBy, filter: $filter, channel: $channel
) {
edges {
node {
@@ -531,8 +539,12 @@ def test_products_pagination_with_sorting_and_channel(
):
page_size = 3
- sort_by["channel"] = channel_USD.slug
- variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "sortBy": sort_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_PRODUCTS_PAGINATION,
variables,
@@ -687,8 +699,8 @@ def test_products_pagination_for_products_with_the_same_names_one_page(
[
({"hasCategory": True}, ["Product1", "Product2"]),
(
- {"stockAvailability": "OUT_OF_STOCK", "channel": "main"},
- ["Product2", "Product3"],
+ {"stockAvailability": "OUT_OF_STOCK"},
+ ["Product2", "ProductProduct1"],
),
],
)
@@ -702,8 +714,12 @@ def test_products_pagination_with_filtering(
):
page_size = 2
- filter_by["channel"] = channel_USD.slug
- variables = {"first": page_size, "after": None, "filter": filter_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": filter_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_PRODUCTS_PAGINATION,
variables,
@@ -712,9 +728,9 @@ def test_products_pagination_with_filtering(
)
content = get_graphql_content(response)
products_nodes = content["data"]["products"]["edges"]
+ assert len(products_nodes) == page_size
assert products_order[0] == products_nodes[0]["node"]["name"]
assert products_order[1] == products_nodes[1]["node"]["name"]
- assert len(products_nodes) == page_size
@pytest.mark.parametrize(
@@ -734,8 +750,12 @@ def test_products_pagination_with_filtering_and_channel(
):
page_size = 2
- filter_by["channel"] = channel_USD.slug
- variables = {"first": page_size, "after": None, "filter": filter_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": filter_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_PRODUCTS_PAGINATION,
variables,
@@ -756,10 +776,14 @@ def test_products_pagination_with_filtering_by_attribute(
products_order = ["Product2", "ProductProduct1"]
filter_by = {
"attributes": [{"slug": "color", "values": ["red", "blue"]}],
- "channel": channel_USD.slug,
}
- variables = {"first": page_size, "after": None, "filter": filter_by}
+ variables = {
+ "first": page_size,
+ "after": None,
+ "filter": filter_by,
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
QUERY_PRODUCTS_PAGINATION,
variables,
diff --git a/saleor/graphql/product/tests/test_product_sorting.py b/saleor/graphql/product/tests/test_product_sorting.py
index 449d701db5..70d21c532c 100644
--- a/saleor/graphql/product/tests/test_product_sorting.py
+++ b/saleor/graphql/product/tests/test_product_sorting.py
@@ -179,7 +179,6 @@ def test_sort_products_by_publication_date(
"sortBy": {
"direction": direction,
"field": "PUBLICATION_DATE",
- "channel": channel_USD.slug,
},
"channel": channel_USD.slug,
}
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c23d8b6fa1..d6d96975b8 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -512,7 +512,6 @@ input AttributeFilterInput {
type: AttributeTypeEnum
inCollection: ID
inCategory: ID
- channel: String
}
input AttributeInput {
@@ -798,7 +797,6 @@ enum CategorySortField {
input CategorySortingInput {
direction: OrderDirection!
- channel: String
field: CategorySortField!
}
@@ -1232,7 +1230,6 @@ input CollectionFilterInput {
search: String
metadata: [MetadataFilter]
ids: [ID]
- channel: String
}
input CollectionInput {
@@ -1272,7 +1269,6 @@ enum CollectionSortField {
input CollectionSortingInput {
direction: OrderDirection!
- channel: String
field: CollectionSortField!
}
@@ -4294,7 +4290,6 @@ input ProductFilterInput {
minimalPrice: PriceRangeInput
productTypes: [ID]
ids: [ID]
- channel: String
}
type ProductImage {
@@ -4379,7 +4374,6 @@ input ProductMediaUpdateInput {
input ProductOrder {
direction: OrderDirection!
- channel: String
attributeId: ID
field: ProductOrderField
}
@@ -4786,7 +4780,7 @@ type Query {
checkoutLines(before: String, after: String, first: Int, last: Int): CheckoutLineCountableConnection
channel(id: ID): Channel
channels: [Channel!]
- attributes(filter: AttributeFilterInput, sortBy: AttributeSortingInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
+ attributes(filter: AttributeFilterInput, sortBy: AttributeSortingInput, channel: String, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
attribute(id: ID, slug: String): Attribute
appsInstallations: [AppInstallation!]!
apps(filter: AppFilterInput, sortBy: AppSortingInput, before: String, after: String, first: Int, last: Int): AppCountableConnection
@@ -4943,7 +4937,6 @@ enum SaleSortField {
input SaleSortingInput {
direction: OrderDirection!
- channel: String
field: SaleSortField!
}
@@ -5890,7 +5883,6 @@ enum VoucherSortField {
input VoucherSortingInput {
direction: OrderDirection!
- channel: String
field: VoucherSortField!
}
diff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.py
index e490f5ab05..8b981687f4 100644
--- a/saleor/graphql/utils/sorting.py
+++ b/saleor/graphql/utils/sorting.py
@@ -1,8 +1,9 @@
-from typing import Tuple
+from typing import Optional, Tuple
from django.db.models import QuerySet
from graphql.error import GraphQLError
+from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..core.enums import OrderDirection
from ..core.types import SortInputObjectType
from ..core.utils import from_global_id_or_error
@@ -28,7 +29,13 @@ def sort_queryset_for_connection(iterable, args):
reversed = True if "last" in args else False
query = getattr(iterable, "query", None)
if sort_by:
- iterable = sort_queryset(queryset=iterable, sort_by=sort_by, reversed=reversed)
+ iterable = sort_queryset(
+ queryset=iterable,
+ sort_by=sort_by,
+ reversed=reversed,
+ channel_slug=args.get("channel")
+ or get_default_channel_slug_or_graphql_error(),
+ )
elif query and "-rank" in query.order_by:
return iterable, {"field": "rank", "direction": "-"}
else:
@@ -40,7 +47,10 @@ def sort_queryset_for_connection(iterable, args):
def sort_queryset(
- queryset: QuerySet, sort_by: SortInputObjectType, reversed: bool
+ queryset: QuerySet,
+ sort_by: SortInputObjectType,
+ reversed: bool,
+ channel_slug: Optional[str],
) -> QuerySet:
"""Sort queryset according to given parameters.
@@ -76,7 +86,6 @@ def sort_queryset(
sorting_fields = sort_enum.get(sorting_field)
sorting_field_name = sorting_fields.name.lower()
- channel_slug = getattr(sort_by, "channel", None)
custom_sort_by = getattr(sort_enum, f"qs_with_{sorting_field_name}", None)
if custom_sort_by:
queryset = custom_sort_by(queryset, channel_slug=channel_slug)