Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor product resolver/Add unit tests
Damian W6c453540c08b
diff --git a/saleor/graphql/core/tests/test_graphql.py b/saleor/graphql/core/tests/test_graphql.pyindex 6545a12bd0..b0674a595e 100644--- a/saleor/graphql/core/tests/test_graphql.py+++ b/saleor/graphql/core/tests/test_graphql.py@@ -86,7 +86,7 @@ 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}, channel: $channel) {...ProductListFragmentQuery__typenamediff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.pyindex bf6620546e..56213b5368 100644--- a/saleor/graphql/product/dataloaders/__init__.py+++ b/saleor/graphql/product/dataloaders/__init__.py@@ -5,7 +5,7 @@ from .attributes import (VariantAttributesByProductTypeIdLoader,)from .products import (- AvailableProductVariantsByProductVariantId,+ AvailableProductVariantsByProductVariantIdAndChannel,CategoryByIdLoader,CollectionByIdLoader,CollectionChannelListingByCollectionIdAndChannelSlugLoader,@@ -63,5 +63,5 @@ __all__ = ["VariantChannelListingByVariantIdAndChannelIdLoader","VariantChannelListingByVariantIdLoader","VariantsChannelListingByProductIdAndChannelSlugLoader",- "AvailableProductVariantsByProductVariantId",+ "AvailableProductVariantsByProductVariantIdAndChannel",]diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.pyindex f347c57acc..ce7f398d02 100644--- a/saleor/graphql/product/dataloaders/products.py+++ b/saleor/graphql/product/dataloaders/products.py@@ -166,18 +166,22 @@ class ProductVariantsByProductIdLoader(DataLoader):return [variant_map.get(product_id, []) for product_id in keys]-class AvailableProductVariantsByProductVariantId(+class AvailableProductVariantsByProductVariantIdAndChannel(DataLoader[VariantIdAndChannelSlug, ProductVariantChannelListing]):context_key = "available_productvariant_by_variant_and_channel"field = "slug"def batch_load(self, keys):+ # Split the list of keys by channel first. A typical query will only touch+ # a handful of unique countries but may access thousands of product variants+ # so it's cheaper to execute one query per channel.available_variants_by_channel: DefaultDict[str, List[int]] = defaultdict(list)- for channel, variants in keys:+ for variants, channel in keys:+ # For each channel execute a single query for all product variants.available_variants = self.batch_load_available(channel, variants)available_variants_by_channel[channel] = available_variants- return [available_variants_by_channel[key] for key, _ in keys]+ return [available_variants_by_channel[key] for _, key in keys]def batch_load_available(self, channel: str, variant_ids: Iterable[int]@@ -187,12 +191,11 @@ class AvailableProductVariantsByProductVariantId("variant_id__in": variant_ids,"price_amount__isnull": False,}- variant_channel_listings = ProductVariantChannelListing.objects.filter(**filter)+ available_variants = ProductVariantChannelListing.objects.filter(+ **filter+ ).values_list("variant__id", flat=True)- return [- variant_channel_listing.variant_id- for variant_channel_listing in variant_channel_listings.iterator()- ]+ return list(available_variants)class ProductVariantChannelListingByIdLoader(DataLoader):@@ -322,7 +325,9 @@ class VariantsChannelListingByProductIdAndChannelSlugLoader(self, channel_slug: str, products_ids: Iterable[int]) -> Iterable[Tuple[int, Optional[List[ProductVariantChannelListing]]]]:variants_channel_listings = ProductVariantChannelListing.objects.filter(- channel__slug=channel_slug, variant__product_id__in=products_ids+ channel__slug=channel_slug,+ variant__product_id__in=products_ids,+ price_amount__isnull=False,).annotate(product_id=F("variant__product_id"))variants_channel_listings_map: Dict[diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex a03905b71c..f371423276 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -61,9 +61,7 @@ def _clean_product_attributes_filter_input(T_PRODUCT_FILTER_QUERIES = Dict[int, Iterable[int]]-def filter_products_by_attributes_values(- qs, queries: T_PRODUCT_FILTER_QUERIES, channel_slug-):+def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):filters = [Q(Exists(@@ -85,22 +83,22 @@ def filter_products_by_attributes_values(return qs.filter(*filters)-def filter_products_by_attributes(qs, filter_value, channel_slug):+def filter_products_by_attributes(qs, filter_value):queries = _clean_product_attributes_filter_input(filter_value)- return filter_products_by_attributes_values(qs, queries, channel_slug)+ return filter_products_by_attributes_values(qs, queries)def filter_products_by_variant_price(qs, channel_slug, price_lte=None, price_gte=None):if price_lte:qs = qs.filter(- variants__channel_listings__price_amount__lte=price_lte,- variants__channel_listings__price_amount__isnull=False,+ Q(variants__channel_listings__price_amount__lte=price_lte)+ | Q(variants__channel_listings__price_amount__isnull=True),variants__channel_listings__channel__slug=channel_slug,)if price_gte:qs = qs.filter(- variants__channel_listings__price_amount__gte=price_gte,- variants__channel_listings__price_amount__isnull=False,+ Q(variants__channel_listings__price_amount__gte=price_gte)+ | Q(variants__channel_listings__price_amount__isnull=True),variants__channel_listings__channel__slug=channel_slug,)return qs@@ -136,7 +134,7 @@ def filter_products_by_collections(qs, collections):return qs.filter(collections__in=collections)-def filter_products_by_stock_availability(qs, stock_availability, channel_slug=None):+def filter_products_by_stock_availability(qs, stock_availability):total_stock = (Stock.objects.select_related("product_variant").values("product_variant__product_id")@@ -147,8 +145,6 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug=N.annotate(total_available=F("total_quantity") - F("total_quantity_allocated")).filter(total_available__lte=0,- product_variant__channel_listings__channel__slug=channel_slug,- product_variant__channel_listings__price_amount__isnull=False,).values_list("product_variant__product_id", flat=True))@@ -159,14 +155,14 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug=Nreturn qs-def _filter_attributes(qs, _, value, channel_slug):+def _filter_attributes(qs, _, value):if value:value_list = []for v in value:slug = v["slug"]values = [v["value"]] if "value" in v else v.get("values", [])value_list.append((slug, values))- qs = filter_products_by_attributes(qs, value_list, channel_slug)+ qs = filter_products_by_attributes(qs, value_list)return qs@@ -212,9 +208,9 @@ def _filter_minimal_price(qs, _, value, channel_slug):return qs-def _filter_stock_availability(qs, _, value, channel_slug):+def _filter_stock_availability(qs, _, value):if value:- qs = filter_products_by_stock_availability(qs, value, channel_slug)+ qs = filter_products_by_stock_availability(qs, value)return qs@@ -358,12 +354,10 @@ class ProductFilter(django_filters.FilterSet):]def filter_attributes(self, queryset, name, value):- channel_slug = get_channel_slug_from_filter_data(self.data)- return _filter_attributes(queryset, name, value, channel_slug)+ return _filter_attributes(queryset, name, value)def filter_stock_availability(self, queryset, name, value):- channel_slug = get_channel_slug_from_filter_data(self.data)- return _filter_stock_availability(queryset, name, value, channel_slug)+ return _filter_stock_availability(queryset, name, value)def filter_variant_price(self, queryset, name, value):channel_slug = get_channel_slug_from_filter_data(self.data)diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex d238b03a74..b3dd344025 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -96,6 +96,9 @@ def resolve_variant_by_id(requestor, channel_slug, requestor_has_access_to_all)qs = models.ProductVariant.objects.filter(product__in=visible_products)+ if not requestor_has_access_to_all:+ qs = qs.available_in_channel(channel_slug)+return qs.filter(pk=id).first()@@ -109,11 +112,10 @@ def resolve_product_variant_by_sku(visible_products = _return_visible_product(requestor, channel_slug, requestor_has_access_to_all)- return (- models.ProductVariant.objects.filter(product__in=visible_products)- .filter(sku=sku)- .first()- )+ qs = models.ProductVariant.objects.filter(product__in=visible_products)+ if not requestor_has_access_to_all:+ qs = qs.available_in_channel(channel_slug)+ return qs.filter(sku=sku).first()def resolve_product_variants(@@ -124,6 +126,8 @@ def resolve_product_variants()qs = models.ProductVariant.objects.filter(product__in=visible_products)+ if not requestor_has_access_to_all:+ qs = qs.available_in_channel(channel_slug=channel_slug)if ids:db_ids = [get_database_id(info, node_id, "ProductVariant") for node_id in ids]qs = qs.filter(pk__in=db_ids)diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex f1f65c765e..f7f309e58e 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -1719,9 +1719,8 @@ def test_products_with_variants_query_as_app(@pytest.mark.parametrize("products_filter",[- {"price": {"gte": 1.0, "lte": 2.0}},- {"minimalPrice": {"gte": 1.0, "lte": 2.0}},- {"isPublished": False},+ {"minimalPrice": {"gte": 1.0, "lte": 2.0}, "channel": "main"},+ {"isPublished": False, "channel": "main"},{"search": "Juice1"},],)@@ -1753,10 +1752,11 @@ def test_products_query_with_filter()ProductChannelListing.objects.create(product=second_product,+ discounted_price_amount=Decimal(1.99),channel=channel_USD,- is_published=True,+ is_published=False,)- variables = {"filter": {"search": "Juice1"}, "channel": channel_USD.slug}+ 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)@@ -1768,6 +1768,53 @@ def test_products_query_with_filter(assert products[0]["node"]["name"] == second_product.name+def test_products_query_with_price_filter_as_staff(+ query_products_with_filter,+ staff_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+):+ product = product_list[0]+ product.variants.first().channel_listings.filter().update(price_amount=None)++ variables = {+ "filter": {"price": {"gte": 9, "lte": 31}, "channel": channel_USD.slug},+ "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)+ products = content["data"]["products"]["edges"]++ assert len(products) == 3+++def test_products_query_with_price_filter_as_user(+ query_products_with_filter,+ user_api_client,+ product_list,+ permission_manage_products,+ channel_USD,+):+ product = product_list[0]+ product.variants.first().channel_listings.filter().update(price_amount=None)+ 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},+ "channel": channel_USD.slug,+ }+ user_api_client.user.user_permissions.add(permission_manage_products)+ response = user_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 2+ assert products[0]["node"]["id"] == second_product_id+ assert products[1]["node"]["id"] == third_product_id++@pytest.mark.parametrize("is_published", [(True), (False)])def test_products_query_with_filter_search_by_sku(is_published,@@ -1793,30 +1840,70 @@ def test_products_query_with_filter_search_by_sku(assert products[0]["node"]["name"] == product_with_default_variant.name-def test_products_query_with_filter_stock_availability(+def test_products_query_with_filter_stock_availability_as_staff(query_products_with_filter,staff_api_client,- product,+ product_list,order_line,permission_manage_products,channel_USD,):- stock = product.variants.first().stocks.first()- Allocation.objects.create(- order_line=order_line, stock=stock, quantity_allocated=stock.quantity++ for product in product_list:+ stock = product.variants.first().stocks.first()+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity+ )+ product = product_list[0]+ product.variants.first().channel_listings.filter(channel=channel_USD).update(+ price_amount=None)+variables = {"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)content = get_graphql_content(response)- product_id = graphene.Node.to_global_id("Product", product.id)products = content["data"]["products"]["edges"]- assert len(products) == 1+ assert len(products) == 3+++def test_products_query_with_filter_stock_availability_as_user(+ query_products_with_filter,+ user_api_client,+ product_list,+ order_line,+ permission_manage_products,+ channel_USD,+):++ for product in product_list:+ stock = product.variants.first().stocks.first()+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity+ )+ product = product_list[0]+ product.variants.first().channel_listings.filter(channel=channel_USD).update(+ price_amount=None+ )+ variables = {+ "filter": {"stockAvailability": "OUT_OF_STOCK", "channel": channel_USD.slug},+ "channel": channel_USD.slug,+ }+ response = user_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ product_id = graphene.Node.to_global_id("Product", product_list[1].id)+ second_product_id = graphene.Node.to_global_id("Product", product_list[2].id)++ products = content["data"]["products"]["edges"]++ assert len(products) == 2assert products[0]["node"]["id"] == product_id- assert products[0]["node"]["name"] == product.name+ assert products[0]["node"]["name"] == product_list[1].name+ assert products[1]["node"]["id"] == second_product_id+ assert products[1]["node"]["name"] == product_list[2].name@pytest.mark.parametrize(@@ -2078,10 +2165,91 @@ def test_filter_products_by_wrong_attributes(user_api_client, product, channel_Uassert products == []+def test_filter_products_with_unavailable_variants_attributes_as_user(+ user_api_client, product_list, channel_USD+):+ product_attr = product_list[0].product_type.product_attributes.first()+ attr_value = product_attr.values.first()++ query = """+ query Products($attributesFilter: [AttributeInput], $channel: String) {+ products(+ first: 5,+ filter: {attributes: $attributesFilter,channel: $channel},+ channel: $channel+ ) {+ edges {+ node {+ id+ }+ }+ }+ }+ """+ 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 = {+ "channel": channel_USD.slug,+ "attributesFilter": [+ {"slug": f"{product_attr.slug}", "value": f"{attr_value.slug}"}+ ],+ }+ product_list[0].variants.first().channel_listings.filter(+ channel=channel_USD+ ).update(price_amount=None)++ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 2+ assert products[0]["node"]["id"] == second_product_id+ assert products[1]["node"]["id"] == third_product_id+++def test_filter_products_with_unavailable_variants_attributes_as_staff(+ staff_api_client, product_list, channel_USD+):+ product_attr = product_list[0].product_type.product_attributes.first()+ attr_value = product_attr.values.first()++ query = """+ query Products($attributesFilter: [AttributeInput], $channel: String) {+ products(+ first: 5,+ filter: {attributes: $attributesFilter,channel: $channel},+ channel: $channel+ ) {+ edges {+ node {+ name+ }+ }+ }+ }+ """++ variables = {+ "channel": channel_USD.slug,+ "attributesFilter": [+ {"slug": f"{product_attr.slug}", "value": f"{attr_value.slug}"}+ ],+ }+ product_list[0].variants.first().channel_listings.filter(+ channel=channel_USD+ ).update(price_amount=None)++ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 3++SORT_PRODUCTS_QUERY = """query ($channel:String) {products (- sortBy: %(sort_by_product_order)s, first: 2, channel: $channel+ sortBy: %(sort_by_product_order)s, first: 3, channel: $channel) {edges {node {@@ -2135,7 +2303,22 @@ def test_sort_products(user_api_client, product, channel_USD):cost_price_amount=Decimal(2),currency=channel_USD.currency_code,)-+ product.pk = None+ product.slug = "third-product"+ product.updated_at = datetime.utcnow()+ product.save()+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ visible_in_listings=True,+ )+ variant_second = ProductVariant.objects.create(product=product, sku="12345")+ ProductVariantChannelListing.objects.create(+ variant=variant_second,+ channel=channel_USD,+ currency=channel_USD.currency_code,+ )variables = {"channel": channel_USD.slug}query = SORT_PRODUCTS_QUERY@@ -2145,6 +2328,7 @@ def test_sort_products(user_api_client, product, channel_USD):response = user_api_client.post_graphql(asc_price_query, variables)content = get_graphql_content(response)edges = content["data"]["products"]["edges"]+ assert len(edges) == 2price1 = edges[0]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"]["amount"]@@ -2204,6 +2388,79 @@ def test_sort_products(user_api_client, product, channel_USD):assert parse_datetime(date_0) > parse_datetime(date_1)+def test_sort_products_by_price_as_staff(staff_api_client, product, channel_USD):+ product.updated_at = datetime.utcnow()+ product.save()++ product.pk = None+ product.slug = "second-product"+ product.updated_at = datetime.utcnow()+ product.save()+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ visible_in_listings=True,+ )+ variant = ProductVariant.objects.create(product=product, sku="1234")+ ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ price_amount=Decimal(20),+ cost_price_amount=Decimal(2),+ currency=channel_USD.currency_code,+ )+ product.pk = None+ product.slug = "third-product"+ product.updated_at = datetime.utcnow()+ product.save()+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ visible_in_listings=True,+ )+ variant_second = ProductVariant.objects.create(product=product, sku="12345")+ ProductVariantChannelListing.objects.create(+ variant=variant_second,+ channel=channel_USD,+ currency=channel_USD.currency_code,+ )+ variables = {"channel": channel_USD.slug}+ query = SORT_PRODUCTS_QUERY++ # Test sorting by PRICE, ascending+ sort_by = f'{{field: PRICE, direction: ASC, channel: "{channel_USD.slug}"}}'+ 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)+ edges = content["data"]["products"]["edges"]+ assert len(edges) == 3+ price1 = edges[0]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"][+ "amount"+ ]+ price2 = edges[1]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"][+ "amount"+ ]+ assert edges[2]["node"]["pricing"] is None+ assert price1 < price2++ # Test sorting by PRICE, descending+ sort_by = f'{{field: PRICE, direction:DESC, channel: "{channel_USD.slug}"}}'+ 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)+ edges = content["data"]["products"]["edges"]+ price1 = edges[1]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"][+ "amount"+ ]+ price2 = edges[2]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"][+ "amount"+ ]+ assert edges[0]["node"]["pricing"] is None+ assert price1 > price2++def test_sort_products_product_type_name(user_api_client, product, product_with_default_variant, channel_USD):@@ -6454,6 +6711,86 @@ def test_unavailable_product_by_id_as_user(user_api_client, product, channel_USDassert content["data"]["product"] is None+def test_product_without_variant_price_by_id_as_user(+ user_api_client, product, channel_USD+):+ query = """+ query getProduct($id: ID!, $channel: String) {+ product(id: $id, channel: $channel) {+ id+ name+ }+ }+ """+ variant_channel_listing = (+ product.variants.first()+ .channel_listings.filter(channel__slug=channel_USD.slug)+ .first()+ )+ variant_channel_listing.price_amount = None+ variant_channel_listing.save()+ product_id = graphene.Node.to_global_id("Product", product.id)++ variables = {"id": product_id, "channel": channel_USD.slug}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert content["data"]["product"] is None+++def test_product_without_variant_price_by_id_as_staff(+ staff_api_client, product, channel_USD+):+ query = """+ query getProduct($id: ID!, $channel: String) {+ product(id: $id, channel: $channel) {+ id+ name+ }+ }+ """+ variant_channel_listing = (+ product.variants.first()+ .channel_listings.filter(channel__slug=channel_USD.slug)+ .first()+ )+ variant_channel_listing.price_amount = None+ variant_channel_listing.save()+ product_id = graphene.Node.to_global_id("Product", product.id)++ variables = {"id": product_id, "channel": channel_USD.slug}+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["product"]+ assert data["id"] == product_id+++def test_product_without_variant_price_by_id_as_app(+ app_api_client, product, channel_USD+):+ query = """+ query getProduct($id: ID!, $channel: String) {+ product(id: $id, channel: $channel) {+ id+ name+ }+ }+ """+ variant_channel_listing = (+ product.variants.first()+ .channel_listings.filter(channel__slug=channel_USD.slug)+ .first()+ )+ variant_channel_listing.price_amount = None+ variant_channel_listing.save()+ product_id = graphene.Node.to_global_id("Product", product.id)++ variables = {"id": product_id, "channel": channel_USD.slug}+ response = app_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["product"]+ assert data["id"] == product_id++def test_unavailable_product_by_slug_as_staff(staff_api_client, product, channel_USD):query = """query getProduct($slug: String!, $channel: String) {@@ -6521,8 +6858,75 @@ def test_unavailable_product_by_slug_as_user(user_api_client, product, channel_Uassert content["data"]["product"] is None-def test_unavailable_product_variant_by_id_as_staff(- staff_api_client, variant, channel_USD+def test_product_without_variant_price_by_slug_as_user(+ user_api_client, product, channel_USD+):+ query = """+ query getProduct($slug: String!, $channel: String) {+ product(slug: $slug, channel: $channel) {+ id+ name+ }+ }+ """+ variant = product.variants.first()+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)++ variables = {"slug": product.slug, "channel": channel_USD.slug}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert content["data"]["product"] is None+++def test_product_without_variant_price_by_slug_as_staff(+ staff_api_client, product, channel_USD+):+ query = """+ query getProduct($slug: String!, $channel: String) {+ product(slug: $slug, channel: $channel) {+ id+ name+ }+ }+ """+ variant = product.variants.first()+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ product_id = graphene.Node.to_global_id("Product", product.id)++ variables = {"slug": product.slug, "channel": channel_USD.slug}+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["product"]+ assert data["id"] == product_id+++def test_product_without_variant_price_by_slug_as_app(+ staff_api_client, product, channel_USD+):+ query = """+ query getProduct($slug: String!, $channel: String) {+ product(slug: $slug, channel: $channel) {+ id+ name+ }+ }+ """+ variant = product.variants.first()+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ product_id = graphene.Node.to_global_id("Product", product.id)++ variables = {"slug": product.slug, "channel": channel_USD.slug}+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["product"]+ assert data["id"] == product_id+++def test_unavailable_product_variant_by_id_as_staff(+ staff_api_client, variant, channel_USD):query = """query getProductVariant($id: ID!, $channel: String) {@@ -6580,11 +6984,8 @@ def test_unavailable_product_variant_by_id_as_user(}}"""- product_channel_listing = variant.product.channel_listings.filter(- channel__slug=channel_USD.slug- ).first()- product_channel_listing.visible_in_listings = False- product_channel_listing.save()+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)variables = {"id": variant_id, "channel": channel_USD.slug}@@ -6593,6 +6994,134 @@ def test_unavailable_product_variant_by_id_as_user(assert content["data"]["productVariant"] is None+def test_product_variant_without_price_by_id_as_user(+ user_api_client, variant, channel_USD+):+ query = """+ query getProductVariant($id: ID!, $channel: String) {+ productVariant(id: $id, channel: $channel) {+ id+ name+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"id": variant_id, "channel": channel_USD.slug}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert content["data"]["productVariant"] is None+++def test_product_variant_without_price_by_id_as_staff(+ staff_api_client, variant, channel_USD+):+ query = """+ query getProductVariant($id: ID!, $channel: String) {+ productVariant(id: $id, channel: $channel) {+ id+ name+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"id": variant_id, "channel": channel_USD.slug}+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariant"]+ assert data["id"] == variant_id+++def test_product_variant_without_price_by_id_as_app(+ app_api_client, variant, channel_USD+):+ query = """+ query getProductVariant($id: ID!, $channel: String) {+ productVariant(id: $id, channel: $channel) {+ id+ name+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"id": variant_id, "channel": channel_USD.slug}+ response = app_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariant"]+ assert data["id"] == variant_id+++def test_product_variant_without_price_sku_as_app(app_api_client, variant, channel_USD):+ query = """+ query getProductVariant($sku: String!, $channel: String) {+ productVariant(sku: $sku, channel: $channel) {+ id+ name+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"sku": variant.sku, "channel": channel_USD.slug}+ response = app_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariant"]+ assert data["id"] == variant_id+++def test_product_variant_without_price_sku_as_staff(+ staff_api_client, variant, channel_USD+):+ query = """+ query getProductVariant($sku: String!, $channel: String) {+ productVariant(sku: $sku, channel: $channel) {+ id+ name+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"sku": variant.sku, "channel": channel_USD.slug}+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariant"]+ assert data["id"] == variant_id+++def test_product_variant_without_price_sku_as_user(+ user_api_client, variant, channel_USD+):+ query = """+ query getProductVariant($sku: String!, $channel: String) {+ productVariant(sku: $sku, channel: $channel) {+ id+ name+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)++ variables = {"sku": variant.sku, "channel": channel_USD.slug}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert content["data"]["productVariant"] is None++def test_product_variants_by_ids(staff_api_client, variant, channel_USD):query = """query getProduct($ids: [ID!], $channel: String) {@@ -6629,6 +7158,113 @@ def test_product_variants_by_ids(staff_api_client, variant, channel_USD):assert len(data["edges"]) == 1+def test_product_variants_without_price_by_ids_as_staff(+ staff_api_client, variant, channel_USD+):+ query = """+ query getProduct($ids: [ID!], $channel: String) {+ productVariants(ids: $ids, first: 1, channel: $channel) {+ edges {+ node {+ id+ name+ sku+ channelListings {+ channel {+ id+ isActive+ name+ currencyCode+ }+ price {+ amount+ currency+ }+ }+ }+ }+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"ids": [variant_id], "channel": channel_USD.slug}+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariants"]+ assert data["edges"][0]["node"]["id"] == variant_id+ assert len(data["edges"]) == 1+++def test_product_variants_without_price_by_ids_as_user(+ user_api_client, variant, channel_USD+):+ query = """+ query getProduct($ids: [ID!], $channel: String) {+ productVariants(ids: $ids, first: 1, channel: $channel) {+ edges {+ node {+ id+ name+ sku+ }+ }+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"ids": [variant_id], "channel": channel_USD.slug}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariants"]+ assert len(data["edges"]) == 0+++def test_product_variants_without_price_by_ids_as_app(+ app_api_client, variant, channel_USD+):+ query = """+ query getProduct($ids: [ID!], $channel: String) {+ productVariants(ids: $ids, first: 1, channel: $channel) {+ edges {+ node {+ id+ name+ sku+ channelListings {+ channel {+ id+ isActive+ name+ currencyCode+ }+ price {+ amount+ currency+ }+ }+ }+ }+ }+ }+ """+ variant.channel_listings.all().delete()+ variant.channel_listings.create(channel=channel_USD)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"ids": [variant_id], "channel": channel_USD.slug}+ response = app_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["productVariants"]+ assert data["edges"][0]["node"]["id"] == variant_id+ assert len(data["edges"]) == 1++def test_product_variants_by_customer(user_api_client, variant, channel_USD):query = """query getProduct($ids: [ID!], $channel: String) {@@ -6726,6 +7362,88 @@ def test_product_variant_price(assert variant_price["amount"] == api_variant_price+def test_product_variant_without_price_as_user(+ user_api_client,+ variant,+ stock,+ channel_USD,+):+ variant.channel_listings.filter(channel=channel_USD).update(price_amount=None)++ query = """+ query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {+ product(id: $id, channel: $channel) {+ variants {+ id+ pricing(address: $address) {+ priceUndiscounted {+ gross {+ amount+ }+ }+ }+ }+ }+ }+ """+ product_id = graphene.Node.to_global_id("Product", variant.product.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {+ "id": product_id,+ "channel": channel_USD.slug,+ "address": {"country": "US"},+ }++ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ variants_data = content["data"]["product"]["variants"]+ assert not variants_data[0]["id"] == variant_id+ assert len(variants_data) == 1+++def test_product_variant_without_price_as_staff(+ staff_api_client,+ variant,+ stock,+ channel_USD,+):+ product = variant.product+ ProductVariantChannelListing.objects.filter(+ channel=channel_USD, variant__product_id=product.pk+ ).update(price_amount=None)++ query = """+ query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {+ product(id: $id, channel: $channel) {+ variants {+ id+ pricing(address: $address) {+ priceUndiscounted {+ gross {+ amount+ }+ }+ }+ }+ }+ }+ """+ product_id = graphene.Node.to_global_id("Product", variant.product.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {+ "id": product_id,+ "channel": channel_USD.slug,+ "address": {"country": "US"},+ }+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ variants_data = content["data"]["product"]["variants"]+ assert variants_data[1]["id"] == variant_id+ assert variants_data[1]["pricing"] is None+ assert len(variants_data) == 2++QUERY_REPORT_PRODUCT_SALES = """query TopProducts($period: ReportingPeriod!, $channel: String!) {reportProductSales(period: $period, first: 20, channel: $channel) {diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex ce79b49c82..0b93754de8 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -53,7 +53,9 @@ from ...order.dataloaders import (OrderByIdLoader,OrderLinesByVariantIdAndChannelIdLoader,)-from ...product.dataloaders.products import AvailableProductVariantsByProductVariantId+from ...product.dataloaders.products import (+ AvailableProductVariantsByProductVariantIdAndChannel,+)from ...translations.fields import TranslationFieldfrom ...translations.types import (CategoryTranslation,@@ -733,16 +735,18 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):requestor = get_user_or_app_from_context(info.context)is_staff = requestor_is_staff_member_or_app(requestor)- def return_available_variants_in_channel(variants):+ def return_available_variants(variants):if is_staff:return variantsvariants_id = (variant.id for variant in variants)- variant_channel_listings = AvailableProductVariantsByProductVariantId(- info.context- ).load((root.channel_slug, variants_id))+ available_variants_in_channel = (+ AvailableProductVariantsByProductVariantIdAndChannel(info.context).load(+ (variants_id, root.channel_slug)+ )+ )- def return_available_variants(available_variants):+ def return_available_variants_in_channel(available_variants):result = []variants_map = {variant.id: variant for variant in variants}for variant_id in variants_map.keys() & available_variants:@@ -751,7 +755,9 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):result.append(variant)return result- return variant_channel_listings.then(return_available_variants)+ return available_variants_in_channel.then(+ return_available_variants_in_channel+ )def map_channel_context(variants):return [@@ -762,7 +768,7 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return (ProductVariantsByProductIdLoader(info.context).load(root.node.id)- .then(return_available_variants_in_channel)+ .then(return_available_variants).then(map_channel_context))diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.pyindex bfa38826af..205529ac42 100644--- a/saleor/product/tests/test_product.py+++ b/saleor/product/tests/test_product.py@@ -65,34 +65,26 @@ def test_filtering_by_attribute(product_qs = models.Product.objects.all().values_list("pk", flat=True)filters = {color_attribute.pk: [color.pk]}- filtered = filter_products_by_attributes_values(- product_qs, filters, channel_USD.slug- )+ filtered = filter_products_by_attributes_values(product_qs, filters)assert product_a.pk in list(filtered)assert product_b.pk in list(filtered)associate_attribute_values_to_instance(product_a, color_attribute, color_2)filters = {color_attribute.pk: [color.pk]}- filtered = filter_products_by_attributes_values(- product_qs, filters, channel_USD.slug- )+ filtered = filter_products_by_attributes_values(product_qs, filters)assert product_a.pk not in list(filtered)assert product_b.pk in list(filtered)filters = {color_attribute.pk: [color_2.pk]}- filtered = filter_products_by_attributes_values(- product_qs, filters, channel_USD.slug- )+ filtered = filter_products_by_attributes_values(product_qs, filters)assert product_a.pk in list(filtered)assert product_b.pk not in list(filtered)# Filter by multiple values, should trigger a OR conditionfilters = {color_attribute.pk: [color.pk, color_2.pk]}- filtered = filter_products_by_attributes_values(- product_qs, filters, channel_USD.slug- )+ filtered = filter_products_by_attributes_values(product_qs, filters)assert product_a.pk in list(filtered)assert product_b.pk in list(filtered)@@ -103,9 +95,7 @@ def test_filtering_by_attribute(# Filter by multiple attributesfilters = {color_attribute.pk: [color_2.pk], size_attribute.pk: [size.pk]}- filtered = filter_products_by_attributes_values(- product_qs, filters, channel_USD.slug- )+ filtered = filter_products_by_attributes_values(product_qs, filters)assert product_a.pk in list(filtered)