Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Update product variant resolver
Damian W52a797b00af3
diff --git a/saleor/graphql/core/tests/test_graphql.py b/saleor/graphql/core/tests/test_graphql.pyindex 95c201e5ec..6545a12bd0 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) {+ attributes: $attributesFilter,channel: $channel}, channel: $channel) {...ProductListFragmentQuery__typenamediff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.pyindex f20074511a..bf6620546e 100644--- a/saleor/graphql/product/dataloaders/__init__.py+++ b/saleor/graphql/product/dataloaders/__init__.py@@ -5,6 +5,7 @@ from .attributes import (VariantAttributesByProductTypeIdLoader,)from .products import (+ AvailableProductVariantsByProductVariantId,CategoryByIdLoader,CollectionByIdLoader,CollectionChannelListingByCollectionIdAndChannelSlugLoader,@@ -29,7 +30,7 @@ from .products import (VariantChannelListingByVariantIdAndChannelIdLoader,VariantChannelListingByVariantIdAndChannelSlugLoader,VariantChannelListingByVariantIdLoader,- VariantsChannelListingByProductIdAndChanneSlugLoader,+ VariantsChannelListingByProductIdAndChannelSlugLoader,)__all__ = [@@ -61,5 +62,6 @@ __all__ = ["VariantChannelListingByVariantIdAndChannelSlugLoader","VariantChannelListingByVariantIdAndChannelIdLoader","VariantChannelListingByVariantIdLoader",- "VariantsChannelListingByProductIdAndChanneSlugLoader",+ "VariantsChannelListingByProductIdAndChannelSlugLoader",+ "AvailableProductVariantsByProductVariantId",]diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.pyindex fa04e372f8..f347c57acc 100644--- a/saleor/graphql/product/dataloaders/products.py+++ b/saleor/graphql/product/dataloaders/products.py@@ -166,6 +166,35 @@ class ProductVariantsByProductIdLoader(DataLoader):return [variant_map.get(product_id, []) for product_id in keys]+class AvailableProductVariantsByProductVariantId(+ DataLoader[VariantIdAndChannelSlug, ProductVariantChannelListing]+):+ context_key = "available_productvariant_by_variant_and_channel"+ field = "slug"++ def batch_load(self, keys):+ available_variants_by_channel: DefaultDict[str, List[int]] = defaultdict(list)+ for channel, variants in keys:+ 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]++ def batch_load_available(+ self, channel: str, variant_ids: Iterable[int]+ ) -> Iterable[int]:+ filter = {+ f"channel__{self.field}": channel,+ "variant_id__in": variant_ids,+ "price_amount__isnull": False,+ }+ variant_channel_listings = ProductVariantChannelListing.objects.filter(**filter)++ return [+ variant_channel_listing.variant_id+ for variant_channel_listing in variant_channel_listings.iterator()+ ]++class ProductVariantChannelListingByIdLoader(DataLoader):context_key = "productvariantchannelisting_by_id"@@ -224,7 +253,11 @@ class VariantChannelListingByVariantIdAndChannelLoader(def batch_load_channel(self, channel: str, variant_ids: Iterable[int]) -> Iterable[Tuple[int, Optional[ProductVariantChannelListing]]]:- filter = {f"channel__{self.field}": channel, "variant_id__in": variant_ids}+ filter = {+ f"channel__{self.field}": channel,+ "variant_id__in": variant_ids,+ "price_amount__isnull": False,+ }variant_channel_listings = ProductVariantChannelListing.objects.filter(**filter)variant_channel_listings_map: Dict[int, ProductVariantChannelListing] = {}@@ -253,7 +286,7 @@ class VariantChannelListingByVariantIdAndChannelIdLoader(field = "id"-class VariantsChannelListingByProductIdAndChanneSlugLoader(+class VariantsChannelListingByProductIdAndChannelSlugLoader(DataLoader[ProductIdAndChannelSlug, Iterable[ProductVariantChannelListing]]):context_key = "variantschannelisting_by_product_and_channel"diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex aa3c809636..a03905b71c 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -61,7 +61,9 @@ 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):+def filter_products_by_attributes_values(+ qs, queries: T_PRODUCT_FILTER_QUERIES, channel_slug+):filters = [Q(Exists(@@ -80,24 +82,25 @@ def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):)for values in queries.values()]-return qs.filter(*filters)-def filter_products_by_attributes(qs, filter_value):+def filter_products_by_attributes(qs, filter_value, channel_slug):queries = _clean_product_attributes_filter_input(filter_value)- return filter_products_by_attributes_values(qs, queries)+ return filter_products_by_attributes_values(qs, queries, channel_slug)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,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,variants__channel_listings__channel__slug=channel_slug,)return qs@@ -109,11 +112,13 @@ def filter_products_by_minimal_price(if minimal_price_lte:qs = qs.filter(channel_listings__discounted_price_amount__lte=minimal_price_lte,+ channel_listings__discounted_price_amount__isnull=False,channel_listings__channel__slug=channel_slug,)if minimal_price_gte:qs = qs.filter(channel_listings__discounted_price_amount__gte=minimal_price_gte,+ channel_listings__discounted_price_amount__isnull=False,channel_listings__channel__slug=channel_slug,)return qs@@ -131,7 +136,7 @@ def filter_products_by_collections(qs, collections):return qs.filter(collections__in=collections)-def filter_products_by_stock_availability(qs, stock_availability):+def filter_products_by_stock_availability(qs, stock_availability, channel_slug=None):total_stock = (Stock.objects.select_related("product_variant").values("product_variant__product_id")@@ -140,7 +145,11 @@ def filter_products_by_stock_availability(qs, stock_availability):).annotate(total_quantity=Coalesce(Sum("quantity"), 0)).annotate(total_available=F("total_quantity") - F("total_quantity_allocated"))- .filter(total_available__lte=0)+ .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))if stock_availability == StockAvailability.IN_STOCK:@@ -150,14 +159,14 @@ def filter_products_by_stock_availability(qs, stock_availability):return qs-def filter_attributes(qs, _, value):+def _filter_attributes(qs, _, value, channel_slug):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)+ qs = filter_products_by_attributes(qs, value_list, channel_slug)return qs@@ -203,9 +212,9 @@ def _filter_minimal_price(qs, _, value, channel_slug):return qs-def filter_stock_availability(qs, _, value):+def _filter_stock_availability(qs, _, value, channel_slug):if value:- qs = filter_products_by_stock_availability(qs, value)+ qs = filter_products_by_stock_availability(qs, value, channel_slug)return qs@@ -323,10 +332,10 @@ class ProductFilter(django_filters.FilterSet):)attributes = ListObjectTypeFilter(input_class="saleor.graphql.attribute.types.AttributeInput",- method=filter_attributes,+ method="filter_attributes",)stock_availability = EnumFilter(- input_class=StockAvailability, method=filter_stock_availability+ input_class=StockAvailability, method="filter_stock_availability")product_type = GlobalIDFilter() # Deprecatedproduct_types = GlobalIDMultipleChoiceFilter(field_name="product_type")@@ -348,6 +357,14 @@ class ProductFilter(django_filters.FilterSet):"search",]+ 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)++ 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)+def filter_variant_price(self, queryset, name, value):channel_slug = get_channel_slug_from_filter_data(self.data)return _filter_variant_price(queryset, name, value, channel_slug)diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex 1f1b11c481..a503a45cf6 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -76,11 +76,19 @@ def resolve_products(return ChannelQsContext(qs=qs.distinct(), channel_slug=channel_slug)-def resolve_variant_by_id(info, id, channel_slug, requestor):- visible_products = models.Product.objects.visible_to_user(- requestor, channel_slug- ).values_list("pk", flat=True)- qs = models.ProductVariant.objects.filter(product__id__in=visible_products)+def resolve_variant_by_id(+ info, id, channel_slug, requestor, requestor_has_access_to_all+):+ visible_products = models.Product.objects.visible_to_user(requestor, channel_slug)+ if not requestor_has_access_to_all:+ visible_products = visible_products.annotate_visible_in_listings(+ channel_slug+ ).exclude(visible_in_listings=False)+ qs = models.ProductVariant.objects.filter(+ product__id__in=visible_products+ ).available_in_channel(channel_slug)+ else:+ qs = models.ProductVariant.objects.filter(product__id__in=visible_products)return qs.filter(pk=id).first()@@ -96,12 +104,12 @@ def resolve_product_variant_by_sku(visible_products = visible_products.annotate_visible_in_listings(channel_slug).exclude(visible_in_listings=False)-- return (- models.ProductVariant.objects.filter(product__id__in=visible_products)- .filter(sku=sku)- .first()- )+ qs = models.ProductVariant.objects.filter(+ product__id__in=visible_products+ ).available_in_channel(channel_slug)+ else:+ qs = models.ProductVariant.objects.filter(product__id__in=visible_products)+ return qs.filter(sku=sku).first()def resolve_product_variants(@@ -112,8 +120,12 @@ def resolve_product_variants(visible_products = visible_products.annotate_visible_in_listings(channel_slug).exclude(visible_in_listings=False)+ qs = models.ProductVariant.objects.filter(+ product__id__in=visible_products+ ).available_in_channel(channel_slug)+ else:+ qs = models.ProductVariant.objects.filter(product__id__in=visible_products)- qs = models.ProductVariant.objects.filter(product__id__in=visible_products)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/schema.py b/saleor/graphql/product/schema.pyindex 685fba3dc0..d5f0c977d6 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -337,7 +337,11 @@ class ProductQueries(graphene.ObjectType):if id:_, id = graphene.Node.from_global_id(id)variant = resolve_variant_by_id(- info, id, channel_slug=channel, requestor=requestor+ info,+ id,+ channel_slug=channel,+ requestor=requestor,+ requestor_has_access_to_all=is_staff,)else:variant = resolve_product_variant_by_sku(diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.pyindex 8dee609f16..fafaa0fab5 100644--- a/saleor/graphql/product/sorters.py+++ b/saleor/graphql/product/sorters.py@@ -167,7 +167,8 @@ class ProductOrderField(graphene.Enum):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=channel_slug)+ & Q(variants__channel_listings__price_amount__isnull=False),))diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.pyindex c0157a5d7a..08f6e5eb05 100644--- a/saleor/graphql/product/tests/test_collection.py+++ b/saleor/graphql/product/tests/test_collection.py@@ -346,6 +346,7 @@ 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_product.py b/saleor/graphql/product/tests/test_product.pyindex 0c1da5e288..4df013e058 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -1493,7 +1493,11 @@ def test_fetch_product_from_category_query(def test_products_query_with_filter_attributes(- query_products_with_filter, staff_api_client, product, permission_manage_products+ query_products_with_filter,+ staff_api_client,+ product,+ permission_manage_products,+ channel_USD,):product_type = ProductType.objects.create(@@ -1515,7 +1519,10 @@ def test_products_query_with_filter_attributes(associate_attribute_values_to_instance(second_product, attribute, attr_value)variables = {- "filter": {"attributes": [{"slug": attribute.slug, "value": attr_value.slug}]}+ "filter": {+ "attributes": [{"slug": attribute.slug, "value": attr_value.slug}],+ "channel": channel_USD.slug,+ }}staff_api_client.user.user_permissions.add(permission_manage_products)@@ -1792,12 +1799,15 @@ def test_products_query_with_filter_stock_availability(product,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)- variables = {"filter": {"stockAvailability": "OUT_OF_STOCK"}}+ 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)@@ -2041,7 +2051,10 @@ def test_filter_products_by_wrong_attributes(user_api_client, product, channel_Uquery = """query ($channel: String){products(- filter: {attributes: {slug: "%(slug)s", value: "%(value)s"}},+ filter: {+ attributes: {slug: "%(slug)s", value: "%(value)s"},+ channel: $channel+ },first: 1,channel: $channel) {diff --git a/saleor/graphql/product/tests/test_product_pagination.py b/saleor/graphql/product/tests/test_product_pagination.pyindex 0b804e88b9..78e6206e06 100644--- a/saleor/graphql/product/tests/test_product_pagination.py+++ b/saleor/graphql/product/tests/test_product_pagination.py@@ -686,7 +686,10 @@ def test_products_pagination_for_products_with_the_same_names_one_page("filter_by, products_order",[({"hasCategory": True}, ["Product1", "Product2"]),- ({"stockAvailability": "OUT_OF_STOCK"}, ["ProductProduct1", "ProductProduct2"]),+ (+ {"stockAvailability": "OUT_OF_STOCK", "channel": "main"},+ ["ProductProduct1", "ProductProduct2"],+ ),],)def test_products_pagination_with_filtering(@@ -749,7 +752,10 @@ def test_products_pagination_with_filtering_by_attribute():page_size = 2products_order = ["Product2", "ProductProduct1"]- filter_by = {"attributes": [{"slug": "color", "values": ["red", "blue"]}]}+ filter_by = {+ "attributes": [{"slug": "color", "values": ["red", "blue"]}],+ "channel": channel_USD.slug,+ }variables = {"first": page_size, "after": None, "filter": filter_by}response = staff_api_client.post_graphql(diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex bb605bbbb5..30958802d4 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -23,7 +23,7 @@ from ..dataloaders import (ProductByIdLoader,ProductVariantsByProductIdLoader,VariantChannelListingByVariantIdAndChannelSlugLoader,- VariantsChannelListingByProductIdAndChanneSlugLoader,+ VariantsChannelListingByProductIdAndChannelSlugLoader,)@@ -195,7 +195,7 @@ class ProductChannelListing(CountableDjangoObjectType):)return (- VariantsChannelListingByProductIdAndChanneSlugLoader(+ VariantsChannelListingByProductIdAndChannelSlugLoader(context).load((root.product_id, channel.slug))diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 88ed5463d6..ce79b49c82 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -53,6 +53,7 @@ from ...order.dataloaders import (OrderByIdLoader,OrderLinesByVariantIdAndChannelIdLoader,)+from ...product.dataloaders.products import AvailableProductVariantsByProductVariantIdfrom ...translations.fields import TranslationFieldfrom ...translations.types import (CategoryTranslation,@@ -89,7 +90,7 @@ from ..dataloaders import (VariantAttributesByProductTypeIdLoader,VariantChannelListingByVariantIdAndChannelSlugLoader,VariantChannelListingByVariantIdLoader,- VariantsChannelListingByProductIdAndChanneSlugLoader,+ VariantsChannelListingByProductIdAndChannelSlugLoader,)from ..enums import VariantAttributeScopefrom ..filters import ProductFilterInput@@ -632,9 +633,11 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):context).load((root.node.id, channel_slug))variants = ProductVariantsByProductIdLoader(context).load(root.node.id)- variants_channel_listing = VariantsChannelListingByProductIdAndChanneSlugLoader(- context- ).load((root.node.id, channel_slug))+ variants_channel_listing = (+ VariantsChannelListingByProductIdAndChannelSlugLoader(context).load(+ (root.node.id, channel_slug)+ )+ )collections = CollectionsByProductIdLoader(context).load(root.node.id)channel = ChannelBySlugLoader(context).load(channel_slug)@@ -727,15 +730,40 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@staticmethoddef resolve_variants(root: ChannelContext[models.Product], info, **_kwargs):+ 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):+ if is_staff:+ return variants++ variants_id = (variant.id for variant in variants)+ variant_channel_listings = AvailableProductVariantsByProductVariantId(+ info.context+ ).load((root.channel_slug, variants_id))++ def return_available_variants(available_variants):+ result = []+ variants_map = {variant.id: variant for variant in variants}+ for variant_id in variants_map.keys() & available_variants:+ variant = variants_map.get(variant_id)+ if variant:+ result.append(variant)+ return result++ return variant_channel_listings.then(return_available_variants)++ def map_channel_context(variants):+ return [+ ChannelContext(node=variant, channel_slug=root.channel_slug)+ for variant in variants+ ]+return (ProductVariantsByProductIdLoader(info.context).load(root.node.id)- .then(- lambda variants: [- ChannelContext(node=variant, channel_slug=root.channel_slug)- for variant in variants- ]- )+ .then(return_available_variants_in_channel)+ .then(map_channel_context))@staticmethoddiff --git a/saleor/product/models.py b/saleor/product/models.pyindex b8fcba1c49..7f789a9455 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -155,7 +155,9 @@ class ProductsQueryset(models.QuerySet):def published_with_variants(self, channel_slug: str):published = self.published(channel_slug)query = ProductVariantChannelListing.objects.filter(- variant_id=OuterRef("variants__id"), channel__slug=str(channel_slug)+ variant_id=OuterRef("variants__id"),+ channel__slug=str(channel_slug),+ price_amount__isnull=False,).values_list("variant", flat=True)return published.filter(variants__in=query).distinct()@@ -403,6 +405,12 @@ class ProductVariantQueryset(models.QuerySet):),)+ def available_in_channel(self, channel_slug):+ return self.filter(+ channel_listings__price_amount__isnull=False,+ channel_listings__channel__slug=channel_slug,+ )+class ProductChannelListing(PublishableModel):product = models.ForeignKey(diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.pyindex 205529ac42..bfa38826af 100644--- a/saleor/product/tests/test_product.py+++ b/saleor/product/tests/test_product.py@@ -65,26 +65,34 @@ 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)+ filtered = filter_products_by_attributes_values(+ product_qs, filters, channel_USD.slug+ )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)+ filtered = filter_products_by_attributes_values(+ product_qs, filters, channel_USD.slug+ )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)+ filtered = filter_products_by_attributes_values(+ product_qs, filters, channel_USD.slug+ )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)+ filtered = filter_products_by_attributes_values(+ product_qs, filters, channel_USD.slug+ )assert product_a.pk in list(filtered)assert product_b.pk in list(filtered)@@ -95,7 +103,9 @@ 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)+ filtered = filter_products_by_attributes_values(+ product_qs, filters, channel_USD.slug+ )assert product_a.pk in list(filtered)