Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add paginated `productVariants` to `Product` type (#16998)
Krzysztof Waliczek9c032845e29b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 703dea6569..6433d3e0c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `CheckoutCustomerNoteUpdate` mutation - #16315 by @pitkes22- Add `customerNote` field to `Checkout` type to make it consistent with `Order` model - #16561 by @Air-t- Add `type` field to `TaxableObjectDiscount` type - #16630 by @zedzior+- Add `productVariants` field to `Product` instead of `variants`. Mark `Product.variants` as deprecated - #16998 by @kadewu### Webhooksdiff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex cbb8fef27b..d2450d5782 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -191,6 +191,7 @@ def resolve_product_variants(requestor,ids=None,channel: Optional[Channel] = None,+ product_id: Optional[int] = None,limited_channel_access: bool = False,) -> ChannelQsContext:connection_name = get_database_connection_name(info.context)@@ -205,6 +206,9 @@ def resolve_product_variants(]qs = qs.filter(pk__in=db_ids)+ if product_id:+ qs = qs.filter(product_id=product_id)+channel_slug = channel.slug if channel else Nonereturn ChannelQsContext(qs=qs, channel_slug=channel_slug)diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.pyindex cf57acd382..81707d54e6 100644--- a/saleor/graphql/product/tests/queries/test_product_query.py+++ b/saleor/graphql/product/tests/queries/test_product_query.py@@ -250,6 +250,9 @@ QUERY_PRODUCT_BY_ID = """variants {id}+ productVariants(first: 10){+ edges{ node{ id }}+ }}}"""@@ -258,12 +261,14 @@ QUERY_PRODUCT_BY_ID = """def test_product_query_by_id_as_user(user_api_client, permission_manage_products, product, channel_USD):+ # givenquery = QUERY_PRODUCT_BY_IDvariables = {"id": graphene.Node.to_global_id("Product", product.pk),"channel": channel_USD.slug,}+ # whenresponse = user_api_client.post_graphql(query,variables=variables,@@ -271,16 +276,23 @@ def test_product_query_by_id_as_user(check_no_permissions=False,)content = get_graphql_content(response)++ # thenproduct_data = content["data"]["product"]assert product_data is not None- expected_variants = [- {- "id": graphene.Node.to_global_id(- "ProductVariant", product.variants.first().pk- )- }- ]- assert product_data["variants"] == expected_variants++ first_product_variant_id = graphene.Node.to_global_id(+ "ProductVariant", product.variants.first().pk+ )++ assert len(product_data["productVariants"]["edges"]) == 1+ assert (+ product_data["productVariants"]["edges"][0]["node"]["id"]+ == first_product_variant_id+ )++ # deprecated field test+ assert product_data["variants"][0]["id"] == first_product_variant_iddef test_product_query_invalid_id(user_api_client, product, channel_USD):@@ -389,6 +401,7 @@ def test_product_query_by_id_as_app_without_channel_slug(def test_product_variants_without_sku_query_by_staff(staff_api_client, product, channel_USD):+ # givenproduct.variants.update(sku=None)product_id = graphene.Node.to_global_id("Product", product.pk)@@ -397,10 +410,13 @@ def test_product_variants_without_sku_query_by_staff("channel": channel_USD.slug,}+ # whenresponse = staff_api_client.post_graphql(QUERY_PRODUCT_BY_ID,variables=variables,)++ # thencontent = get_graphql_content(response)product_data = content["data"]["product"]@@ -409,12 +425,16 @@ def test_product_variants_without_sku_query_by_staff(variant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ assert product_data["productVariants"]["edges"] == [{"node": {"id": variant_id}}]+ # deprecated field testassert product_data["variants"] == [{"id": variant_id}]def test_product_only_with_variants_without_sku_query_by_customer(user_api_client, product, channel_USD):+ # givenproduct.variants.update(sku=None)product_id = graphene.Node.to_global_id("Product", product.pk)@@ -423,10 +443,13 @@ def test_product_only_with_variants_without_sku_query_by_customer("channel": channel_USD.slug,}+ # whenresponse = user_api_client.post_graphql(QUERY_PRODUCT_BY_ID,variables=variables,)++ # thencontent = get_graphql_content(response)product_data = content["data"]["product"]@@ -435,12 +458,15 @@ def test_product_only_with_variants_without_sku_query_by_customer(variant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ assert product_data["productVariants"]["edges"] == [{"node": {"id": variant_id}}]+ # deprecated field testassert product_data["variants"] == [{"id": variant_id}]def test_product_only_with_variants_without_sku_query_by_anonymous(api_client, product, channel_USD):+ # givenproduct.variants.update(sku=None)product_id = graphene.Node.to_global_id("Product", product.pk)@@ -449,10 +475,13 @@ def test_product_only_with_variants_without_sku_query_by_anonymous("channel": channel_USD.slug,}+ # whenresponse = api_client.post_graphql(QUERY_PRODUCT_BY_ID,variables=variables,)++ # thencontent = get_graphql_content(response)product_data = content["data"]["product"]@@ -461,6 +490,8 @@ def test_product_only_with_variants_without_sku_query_by_anonymous(variant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ assert product_data["productVariants"]["edges"] == [{"node": {"id": variant_id}}]+ # deprecated field testassert product_data["variants"] == [{"id": variant_id}]@@ -474,13 +505,6 @@ QUERY_PRODUCT_BY_ID_WITH_MEDIA = """urlalt}- variants {- id- name- media {- id- }- }}}"""@@ -1429,22 +1453,24 @@ def test_product_restricted_fields_permissions(QUERY_GET_PRODUCT_VARIANTS_PRICING = """query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {product(id: $id, channel: $channel) {- variants {- id- pricingNoAddress: pricing {- priceUndiscounted {- gross {- amount+ productVariants(first:10) {+ edges { node {+ id+ pricingNoAddress: pricing {+ priceUndiscounted {+ gross {+ amount+ }}}- }- pricing(address: $address) {- priceUndiscounted {- gross {- amount+ pricing(address: $address) {+ priceUndiscounted {+ gross {+ amount+ }}}- }+ } }}}}@@ -1479,7 +1505,9 @@ def test_product_variant_price()content = get_graphql_content(response)data = content["data"]["product"]- variant_price = data["variants"][0]["pricing"]["priceUndiscounted"]["gross"]+ variant_price = data["productVariants"]["edges"][0]["node"]["pricing"][+ "priceUndiscounted"+ ]["gross"]assert variant_price["amount"] == api_variant_price@@ -1503,8 +1531,8 @@ def test_product_variant_without_price_as_user()content = get_graphql_content(response)- variants_data = content["data"]["product"]["variants"]- assert not variants_data[0]["id"] == variant_id+ variants_data = content["data"]["product"]["productVariants"]["edges"]+ assert not variants_data[0]["node"]["id"] == variant_idassert len(variants_data) == 1@@ -1529,12 +1557,12 @@ def test_product_variant_without_price_as_staff_without_permission(QUERY_GET_PRODUCT_VARIANTS_PRICING, variables)content = get_graphql_content(response)- variants_data = content["data"]["product"]["variants"]+ variants_data = content["data"]["product"]["productVariants"]["edges"]assert len(variants_data) == 1- assert variants_data[0]["pricing"] is not None- assert variants_data[0]["id"] != variant_id+ assert variants_data[0]["node"]["pricing"] is not None+ assert variants_data[0]["node"]["id"] != variant_iddef test_product_variant_without_price_as_staff_with_permission(@@ -1558,13 +1586,13 @@ def test_product_variant_without_price_as_staff_with_permission(check_no_permissions=False,)content = get_graphql_content(response)- variants_data = content["data"]["product"]["variants"]+ variants_data = content["data"]["product"]["productVariants"]["edges"]assert len(variants_data) == 2- assert variants_data[0]["pricing"] is not None- assert variants_data[1]["id"] == variant_id- assert variants_data[1]["pricing"] is None+ assert variants_data[0]["node"]["pricing"] is not None+ assert variants_data[1]["node"]["id"] == variant_id+ assert variants_data[1]["node"]["pricing"] is Nonedef test_get_product_with_sorted_attribute_values(diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 05b82b943f..dcf9520002 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -57,6 +57,7 @@ from ...core.connection import ()from ...core.context import get_database_connection_namefrom ...core.descriptions import (+ ADDED_IN_321,DEPRECATED_IN_3X_FIELD,DEPRECATED_IN_3X_INPUT,RICH_CONTENT,@@ -145,8 +146,9 @@ from ..dataloaders import (VariantsChannelListingByProductIdAndChannelSlugLoader,)from ..enums import ProductMediaType, ProductTypeKindEnum, VariantAttributeScope+from ..filters import ProductVariantFilterInput, ProductVariantWhereInputfrom ..resolvers import resolve_product_variants, resolve_products-from ..sorters import MediaSortingInput+from ..sorters import MediaSortingInput, ProductVariantSortingInputfrom .channels import ProductChannelListing, ProductVariantChannelListingfrom .digital_contents import DigitalContent@@ -947,6 +949,20 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):"include the unpublished items: "f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."),+ deprecation_reason=f"{DEPRECATED_IN_3X_FIELD} Use `productVariants` field instead.",+ )+ product_variants = FilterConnectionField(+ ProductVariantCountableConnection,+ filter=ProductVariantFilterInput(+ description="Filtering options for product variant."+ ),+ where=ProductVariantWhereInput(description="Where filtering options."),+ sort_by=ProductVariantSortingInput(description="Sort products variants."),+ description=(+ "List of variants for the product. Requires the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}." + ADDED_IN_321+ ),)media = NonNullList(lambda: ProductMedia,@@ -1428,6 +1444,32 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):return variants.then(map_channel_context)+ @staticmethod+ def resolve_product_variants(root: ChannelContext[models.Product], info, **kwargs):+ requestor = get_user_or_app_from_context(info.context)++ def _resolve_product_variants(channel_obj):+ qs = resolve_product_variants(+ info,+ channel=channel_obj,+ product_id=root.node.pk,+ limited_channel_access=True,+ 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+ )++ return (+ ChannelBySlugLoader(info.context)+ .load(root.channel_slug)+ .then(_resolve_product_variants)+ )+@staticmethoddef resolve_channel_listings(root: ChannelContext[models.Product], info):return ProductChannelListingByProductIdLoader(info.context).load(root.node.id)diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.pyindex 6fe0ae13cc..318aed2c6d 100644--- a/saleor/graphql/query_cost_map.py+++ b/saleor/graphql/query_cost_map.py@@ -256,6 +256,7 @@ COST_MAP = {"productType": {"complexity": 1},"thumbnail": {"complexity": 1},"variants": {"complexity": 1},+ "productVariants": {"complexity": 1, "multipliers": ["first", "last"]},},"ProductChannelListing": {"channel": {"complexity": 1},diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 51076c9c91..7b98515bab 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5520,7 +5520,39 @@ type Product implements Node & ObjectWithMetadata @doc(category: "Products") {"""List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""- variants: [ProductVariant!]+ variants: [ProductVariant!] @deprecated(reason: "This field will be removed in Saleor 4.0. Use `productVariants` field instead.")++ """+ List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.++ Added in Saleor 3.21.+ """+ productVariants(+ """Filtering options for product variant."""+ filter: ProductVariantFilterInput++ """Where filtering options."""+ where: ProductVariantWhereInput++ """Sort products variants."""+ sortBy: ProductVariantSortingInput++ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductVariantCountableConnection"""List of media for the product."""media(@@ -7643,6 +7675,55 @@ type Margin @doc(category: "Products") {stop: Int}+type ProductVariantCountableConnection @doc(category: "Products") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [ProductVariantCountableEdge!]!++ """A total count of items in the collection."""+ totalCount: Int+}++type ProductVariantCountableEdge @doc(category: "Products") {+ """The item at the end of the edge."""+ node: ProductVariant!++ """A cursor for use in pagination."""+ cursor: String!+}++input ProductVariantFilterInput @doc(category: "Products") {+ search: String+ sku: [String!]+ metadata: [MetadataFilter!]+ isPreorder: Boolean+ updatedAt: DateTimeRangeInput+}++input ProductVariantWhereInput @doc(category: "Products") {+ metadata: [MetadataFilter!]+ ids: [ID!]++ """List of conditions that must be met."""+ AND: [ProductVariantWhereInput!]++ """A list of conditions of which at least one must be met."""+ OR: [ProductVariantWhereInput!]+}++input ProductVariantSortingInput @doc(category: "Products") {+ """Specifies the direction in which to sort productVariants."""+ direction: OrderDirection!++ """Sort productVariants by the selected field."""+ field: ProductVariantSortField!+}++enum ProductVariantSortField @doc(category: "Products") {+ """Sort products variants by last modified at."""+ LAST_MODIFIED_AT+}+input MediaSortingInput @doc(category: "Products") {"""Specifies the direction in which to sort media."""direction: OrderDirection!@@ -8643,23 +8724,6 @@ type CollectionCountableEdge @doc(category: "Products") {cursor: String!}-type ProductVariantCountableConnection @doc(category: "Products") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [ProductVariantCountableEdge!]!-- """A total count of items in the collection."""- totalCount: Int-}--type ProductVariantCountableEdge @doc(category: "Products") {- """The item at the end of the edge."""- node: ProductVariant!-- """A cursor for use in pagination."""- cursor: String!-}-enum DiscountValueTypeEnum @doc(category: "Discounts") {FIXEDPERCENTAGE@@ -12381,38 +12445,6 @@ enum ProductTypeSortField @doc(category: "Products") {SHIPPING_REQUIRED}-input ProductVariantFilterInput @doc(category: "Products") {- search: String- sku: [String!]- metadata: [MetadataFilter!]- isPreorder: Boolean- updatedAt: DateTimeRangeInput-}--input ProductVariantWhereInput @doc(category: "Products") {- metadata: [MetadataFilter!]- ids: [ID!]-- """List of conditions that must be met."""- AND: [ProductVariantWhereInput!]-- """A list of conditions of which at least one must be met."""- OR: [ProductVariantWhereInput!]-}--input ProductVariantSortingInput @doc(category: "Products") {- """Specifies the direction in which to sort productVariants."""- direction: OrderDirection!-- """Sort productVariants by the selected field."""- field: ProductVariantSortField!-}--enum ProductVariantSortField @doc(category: "Products") {- """Sort products variants by last modified at."""- LAST_MODIFIED_AT-}-type PaymentCountableConnection @doc(category: "Payments") {"""Pagination data for this connection."""pageInfo: PageInfo!