Skip to content

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

ProductsQueryset manager execute duplicated channel queries (#15858)

Filip Owczarekfa9ea3af1251
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
index 60c3997373..78d068ff20 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -4,6 +4,7 @@ from django.db.models import Q
from ...attribute import AttributeInputType
from ...attribute.models import Attribute, AttributeValue
+from ...channel.models import Channel
from ...permission.utils import has_one_of_permissions
from ...product import models
from ...product.models import ALL_PRODUCTS_PERMISSIONS
@@ -42,8 +43,12 @@ def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug
if not value:
return qs
+ channel = None
+ if channel_slug is not None:
+ channel = Channel.objects.using(qs.db).filter(slug=str(channel_slug)).first()
+ limited_channel_access = False if channel_slug is None else True
product_qs = models.Product.objects.using(qs.db).visible_to_user(
- requestor, channel_slug
+ requestor, channel, limited_channel_access
)
if field == "in_category":
@@ -57,7 +62,7 @@ def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug
product_qs = product_qs.filter(category__in=tree)
if not has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS):
- product_qs = product_qs.annotate_visible_in_listings(channel_slug).exclude(
+ product_qs = product_qs.annotate_visible_in_listings(channel).exclude(
visible_in_listings=False
)
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 0113fc487d..7e8303375d 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -209,7 +209,7 @@ def validate_product_is_published(
unpublished_product = (
Product.objects.using(database_connection_name)
.filter(variants__id__in=variant_ids)
- .not_published(channel.slug)
+ .not_published(channel)
)
if unpublished_product.exists():
errors["lines"].append(
@@ -238,7 +238,7 @@ def validate_product_is_published_in_channel(
unpublished_product = list(
Product.objects.using(database_connection_name)
.filter(variants__id__in=variant_ids)
- .not_published(channel.slug)
+ .not_published(channel)
)
if unpublished_product:
unpublished_variants = (
@@ -398,9 +398,9 @@ def prepare_insufficient_stock_order_validation_errors(exc):
"Insufficient product stock.",
code=OrderErrorCode.INSUFFICIENT_STOCK.value,
params={
- "order_lines": [order_line_global_id]
- if order_line_global_id
- else [],
+ "order_lines": (
+ [order_line_global_id] if order_line_global_id else []
+ ),
"warehouse": warehouse_global_id,
},
)
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 841be576d9..da74436646 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -1,3 +1,5 @@
+from typing import Optional
+
from django.db.models import Exists, OuterRef, Sum
from ...channel.models import Channel
@@ -66,11 +68,17 @@ def resolve_digital_contents(info: ResolveInfo):
def resolve_product(
- info: ResolveInfo, id, slug, external_reference, channel_slug, requestor
+ info: ResolveInfo,
+ id,
+ slug,
+ external_reference,
+ channel: Optional[Channel],
+ limited_channel_access: bool,
+ requestor,
):
database_connection_name = get_database_connection_name(info.context)
qs = models.Product.objects.using(database_connection_name).visible_to_user(
- requestor, channel_slug=channel_slug
+ requestor, channel, limited_channel_access
)
if id:
_type, id = from_global_id_or_error(id, "Product")
@@ -83,18 +91,17 @@ def resolve_product(
@traced_resolver
def resolve_products(
- info: ResolveInfo, requestor, channel_slug=None
+ info: ResolveInfo,
+ requestor,
+ channel: Optional[Channel],
+ limited_channel_access: bool,
) -> ChannelQsContext:
connection_name = get_database_connection_name(info.context)
qs = models.Product.objects.using(connection_name).visible_to_user(
- requestor, channel_slug
+ requestor, channel, limited_channel_access
)
if not has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS):
- if channel := (
- Channel.objects.using(connection_name)
- .filter(slug=str(channel_slug))
- .first()
- ):
+ if channel:
product_channel_listings = (
models.ProductChannelListing.objects.using(connection_name)
.filter(channel_id=channel.id, visible_in_listings=True)
@@ -105,6 +112,7 @@ def resolve_products(
)
else:
qs = models.Product.objects.none()
+ channel_slug = channel.slug if channel else None
return ChannelQsContext(qs=qs, channel_slug=channel_slug)
@@ -129,21 +137,22 @@ def resolve_variant(
sku,
external_reference,
*,
- channel_slug,
+ channel: Optional[Channel],
+ limited_channel_access: bool,
requestor,
requestor_has_access_to_all,
):
connection_name = get_database_connection_name(info.context)
visible_products = (
models.Product.objects.using(connection_name)
- .visible_to_user(requestor, channel_slug)
+ .visible_to_user(requestor, channel, limited_channel_access)
.values_list("pk", flat=True)
)
qs = models.ProductVariant.objects.using(connection_name).filter(
product__id__in=visible_products
)
if not requestor_has_access_to_all:
- qs = qs.available_in_channel(channel_slug)
+ qs = qs.available_in_channel(channel)
if id:
_, id = from_global_id_or_error(id, "ProductVariant")
return qs.filter(pk=id).first()
@@ -159,24 +168,26 @@ def resolve_product_variants(
requestor_has_access_to_all,
requestor,
ids=None,
- channel_slug=None,
+ channel: Optional[Channel] = None,
+ limited_channel_access: bool = False,
) -> ChannelQsContext:
connection_name = get_database_connection_name(info.context)
visible_products = models.Product.objects.using(connection_name).visible_to_user(
- requestor, channel_slug
+ requestor, channel, limited_channel_access
)
qs = models.ProductVariant.objects.using(connection_name).filter(
product__id__in=visible_products
)
+ channel_slug = channel.slug if channel else None
if not requestor_has_access_to_all:
visible_products = visible_products.annotate_visible_in_listings(
- channel_slug
+ channel
).exclude(visible_in_listings=False)
qs = (
qs.using(connection_name)
.filter(product__in=visible_products)
- .available_in_channel(channel_slug)
+ .available_in_channel(channel)
)
if ids:
db_ids = [
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 5757a4ada5..1782ea36d5 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -5,6 +5,7 @@ from ...permission.utils import has_one_of_permissions
from ...product.models import ALL_PRODUCTS_PERMISSIONS
from ...product.search import search_products
from ..channel import ChannelContext, ChannelQsContext
+from ..channel.dataloaders import ChannelBySlugLoader
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
@@ -436,21 +437,35 @@ class ProductQueries(graphene.ObjectType):
requestor, ALL_PRODUCTS_PERMISSIONS
)
+ limited_channel_access = False if channel is None else True
if channel is None and not has_required_permissions:
channel = get_default_channel_slug_or_graphql_error(
allow_replica=info.context.allow_replica
)
- product = resolve_product(
- info,
- id=id,
- slug=slug,
- external_reference=external_reference,
- channel_slug=channel,
- requestor=requestor,
- )
+ def _resolve_product(channel_obj):
+ product = resolve_product(
+ info,
+ id=id,
+ slug=slug,
+ external_reference=external_reference,
+ channel=channel_obj,
+ limited_channel_access=limited_channel_access,
+ requestor=requestor,
+ )
- return ChannelContext(node=product, channel_slug=channel) if product else None
+ return (
+ ChannelContext(node=product, channel_slug=channel) if product else None
+ )
+
+ if channel:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(channel))
+ .then(_resolve_product)
+ )
+ else:
+ return _resolve_product(None)
@staticmethod
@traced_resolver
@@ -462,20 +477,32 @@ class ProductQueries(graphene.ObjectType):
has_required_permissions = has_one_of_permissions(
requestor, ALL_PRODUCTS_PERMISSIONS
)
+ limited_channel_access = False if channel is None else True
if channel is None and not has_required_permissions:
channel = get_default_channel_slug_or_graphql_error(
allow_replica=info.context.allow_replica
)
- qs = resolve_products(info, requestor, channel_slug=channel)
- if search:
- qs = ChannelQsContext(
- qs=search_products(qs.qs, search), channel_slug=channel
+
+ def _resolve_products(channel_obj):
+ qs = resolve_products(info, requestor, channel_obj, limited_channel_access)
+ if search:
+ qs = ChannelQsContext(
+ qs=search_products(qs.qs, search), channel_slug=channel
+ )
+ kwargs["channel"] = channel
+ qs = filter_connection_queryset(
+ qs, kwargs, allow_replica=info.context.allow_replica
)
- kwargs["channel"] = channel
- qs = filter_connection_queryset(
- qs, kwargs, allow_replica=info.context.allow_replica
- )
- return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+ return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+
+ if channel:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(channel))
+ .then(_resolve_products)
+ )
+ else:
+ return _resolve_products(None)
@staticmethod
def resolve_product_type(_root, info: ResolveInfo, *, id):
@@ -509,22 +536,35 @@ class ProductQueries(graphene.ObjectType):
requestor, ALL_PRODUCTS_PERMISSIONS
)
+ limited_channel_access = False if channel is None else True
if channel is None and not has_required_permissions:
channel = get_default_channel_slug_or_graphql_error(
allow_replica=info.context.allow_replica
)
- variant = resolve_variant(
- info,
- id,
- sku,
- external_reference,
- channel_slug=channel,
- requestor=requestor,
- requestor_has_access_to_all=has_required_permissions,
- )
+ def _resolve_product_variant(channel_obj):
+ variant = resolve_variant(
+ info,
+ id,
+ sku,
+ external_reference,
+ channel=channel_obj,
+ limited_channel_access=limited_channel_access,
+ requestor=requestor,
+ requestor_has_access_to_all=has_required_permissions,
+ )
+ return (
+ ChannelContext(node=variant, channel_slug=channel) if variant else None
+ )
- return ChannelContext(node=variant, channel_slug=channel) if variant else None
+ if channel:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(channel))
+ .then(_resolve_product_variant)
+ )
+ else:
+ return _resolve_product_variant(None)
@staticmethod
def resolve_product_variants(
@@ -534,24 +574,37 @@ class ProductQueries(graphene.ObjectType):
has_required_permissions = has_one_of_permissions(
requestor, ALL_PRODUCTS_PERMISSIONS
)
+ limited_channel_access = False if channel is None else True
if channel is None and not has_required_permissions:
channel = get_default_channel_slug_or_graphql_error(
allow_replica=info.context.allow_replica
)
- qs = resolve_product_variants(
- info,
- ids=ids,
- channel_slug=channel,
- requestor_has_access_to_all=has_required_permissions,
- requestor=requestor,
- )
- kwargs["channel"] = qs.channel_slug
- qs = filter_connection_queryset(
- qs, kwargs, allow_replica=info.context.allow_replica
- )
- return create_connection_slice(
- qs, info, kwargs, ProductVariantCountableConnection
- )
+
+ def _resolve_product_variants(channel_obj):
+ qs = resolve_product_variants(
+ info,
+ ids=ids,
+ channel=channel_obj,
+ limited_channel_access=limited_channel_access,
+ requestor_has_access_to_all=has_required_permissions,
+ requestor=requestor,
+ )
+ kwargs["channel"] = qs.channel_slug
+ qs = filter_connection_queryset(
+ qs, kwargs, allow_replica=info.context.allow_replica
+ )
+ return create_connection_slice(
+ qs, info, kwargs, ProductVariantCountableConnection
+ )
+
+ if channel:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(channel))
+ .then(_resolve_product_variants)
+ )
+ else:
+ return _resolve_product_variants(None)
@staticmethod
@traced_resolver
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index 1e5c13b09d..b769dd39fc 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -743,7 +743,7 @@ def test_products_for_federation_query_count(
],
}
- with django_assert_num_queries(5):
+ with django_assert_num_queries(3):
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 1
@@ -765,7 +765,7 @@ def test_products_for_federation_query_count(
],
}
- with django_assert_num_queries(5):
+ with django_assert_num_queries(3):
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 2
diff --git a/saleor/graphql/product/tests/benchmark/test_variant.py b/saleor/graphql/product/tests/benchmark/test_variant.py
index fa5f8d2775..7dcc3e5f56 100644
--- a/saleor/graphql/product/tests/benchmark/test_variant.py
+++ b/saleor/graphql/product/tests/benchmark/test_variant.py
@@ -384,7 +384,7 @@ def test_products_variants_for_federation_query_count(
],
}
- with django_assert_num_queries(4):
+ with django_assert_num_queries(3):
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 1
@@ -400,7 +400,7 @@ def test_products_variants_for_federation_query_count(
],
}
- with django_assert_num_queries(4):
+ with django_assert_num_queries(3):
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 4
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.py
index 1cee3df1a6..a877c26e55 100644
--- a/saleor/graphql/product/tests/queries/test_product_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_query.py
@@ -1965,8 +1965,31 @@ def test_query_product_media_by_id_zero_size_value_original_image_returned(
)
-def test_query_product_for_federation(api_client, product, channel_USD):
+QUERY_PRODUCT_IN_FEDERATION = """
+query GetProductInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on Product {
+ id
+ name
+ }
+ }
+}
+"""
+
+
+def test_query_product_for_federation(
+ api_client,
+ product,
+ product_in_channel_JPY,
+ shippable_gift_card_product,
+ channel_USD,
+ channel_JPY,
+):
product_id = graphene.Node.to_global_id("Product", product.pk)
+ shippable_gift_card_product_id = graphene.Node.to_global_id(
+ "Product", shippable_gift_card_product.pk
+ )
variables = {
"representations": [
{
@@ -1974,21 +1997,167 @@ def test_query_product_for_federation(api_client, product, channel_USD):
"id": product_id,
"channel": channel_USD.slug,
},
+ {
+ "__typename": "Product",
+ "id": shippable_gift_card_product_id,
+ "channel": channel_USD.slug,
+ },
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": channel_JPY.slug,
+ },
],
}
- query = """
- query GetProductInFederation($representations: [_Any]) {
- _entities(representations: $representations) {
- __typename
- ... on Product {
- id
- name
- }
- }
- }
- """
- response = api_client.post_graphql(query, variables)
+ response = api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "name": product.name,
+ },
+ {
+ "__typename": "Product",
+ "id": shippable_gift_card_product_id,
+ "name": shippable_gift_card_product.name,
+ },
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "name": product.name,
+ },
+ ]
+
+
+def test_query_product_for_federation_as_customer_not_existing_channel(
+ api_client, product, channel_USD
+):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": "not-existing-channel",
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_for_federation_as_customer_channel_not_active(
+ api_client, product, channel_USD
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_for_federation_as_customer_without_channel(api_client, product):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_for_federation_as_staff_user(
+ staff_api_client,
+ staff_user,
+ permission_manage_products,
+ product,
+ product_in_channel_JPY,
+ shippable_gift_card_product,
+ channel_USD,
+ channel_JPY,
+):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ shippable_gift_card_product_id = graphene.Node.to_global_id(
+ "Product", shippable_gift_card_product.pk
+ )
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": channel_USD.slug,
+ },
+ {
+ "__typename": "Product",
+ "id": shippable_gift_card_product_id,
+ "channel": channel_USD.slug,
+ },
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": channel_JPY.slug,
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "name": product.name,
+ },
+ {
+ "__typename": "Product",
+ "id": shippable_gift_card_product_id,
+ "name": shippable_gift_card_product.name,
+ },
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "name": product.name,
+ },
+ ]
+
+
+def test_query_product_for_federation_as_staff_user_without_chanel(
+ staff_api_client, staff_user, product, permission_manage_products
+):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
content = get_graphql_content(response)
assert content["data"]["_entities"] == [
{
@@ -1999,6 +2168,48 @@ def test_query_product_for_federation(api_client, product, channel_USD):
]
+def test_query_product_for_federation_as_staff_user_not_existing_channel(
+ staff_api_client, staff_user, product, channel_USD, permission_manage_products
+):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": "not-existing-channel",
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_for_federation_as_staff_user_channel_not_active(
+ staff_api_client, staff_user, product, channel_USD, permission_manage_products
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": "not-existing-channel",
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(QUERY_PRODUCT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
def test_query_product_media_for_federation(
api_client, product_with_image, channel_USD, site_settings
):
diff --git a/saleor/graphql/product/tests/queries/test_product_variant_query.py b/saleor/graphql/product/tests/queries/test_product_variant_query.py
index 68f2619e35..c9da985ba3 100644
--- a/saleor/graphql/product/tests/queries/test_product_variant_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_variant_query.py
@@ -625,7 +625,22 @@ def test_fetch_variant_without_sku_anonymous(api_client, product, variant, chann
assert data["product"]["id"] == product_id
-def test_query_product_variant_for_federation(api_client, variant, channel_USD):
+QUERY_PRODUCT_VARIANT_IN_FEDERATION = """
+query GetProductVariantInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on ProductVariant {
+ id
+ name
+ }
+ }
+}
+"""
+
+
+def test_query_product_variant_for_federation_as_customer(
+ api_client, variant, channel_USD
+):
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
variables = {
"representations": [
@@ -636,19 +651,173 @@ def test_query_product_variant_for_federation(api_client, variant, channel_USD):
},
],
}
- query = """
- query GetProductVariantInFederation($representations: [_Any]) {
- _entities(representations: $representations) {
- __typename
- ... on ProductVariant {
- id
- name
- }
+
+ response = api_client.post_graphql(QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "name": variant.name,
}
- }
- """
+ ]
+
+
+def test_query_product_variant_for_federation_as_customer_not_existing_channel(
+ api_client, variant
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "channel": "not-existing-channel",
+ },
+ ],
+ }
- response = api_client.post_graphql(query, variables)
+ response = api_client.post_graphql(QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_variant_for_federation_as_customer_channel_not_active(
+ api_client, variant, channel_USD
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_variant_for_federation_as_customer_without_channel(
+ api_client, variant
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_variant_for_federation_as_staff_user(
+ staff_api_client, staff_user, variant, channel_USD, permission_manage_products
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "name": variant.name,
+ }
+ ]
+
+
+def test_query_product_variant_for_federation_as_staff_user_not_existing_channel(
+ staff_api_client, staff_user, variant, permission_manage_products
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "channel": "not-existing-channel",
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_query_product_variant_for_federation_as_staff_user_channel_not_active(
+ staff_api_client, staff_user, variant, channel_USD, permission_manage_products
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "name": variant.name,
+ }
+ ]
+
+
+def test_query_product_variant_for_federation_as_staff_user_without_chanel(
+ staff_api_client, staff_user, variant, channel_USD, permission_manage_products
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ },
+ ],
+ }
+
+ staff_user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_IN_FEDERATION, variables
+ )
content = get_graphql_content(response)
assert content["data"]["_entities"] == [
{
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index 1ba3787b2a..9b77d1220d 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -12,6 +12,7 @@ from ....thumbnail.utils import (
get_thumbnail_size,
)
from ...channel import ChannelQsContext
+from ...channel.dataloaders import ChannelBySlugLoader
from ...channel.utils import get_default_channel_slug_or_graphql_error
from ...core.connection import (
CountableConnection,
@@ -171,30 +172,42 @@ class Category(ModelObjectType[models.Category]):
requestor, ALL_PRODUCTS_PERMISSIONS
)
tree = root.get_descendants(include_self=True)
+ limited_channel_access = False if channel is None else True
if channel is None and not has_required_permissions:
channel = get_default_channel_slug_or_graphql_error(
allow_replica=info.context.allow_replica
)
connection_name = get_database_connection_name(info.context)
- qs = models.Product.objects.using(connection_name).all()
- if not has_required_permissions:
- qs = (
- qs.visible_to_user(requestor, channel)
- .annotate_visible_in_listings(channel)
- .exclude(
- visible_in_listings=False,
+
+ def _resolve_products(channel_obj):
+ qs = models.Product.objects.using(connection_name).all()
+ if not has_required_permissions:
+ qs = (
+ qs.visible_to_user(requestor, channel_obj, limited_channel_access)
+ .annotate_visible_in_listings(channel_obj)
+ .exclude(
+ visible_in_listings=False,
+ )
)
+ if channel_obj and has_required_permissions:
+ qs = qs.filter(channel_listings__channel_id=channel_obj.id)
+ qs = qs.filter(category__in=tree)
+ qs = ChannelQsContext(qs=qs, channel_slug=channel)
+
+ kwargs["channel"] = channel
+ qs = filter_connection_queryset(
+ qs, kwargs, allow_replica=info.context.allow_replica
)
- if channel and has_required_permissions:
- qs = qs.filter(channel_listings__channel__slug=channel)
- qs = qs.filter(category__in=tree)
- qs = ChannelQsContext(qs=qs, channel_slug=channel)
-
- kwargs["channel"] = channel
- qs = filter_connection_queryset(
- qs, kwargs, allow_replica=info.context.allow_replica
- )
- return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+ return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+
+ if channel:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(channel))
+ .then(_resolve_products)
+ )
+ else:
+ return _resolve_products(None)
@staticmethod
def __resolve_references(roots: list["Category"], info):
diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.py
index 952e5bcce0..24e971a90a 100644
--- a/saleor/graphql/product/types/collections.py
+++ b/saleor/graphql/product/types/collections.py
@@ -13,6 +13,7 @@ from ....thumbnail.utils import (
get_thumbnail_size,
)
from ...channel import ChannelContext, ChannelQsContext
+from ...channel.dataloaders import ChannelBySlugLoader
from ...channel.types import ChannelContextType, ChannelContextTypeWithMetadata
from ...core import ResolveInfo
from ...core.connection import (
@@ -142,22 +143,34 @@ class Collection(ChannelContextTypeWithMetadata[models.Collection]):
search = kwargs.get("search")
requestor = get_user_or_app_from_context(info.context)
- qs = root.node.products.using(
- get_database_connection_name(info.context)
- ).visible_to_user(requestor, root.channel_slug)
+ limited_channel_access = False if root.channel_slug is None else True
- if search:
- qs = ChannelQsContext(
- qs=search_products(qs.qs, search), channel_slug=root.channel_slug
+ def _resolve_products(channel):
+ qs = root.node.products.using(
+ get_database_connection_name(info.context)
+ ).visible_to_user(requestor, channel, limited_channel_access)
+
+ if search:
+ qs = ChannelQsContext(
+ qs=search_products(qs.qs, search), channel_slug=root.channel_slug
+ )
+ else:
+ qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+
+ kwargs["channel"] = root.channel_slug
+ qs = filter_connection_queryset(
+ qs, kwargs, allow_replica=info.context.allow_replica
)
- else:
- qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+ return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
- kwargs["channel"] = root.channel_slug
- qs = filter_connection_queryset(
- qs, kwargs, allow_replica=info.context.allow_replica
- )
- return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+ if root.channel_slug:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(root.channel_slug))
+ .then(_resolve_products)
+ )
+ else:
+ return _resolve_products(None)
@staticmethod
def resolve_channel_listings(root: ChannelContext[models.Collection], info):
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 67319708e3..f73c495b3b 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -9,6 +9,7 @@ from graphene import relay
from promise import Promise
from ....attribute import models as attribute_models
+from ....channel.models import Channel
from ....core.utils import build_absolute_uri
from ....core.utils.country import get_active_country
from ....core.weight import convert_weight_to_default_weight_unit
@@ -808,18 +809,24 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):
channels[root.channel].add(root.id)
variants = {}
- for channel, ids in channels.items():
+ database_connection_name = get_database_connection_name(info.context)
+ channels_map = Channel.objects.using(database_connection_name).in_bulk(
+ set(channels.keys()), field_name="slug"
+ )
+ for channel_slug, ids in channels.items():
+ limited_channel_access = False if channel_slug is None else True
qs = resolve_product_variants(
info,
requestor_has_access_to_all,
requestor,
ids=ids,
- channel_slug=channel,
+ channel=channels_map.get(channel_slug),
+ limited_channel_access=limited_channel_access,
).qs
for variant in qs:
global_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- variants[f"{channel}_{global_id}"] = ChannelContext(
- channel_slug=channel, node=variant
+ variants[f"{channel_slug}_{global_id}"] = ChannelContext(
+ channel_slug=channel_slug, node=variant
)
return [variants.get(root_id) for root_id in roots_ids]
@@ -1600,14 +1607,20 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):
channels[root.channel].add(root_id)
products = {}
- for channel, ids in channels.items():
+
+ database_connection_name = get_database_connection_name(info.context)
+ channels_map = Channel.objects.using(database_connection_name).in_bulk(
+ set(channels.keys()), field_name="slug"
+ )
+ for channel_slug, ids in channels.items():
+ limited_channel_access = False if channel_slug is None else True
queryset = resolve_products(
- info, requestor, channel_slug=channel
+ info, requestor, channels_map.get(channel_slug), limited_channel_access
).qs.filter(id__in=ids)
for product in queryset:
- products[f"{channel}_{product.id}"] = ChannelContext(
- channel_slug=channel, node=product
+ products[f"{channel_slug}_{product.id}"] = ChannelContext(
+ channel_slug=channel_slug, node=product
)
return [products.get(root_id) for root_id in roots_ids]
@@ -1824,16 +1837,28 @@ class ProductType(ModelObjectType[models.ProductType]):
@staticmethod
def resolve_products(root: models.ProductType, info, *, channel=None, **kwargs):
requestor = get_user_or_app_from_context(info.context)
+ limited_channel_access = False if channel is None else True
if channel is None:
channel = get_default_channel_slug_or_graphql_error(
allow_replica=info.context.allow_replica
)
- qs = root.products.using(
- get_database_connection_name(info.context)
- ).visible_to_user(requestor, channel)
- qs = ChannelQsContext(qs=qs, channel_slug=channel)
- kwargs["channel"] = channel
- return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+
+ def _resolve_products(channel_obj):
+ qs = root.products.using(
+ get_database_connection_name(info.context)
+ ).visible_to_user(requestor, channel_obj, limited_channel_access)
+ qs = ChannelQsContext(qs=qs, channel_slug=channel)
+ kwargs["channel"] = channel
+ return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
+
+ if channel:
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(str(channel))
+ .then(_resolve_products)
+ )
+ else:
+ return _resolve_products(None)
@staticmethod
def resolve_available_attributes(root: models.ProductType, info, **kwargs):
diff --git a/saleor/product/managers.py b/saleor/product/managers.py
index 2b9069f6a8..7d20e1d143 100644
--- a/saleor/product/managers.py
+++ b/saleor/product/managers.py
@@ -28,73 +28,76 @@ from ..permission.utils import has_one_of_permissions
class ProductsQueryset(models.QuerySet):
- def published(self, channel_slug: str):
+ def published(self, channel: Channel):
from .models import ProductChannelListing
+ if not channel.is_active:
+ return self.none()
today = datetime.datetime.now(pytz.UTC)
- if channel := (
- Channel.objects.using(self.db)
- .filter(slug=str(channel_slug), is_active=True)
- .first()
- ):
- channel_listings = (
- ProductChannelListing.objects.using(self.db)
- .filter(
- Q(published_at__lte=today) | Q(published_at__isnull=True),
- channel_id=channel.id,
- is_published=True,
- )
- .values("id")
- )
- return self.filter(
- Exists(channel_listings.filter(product_id=OuterRef("pk")))
+ channel_listings = (
+ ProductChannelListing.objects.using(self.db)
+ .filter(
+ Q(published_at__lte=today) | Q(published_at__isnull=True),
+ channel_id=channel.id,
+ is_published=True,
)
- return self.none()
+ .values("id")
+ )
+ return self.filter(Exists(channel_listings.filter(product_id=OuterRef("pk"))))
- def not_published(self, channel_slug: str):
+ def not_published(self, channel: Channel):
today = datetime.datetime.now(pytz.UTC)
- return self.annotate_publication_info(channel_slug).filter(
+ return self.annotate_publication_info(channel).filter(
Q(published_at__gt=today) & Q(is_published=True)
| Q(is_published=False)
| Q(is_published__isnull=True)
)
- def published_with_variants(self, channel_slug: str):
+ def published_with_variants(self, channel: Channel):
from .models import ProductVariant, ProductVariantChannelListing
- if channel := (
- Channel.objects.using(self.db)
- .filter(slug=str(channel_slug), is_active=True)
- .first()
- ):
- variant_channel_listings = (
- ProductVariantChannelListing.objects.using(self.db)
- .filter(
- channel_id=channel.id,
- price_amount__isnull=False,
- )
- .values("id")
- )
- variants = ProductVariant.objects.using(self.db).filter(
- Exists(variant_channel_listings.filter(variant_id=OuterRef("pk")))
- )
- return self.published(channel_slug).filter(
- Exists(variants.filter(product_id=OuterRef("pk")))
+ if not channel.is_active:
+ return self.none()
+ variant_channel_listings = (
+ ProductVariantChannelListing.objects.using(self.db)
+ .filter(
+ channel_id=channel.id,
+ price_amount__isnull=False,
)
- return self.none()
+ .values("id")
+ )
+ variants = ProductVariant.objects.using(self.db).filter(
+ Exists(variant_channel_listings.filter(variant_id=OuterRef("pk")))
+ )
+ return self.published(channel).filter(
+ Exists(variants.filter(product_id=OuterRef("pk")))
+ )
def visible_to_user(
- self, requestor: Union["User", "App", None], channel_slug: Optional[str]
+ self,
+ requestor: Union["User", "App", None],
+ channel: Optional[Channel],
+ limited_channel_access: bool,
):
+ """Determine which products should be visible to user.
+
+ For user without permission we require channel to be passed to determine which
+ products are visible to user.
+ For user with permission we can return:
+ - all products if the channel is not passed and the query is not limited
+ to the provided channel.
+ (channel=None, limited_channel_access=False)
+ - no products if the channel is not passed and the query is limited
+ to the provided channel.
+ (channel=None, limited_channel_access=True)
+ - all products assigned to the channel if the channel is passed and
+ the query is limited to the provided channel.
+ (channel=Channel, limited_channel_access=True)
+ """
from .models import ALL_PRODUCTS_PERMISSIONS, ProductChannelListing
if has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS):
- if channel_slug:
- channel = (
- Channel.objects.using(self.db)
- .filter(slug=str(channel_slug))
- .first()
- )
+ if limited_channel_access:
if channel:
channel_listings = (
ProductChannelListing.objects.using(self.db)
@@ -106,45 +109,47 @@ class ProductsQueryset(models.QuerySet):
)
return self.none()
return self.all()
- if not channel_slug:
+ if not channel:
return self.none()
- return self.published_with_variants(channel_slug)
+ return self.published_with_variants(channel)
- def annotate_publication_info(self, channel_slug: str):
- return self.annotate_is_published(channel_slug).annotate_published_at(
- channel_slug
- )
+ def annotate_publication_info(self, channel: Channel):
+ return self.annotate_is_published(channel).annotate_published_at(channel)
- def annotate_is_published(self, channel_slug: str):
+ def annotate_is_published(self, channel: Channel):
from .models import ProductChannelListing
query = Subquery(
ProductChannelListing.objects.using(self.db)
- .filter(product_id=OuterRef("pk"), channel__slug=str(channel_slug))
+ .filter(product_id=OuterRef("pk"), channel_id=channel.id)
.values_list("is_published")[:1]
)
return self.annotate(
is_published=ExpressionWrapper(query, output_field=BooleanField())
)
- def annotate_published_at(self, channel_slug: str):
+ def annotate_published_at(self, channel: Channel):
from .models import ProductChannelListing
query = Subquery(
ProductChannelListing.objects.using(self.db)
- .filter(product_id=OuterRef("pk"), channel__slug=str(channel_slug))
+ .filter(product_id=OuterRef("pk"), channel_id=channel.id)
.values_list("published_at")[:1]
)
return self.annotate(
published_at=ExpressionWrapper(query, output_field=DateTimeField())
)
- def annotate_visible_in_listings(self, channel_slug):
+ def annotate_visible_in_listings(self, channel: Optional[Channel]):
from .models import ProductChannelListing
+ if not channel:
+ return self.annotate(
+ visible_in_listings=Value(False, output_field=BooleanField())
+ )
query = Subquery(
ProductChannelListing.objects.using(self.db)
- .filter(product_id=OuterRef("pk"), channel__slug=str(channel_slug))
+ .filter(product_id=OuterRef("pk"), channel_id=channel.id)
.values_list("visible_in_listings")[:1]
)
return self.annotate(
@@ -292,11 +297,17 @@ class ProductVariantQueryset(models.QuerySet):
),
)
- def available_in_channel(self, channel_slug):
- return self.filter(
- channel_listings__price_amount__isnull=False,
- channel_listings__channel__slug=str(channel_slug),
+ def available_in_channel(self, channel: Optional[Channel]):
+ from .models import ProductVariantChannelListing
+
+ if not channel:
+ return self.none()
+ channel_listings = (
+ ProductVariantChannelListing.objects.using(self.db)
+ .filter(price_amount__isnull=False, channel_id=channel.id)
+ .values("id")
)
+ return self.filter(Exists(channel_listings.filter(variant_id=OuterRef("pk"))))
def prefetched_for_webhook(self):
return self.prefetch_related(
diff --git a/saleor/product/tests/test_product_availability.py b/saleor/product/tests/test_product_availability.py
index 662156f1f8..ca93bd52bd 100644
--- a/saleor/product/tests/test_product_availability.py
+++ b/saleor/product/tests/test_product_availability.py
@@ -174,11 +174,11 @@ def test_available_products_only_published(product_list, channel_USD):
channel_listing.is_published = False
channel_listing.save(update_fields=["is_published"])
- available_products = models.Product.objects.published(channel_USD.slug)
+ available_products = models.Product.objects.published(channel_USD)
assert available_products.count() == 2
assert all(
[
- product.channel_listings.get(channel__slug=channel_USD.slug).is_published
+ product.channel_listings.get(channel__slug=channel_USD).is_published
for product in available_products
]
)
@@ -190,11 +190,11 @@ def test_available_products_only_available(product_list, channel_USD):
channel_listing.published_at = date_tomorrow
channel_listing.save(update_fields=["published_at"])
- available_products = models.Product.objects.published(channel_USD.slug)
+ available_products = models.Product.objects.published(channel_USD)
assert available_products.count() == 2
assert all(
[
- product.channel_listings.get(channel__slug=channel_USD.slug).is_published
+ product.channel_listings.get(channel__slug=channel_USD).is_published
for product in available_products
]
)
@@ -206,11 +206,11 @@ def test_available_products_available_from_yesterday(product_list, channel_USD):
channel_listing.published_at = date_tomorrow
channel_listing.save(update_fields=["published_at"])
- available_products = models.Product.objects.published(channel_USD.slug)
+ available_products = models.Product.objects.published(channel_USD)
assert available_products.count() == 3
assert all(
[
- product.channel_listings.get(channel__slug=channel_USD.slug).is_published
+ product.channel_listings.get(channel__slug=channel_USD).is_published
for product in available_products
]
)
@@ -219,7 +219,7 @@ def test_available_products_available_from_yesterday(product_list, channel_USD):
def test_available_products_available_without_channel_listings(
product_list, channel_PLN
):
- available_products = models.Product.objects.published(channel_PLN.slug)
+ available_products = models.Product.objects.published(channel_PLN)
assert available_products.count() == 0
@@ -230,9 +230,9 @@ def test_available_products_available_with_many_channels(
product__in=product_list_with_many_channels, channel=channel_PLN
).update(is_published=False)
- available_products = models.Product.objects.published(channel_PLN.slug)
+ available_products = models.Product.objects.published(channel_PLN)
assert available_products.count() == 0
- available_products = models.Product.objects.published(channel_USD.slug)
+ available_products = models.Product.objects.published(channel_USD)
assert available_products.count() == 3
@@ -248,27 +248,21 @@ def test_available_products_with_variants(product_list, channel_USD):
product = product_list[0]
product.variants.all().delete()
- available_products = models.Product.objects.published_with_variants(
- channel_USD.slug
- )
+ available_products = models.Product.objects.published_with_variants(channel_USD)
assert available_products.count() == 2
def test_available_products_with_variants_in_many_channels_usd(
product_list_with_variants_many_channel, channel_USD
):
- available_products = models.Product.objects.published_with_variants(
- channel_USD.slug
- )
+ available_products = models.Product.objects.published_with_variants(channel_USD)
assert available_products.count() == 1
def test_available_products_with_variants_in_many_channels_pln(
product_list_with_variants_many_channel, channel_PLN
):
- available_products = models.Product.objects.published_with_variants(
- channel_PLN.slug
- )
+ available_products = models.Product.objects.published_with_variants(channel_PLN)
assert available_products.count() == 2
@@ -279,14 +273,34 @@ def test_visible_to_customer_user(customer_user, product_list, channel_USD):
# when
available_products = models.Product.objects.visible_to_user(
- customer_user, channel_USD.slug
+ customer_user, channel_USD, True
)
# then
assert available_products.count() == len(product_list) - 1
-def test_visible_to_customer_user_without_channel_slug(
+def test_visible_to_customer_user_without_channel(
+ customer_user,
+ product_list,
+ channel_USD,
+ django_assert_num_queries,
+):
+ # given
+ product = product_list[0]
+ product.channel_listings.all().delete()
+
+ # when
+ available_products = models.Product.objects.visible_to_user(
+ customer_user, None, False
+ )
+
+ # then
+ with django_assert_num_queries(0):
+ assert available_products.count() == 0
+
+
+def test_visible_to_customer_user_with_not_existing_channel_slug_passed(
customer_user,
product_list,
channel_USD,
@@ -297,7 +311,9 @@ def test_visible_to_customer_user_without_channel_slug(
product.channel_listings.all().delete()
# when
- available_products = models.Product.objects.visible_to_user(customer_user, None)
+ available_products = models.Product.objects.visible_to_user(
+ customer_user, None, True
+ )
# then
with django_assert_num_queries(0):
@@ -317,7 +333,7 @@ def test_visible_to_staff_user(
staff_user.user_permissions.add(permission_manage_products)
# when
- available_products = models.Product.objects.visible_to_user(staff_user, None)
+ available_products = models.Product.objects.visible_to_user(staff_user, None, False)
# then
assert available_products.count() == len(product_list)
@@ -337,19 +353,38 @@ def test_visible_to_staff_user_with_channel(
# when
available_products = models.Product.objects.visible_to_user(
- staff_user, channel_USD.slug
+ staff_user, channel_USD, True
)
# then
assert available_products.count() == len(product_list) - 1
+def test_visible_to_staff_user_with_not_existing_channel_slug_passed(
+ staff_user,
+ product_list,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ product = product_list[0]
+ product.channel_listings.all().delete()
+
+ staff_user.user_permissions.add(permission_manage_products)
+
+ # when
+ available_products = models.Product.objects.visible_to_user(staff_user, None, True)
+
+ # then
+ assert available_products.count() == 0
+
+
def test_filter_not_published_product_is_unpublished(product, channel_USD):
channel_listing = product.channel_listings.get()
channel_listing.is_published = False
channel_listing.save(update_fields=["is_published"])
- available_products = models.Product.objects.not_published(channel_USD.slug)
+ available_products = models.Product.objects.not_published(channel_USD)
assert available_products.count() == 1
@@ -360,7 +395,7 @@ def test_filter_not_published_product_published_tomorrow(product, channel_USD):
channel_listing.published_at = date_tomorrow
channel_listing.save(update_fields=["is_published", "published_at"])
- available_products = models.Product.objects.not_published(channel_USD.slug)
+ available_products = models.Product.objects.not_published(channel_USD)
assert available_products.count() == 1
@@ -371,12 +406,12 @@ def test_filter_not_published_product_not_published_tomorrow(product, channel_US
channel_listing.published_at = date_tomorrow
channel_listing.save(update_fields=["is_published", "published_at"])
- available_products = models.Product.objects.not_published(channel_USD.slug)
+ available_products = models.Product.objects.not_published(channel_USD)
assert available_products.count() == 1
def test_filter_not_published_product_is_published(product, channel_USD):
- available_products = models.Product.objects.not_published(channel_USD.slug)
+ available_products = models.Product.objects.not_published(channel_USD)
assert available_products.count() == 0
@@ -387,18 +422,18 @@ def test_filter_not_published_product_is_unpublished_other_channel(
product=product, channel=channel_PLN, is_published=False
)
- available_products_usd = models.Product.objects.not_published(channel_USD.slug)
+ available_products_usd = models.Product.objects.not_published(channel_USD)
assert available_products_usd.count() == 0
- available_products_pln = models.Product.objects.not_published(channel_PLN.slug)
+ available_products_pln = models.Product.objects.not_published(channel_PLN)
assert available_products_pln.count() == 1
def test_filter_not_published_product_without_assigned_channel(
product, channel_USD, channel_PLN
):
- not_available_products_usd = models.Product.objects.not_published(channel_USD.slug)
+ not_available_products_usd = models.Product.objects.not_published(channel_USD)
assert not_available_products_usd.count() == 0
- not_available_products_pln = models.Product.objects.not_published(channel_PLN.slug)
+ not_available_products_pln = models.Product.objects.not_published(channel_PLN)
assert not_available_products_pln.count() == 1