Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Deprecate hasVariants field on ProductType (#18717)
Iga Karbowiaka057b4b5adf0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8a19268198..87a0b2e323 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,7 +9,7 @@ All notable, unreleased changes to this project will be documented in this file.- Shipping method metadata is now copied to dedicated order fields (`shipping_method_metadata` and `shipping_method_private_metadata`) during checkout-to-order conversion. This ensures that order metadata remains consistent even if the original shipping method is modified or deleted. As a result, updates made to a shipping method's metadata after order creation will no longer be reflected in the order's `shippingMethod.metadata` field.- Shipping method metadata is now also denormalized during draft order finalization, ensuring consistent behavior across all order creation flows.- Fields `options`, `mount` and `target` are removed from `AppExtension` and `AppManifestExtension` types. Use `mountName`, `targetName` and `settings`-+- Deprecate the `hasVariants` field on `ProductType`. This setting is a legacy artifact from the former Simple/Configurable product distinction. Products can have multiple variants regardless of this flag. Previously, it only prevented assigning variant attributes to a product type; this restriction will no longer apply.### GraphQL API- Gift cards support as payment method within Transaction API (read more in the [docs](https://docs.saleor.io/developer/gift-cards#using-gift-cards-in-checkout)).@@ -27,3 +27,4 @@ Validation is now performed on the frontend (Dashboard). This change increases v- Improve user search. Use search vector functionality to enable searching users by email address, first name, last name, and addresses.### Deprecations+- Deprecate the `hasVariants` field on `ProductType`.diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex a1bebe0a3b..4a3487df32 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -312,53 +312,28 @@ class ProductVariantBulkCreate(BaseMutation):))attributes_errors_count += 1-- if product_type.has_variants:- try:- cleaned_attributes = AttributeAssignmentMixin.clean_input(- attributes_input, variant_attributes+ try:+ cleaned_attributes = AttributeAssignmentMixin.clean_input(+ attributes_input, variant_attributes+ )+ cleaned_input["attributes"] = cleaned_attributes+ except ValidationError as exc:+ for error in exc.error_list:+ attributes = (+ error.params.get("attributes") if error.params else None)- cleaned_input["attributes"] = cleaned_attributes- except ValidationError as exc:- for error in exc.error_list:- attributes = (- error.params.get("attributes") if error.params else None- )- index_error_map[variant_index].append(- ProductVariantBulkError(- field="attributes",- path="attributes",- message=error.message,- code=error.code,- attributes=attributes,- )+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="attributes",+ path="attributes",+ message=error.message,+ code=error.code,+ attributes=attributes,)- if errors is not None:- exc.params = {"index": variant_index}- errors["attributes"].append(exc)- attributes_errors_count += 1- else:- message = "Cannot assign attributes for product type without variants"- index_error_map[variant_index].append(- ProductVariantBulkError(- field="attributes",- path="attributes",- message=message,- code=ProductVariantBulkErrorCode.INVALID.value,- attributes=invalid_attributes,)- )if errors is not None:- errors["attributes"].append(- ValidationError(- message,- code=ProductVariantBulkErrorCode.INVALID.value,- params={- "attributes": invalid_attributes,- "index": variant_index,- },- )- )+ exc.params = {"index": variant_index}+ errors["attributes"].append(exc)attributes_errors_count += 1return attributes_errors_countdiff --git a/saleor/graphql/product/filters/product_type.py b/saleor/graphql/product/filters/product_type.pyindex 8bce61a7cd..e1893991f4 100644--- a/saleor/graphql/product/filters/product_type.py+++ b/saleor/graphql/product/filters/product_type.py@@ -2,6 +2,8 @@ import django_filtersimport graphenefrom django.db.models import Q+from saleor.graphql.warehouse.types import DEPRECATED_IN_3X_INPUT+from ....product.models import ProductTypefrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.filters import (@@ -45,7 +47,13 @@ class ProductTypeFilter(MetadataFilterBase):search = django_filters.CharFilter(method="filter_product_type_searchable")configurable = EnumFilter(- input_class=ProductTypeConfigurable, method=filter_product_type_configurable+ input_class=ProductTypeConfigurable,+ method=filter_product_type_configurable,+ help_text=(+ f"{DEPRECATED_IN_3X_INPUT} The field has no effect on the API behavior. "+ "This is a leftover from the past Simple/Configurable product distinction. "+ "Products can have multiple variants regardless of this setting. "+ ),)product_type = EnumFilter(input_class=ProductTypeEnum, method=filter_product_type)diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex ce66e53134..bf6cabef2a 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -284,17 +284,6 @@ class ProductAttributeAssign(BaseMutation, VariantAssignmentValidationMixin):# Resolve all the passed IDs to intsproduct_attrs_data, variant_attrs_data = cls.get_operations(info, operations)- variant_attrs_pks = [pk for pk, _, __ in variant_attrs_data]-- if variant_attrs_pks and not product_type.has_variants:- raise ValidationError(- {- "operations": ValidationError(- "Variants are disabled in this product type.",- code=ProductErrorCode.ATTRIBUTE_VARIANTS_DISABLED.value,- )- }- )# Ensure the attribute are assignablecls.clean_operations(product_type, product_attrs_data, variant_attrs_data)diff --git a/saleor/graphql/product/mutations/product_type/product_type_create.py b/saleor/graphql/product/mutations/product_type/product_type_create.pyindex 87dca5583b..2d87bbf114 100644--- a/saleor/graphql/product/mutations/product_type/product_type_create.py+++ b/saleor/graphql/product/mutations/product_type/product_type_create.py@@ -26,6 +26,9 @@ class ProductTypeInput(BaseInputObjectType):"Determines if product of this type has multiple variants. This option ""mainly simplifies product management in the dashboard. There is always at ""least one variant created under the hood."+ f"{DEPRECATED_IN_3X_INPUT} The field has no effect on the API behavior. "+ "This is a leftover from the past Simple/Configurable product distinction. "+ "Products can have multiple variants regardless of this setting. "))product_attributes = NonNullList(diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.pyindex bbbaba67be..f8b7af7458 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py@@ -162,33 +162,25 @@ class ProductVariantCreate(DeprecatedModelMutation):except ValidationError as e:raise ValidationError({"attributes": e}) from e- # Run the validation only if product type is configurable- if product_type.has_variants:- # Attributes are provided as list of `AttributeValueInput` objects.- # We need to transform them into the format they're stored in the- # `Product` model, which is HStore field that maps attribute's PK to- # the value's PK.- try:- if attributes:- attributes_qs = product_type.variant_attributes.all()- cleaned_attributes: T_INPUT_MAP = (- AttributeAssignmentMixin.clean_input(attributes, attributes_qs)- )- cleaned_input["attributes"] = cleaned_attributes- elif product_type.variant_attributes.filter(value_required=True):- # if attributes were not provided on creation- raise ValidationError(- "All required attributes must take a value.",- ProductErrorCode.REQUIRED.value,- )- except ValidationError as e:- raise ValidationError({"attributes": e}) from e- else:+ # Attributes are provided as list of `AttributeValueInput` objects.+ # We need to transform them into the format they're stored in the+ # `Product` model, which is HStore field that maps attribute's PK to+ # the value's PK.+ try:if attributes:+ attributes_qs = product_type.variant_attributes.all()+ cleaned_attributes: T_INPUT_MAP = AttributeAssignmentMixin.clean_input(+ attributes, attributes_qs+ )+ cleaned_input["attributes"] = cleaned_attributes+ elif product_type.variant_attributes.filter(value_required=True):+ # if attributes were not provided on creationraise ValidationError(- "Cannot assign attributes for product type without variants",- ProductErrorCode.INVALID.value,+ "All required attributes must take a value.",+ ProductErrorCode.REQUIRED.value,)+ except ValidationError as e:+ raise ValidationError({"attributes": e}) from e@classmethoddef get_product(cls, cleaned_input: dict) -> models.Product:diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.pyindex a3991e1f93..eea130abe0 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py@@ -156,30 +156,20 @@ class ProductVariantUpdate(DeprecatedModelMutation):params={"attributes": invalid_attributes},)- # Run the validation only if product type is configurable- if product_type.has_variants:- # Attributes are provided as list of `AttributeValueInput` objects.- # We need to transform them into the format they're stored in the- # `Product` model, which is HStore field that maps attribute's PK to- # the value's PK.- try:- if attributes:- attributes_qs = product_type.variant_attributes.all()- cleaned_attributes: T_INPUT_MAP = (- AttributeAssignmentMixin.clean_input(- attributes, attributes_qs, creation=False- )- )- cleaned_input["attributes"] = cleaned_attributes-- except ValidationError as e:- raise ValidationError({"attributes": e}) from e- else:+ # Attributes are provided as list of `AttributeValueInput` objects.+ # We need to transform them into the format they're stored in the+ # `Product` model, which is HStore field that maps attribute's PK to+ # the value's PK.+ try:if attributes:- raise ValidationError(- "Cannot assign attributes for product type without variants",- ProductErrorCode.INVALID.value,+ attributes_qs = product_type.variant_attributes.all()+ cleaned_attributes: T_INPUT_MAP = AttributeAssignmentMixin.clean_input(+ attributes, attributes_qs, creation=False)+ cleaned_input["attributes"] = cleaned_attributes++ except ValidationError as e:+ raise ValidationError({"attributes": e}) from e@classmethoddef set_track_inventory(cls, _info, instance, cleaned_input):diff --git a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.pyindex 10c254fff7..d1fc1b3f36 100644--- a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py+++ b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py@@ -103,7 +103,7 @@ def test_product_channel_listing_update_as_staff_user(variant = product.variants.first()variant_channel_listing = variant.channel_listings.filter(channel_id=channel_USD.id)purchase_cost, margin = get_product_costs_data(- variant_channel_listing, True, channel_USD.currency_code+ variant_channel_listing, channel_USD.currency_code)assert not data["errors"]assert product_data["slug"] == product.slugdiff --git a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.pyindex 9093646630..b0f8fd22c2 100644--- a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py@@ -237,7 +237,7 @@ def test_product_channel_listing_update_as_staff_user(variant = product.variants.first()variant_channel_listing = variant.channel_listings.filter(channel_id=channel_USD.id)purchase_cost, margin = get_product_costs_data(- variant_channel_listing, True, channel_USD.currency_code+ variant_channel_listing, channel_USD.currency_code)assert not data["errors"]assert product_data["slug"] == product.slugdiff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.pyindex 8c8e1c6180..981c4aae5c 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py@@ -2720,8 +2720,8 @@ def test_variant_create_product_with_variant_attributes_variant_flag_false(content = get_graphql_content(response)errors = content["data"]["productVariantCreate"]["errors"]- assert errors- assert errors[0]["code"] == ProductErrorCode.INVALID.name+ # hasVariants has no more effects on variant attributes+ assert not errorsdef test_create_product_variant_with_non_unique_external_reference(diff --git a/saleor/graphql/product/tests/queries/test_category_query.py b/saleor/graphql/product/tests/queries/test_category_query.pyindex 9dc1207b68..84f47109ec 100644--- a/saleor/graphql/product/tests/queries/test_category_query.py+++ b/saleor/graphql/product/tests/queries/test_category_query.py@@ -750,7 +750,7 @@ def test_fetch_product_from_category_query(variant = product.variants.first()variant_channel_listing = variant.channel_listings.filter(channel_id=channel_USD.id)purchase_cost, margin = get_product_costs_data(- variant_channel_listing, True, channel_USD.currency_code+ variant_channel_listing, channel_USD.currency_code)cost_start = product_data["channelListings"][0]["purchaseCost"]["start"]["amount"]cost_stop = product_data["channelListings"][0]["purchaseCost"]["stop"]["amount"]diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.pyindex 0f01db74a0..8e0b5b6edc 100644--- a/saleor/graphql/product/tests/test_attributes.py+++ b/saleor/graphql/product/tests/test_attributes.py@@ -659,14 +659,8 @@ def test_assign_variant_attribute_to_product_type_with_disabled_variants(content = get_graphql_content(staff_api_client.post_graphql(query, variables))["data"]["productAttributeAssign"]- assert content["errors"][0]["field"] == "operations"- assert (- content["errors"][0]["message"] == "Variants are disabled in this product type."- )- assert (- content["errors"][0]["code"]- == ProductErrorCode.ATTRIBUTE_VARIANTS_DISABLED.name- )+ # hasVariants has no more effects on variant attributes+ assert not content["errors"]def test_assign_variant_attribute_having_multiselect_input_type(diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex 3a769b2eef..e3921a12c2 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -144,9 +144,8 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):if not existing_listings:return None- has_variants = Truepurchase_cost, _margin = get_product_costs_data(- existing_listings, has_variants, root.currency+ existing_listings, root.currency)return purchase_cost@@ -172,9 +171,8 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):if not existing_listings:return None- has_variants = True_purchase_cost, margin = get_product_costs_data(- existing_listings, has_variants, root.currency+ existing_listings, root.currency)return Margin(margin[0], margin[1])diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex b589f59234..5be7d18d59 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1736,7 +1736,12 @@ class ProductType(ModelObjectType[models.ProductType]):name = graphene.String(required=True, description="Name of the product type.")slug = graphene.String(required=True, description="Slug of the product type.")has_variants = graphene.Boolean(- required=True, description="Whether the product type has variants."+ required=True,+ description="Whether the product type has variants.",+ deprecation_reason=(+ "This is a leftover from the past Simple/Configurable product distinction. "+ "Products can have multiple variants regardless of this setting. "+ ),)is_shipping_required = graphene.Boolean(required=True, description="Whether shipping is required for this product type."diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4935a1fd13..ada317bcd3 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6105,7 +6105,7 @@ type ProductType implements Node & ObjectWithMetadata @doc(category: "Products")slug: String!"""Whether the product type has variants."""- hasVariants: Boolean!+ hasVariants: Boolean! @deprecated(reason: "This is a leftover from the past Simple/Configurable product distinction. Products can have multiple variants regardless of this setting. ")"""Whether shipping is required for this product type."""isShippingRequired: Boolean!@@ -13050,7 +13050,9 @@ enum CollectionSortField @doc(category: "Products") {input ProductTypeFilterInput @doc(category: "Products") {search: String- configurable: ProductTypeConfigurable++ """"""+ configurable: ProductTypeConfigurable @deprecated(reason: "The field has no effect on the API behavior. This is a leftover from the past Simple/Configurable product distinction. Products can have multiple variants regardless of this setting.")productType: ProductTypeEnummetadata: [MetadataFilter!]kind: ProductTypeKindEnum@@ -22578,7 +22580,7 @@ input ProductTypeInput @doc(category: "Products") {"""Determines if product of this type has multiple variants. This option mainly simplifies product management in the dashboard. There is always at least one variant created under the hood."""- hasVariants: Boolean+ hasVariants: Boolean @deprecated(reason: "The field has no effect on the API behavior. This is a leftover from the past Simple/Configurable product distinction. Products can have multiple variants regardless of this setting.")"""List of attributes shared among all product variants."""productAttributes: [ID!]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex ccebb36cd4..6d7dbc4dfb 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -126,7 +126,6 @@ class ProductType(ModelWithMetadata):name = models.CharField(max_length=250)slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)kind = models.CharField(max_length=32, choices=ProductTypeKind.CHOICES)- has_variants = models.BooleanField(default=True)is_shipping_required = models.BooleanField(default=True)is_digital = models.BooleanField(default=False)weight = MeasurementField(@@ -142,6 +141,9 @@ class ProductType(ModelWithMetadata):null=True,)+ # DEPRECATED, does not affect the variant creation anymore+ has_variants = models.BooleanField(default=True)+class Meta(ModelWithMetadata.Meta):ordering = ("slug",)app_label = "product"diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.pyindex a6328a919f..f732185e0b 100644--- a/saleor/product/utils/costs.py+++ b/saleor/product/utils/costs.py@@ -23,7 +23,6 @@ class CostsData:def get_product_costs_data(variant_channel_listings: Iterable[ProductVariantChannelListing],- has_variants: bool,currency: str,) -> tuple[MoneyRange, tuple[float, float]]:purchase_costs_range = MoneyRange(@@ -31,9 +30,6 @@ def get_product_costs_data()margin = (0.0, 0.0)- if not has_variants:- return purchase_costs_range, margin-costs_data = get_cost_data_from_variant_channel_listing(variant_channel_listings)if costs_data.costs:purchase_costs_range = MoneyRange(min(costs_data.costs), max(costs_data.costs))