Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor attribute values assignment (#11206)
Piotr Zabieglikee8a4fb54333
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87738cb7b8..9b87b2ac2e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,9 @@ All notable, unreleased changes to this project will be documented in this file.- Bump cryptography to 38.0.3: use OpenSSL 3.0.7 - #11126 by @NyanKiyoshi- Add exif image validation - #11224 by @IKarbowiak- Include fully qualified API URL `Saleor-Api-Url` in communication with Apps. #11223 by @przlada+- Add `attribute` field to `AttributeValueTranslatableContent` type. #11028 by @zedzior+- Allow assigning attribute value using its ID. Add to `AttributeValueInput` dedicated field for each input type. #11206 by @zedzior+...# 3.8.0diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.pyindex 22a701850b..938268c250 100644--- a/saleor/attribute/utils.py+++ b/saleor/attribute/utils.py@@ -30,7 +30,7 @@ def associate_attribute_values_to_instance() -> AttributeAssignmentType:"""Assign given attribute values to a product or variant.- Note: be award this function invokes the ``set`` method on the instance's+ Note: be aware this function invokes the ``set`` method on the instance'sattribute association. Meaning any values already assigned or concurrentlyassigned will be overridden by this call."""diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex 9c543aef2f..8ef3bb447e 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -8,6 +8,7 @@ from ....page.error_codes import PageErrorCodefrom ....product.error_codes import ProductErrorCodefrom ..utils import (AttributeAssignmentMixin,+ AttrValuesForSelectableFieldInput,AttrValuesInput,prepare_attribute_values,validate_attributes_input,@@ -1355,6 +1356,456 @@ def test_validate_numeric_attributes_input_for_product_more_than_one_value_given}[email protected]("creation", [True, False])+def test_validate_selectable_attributes_by_value(+ creation, weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(value="new color"),+ ),+ ),+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(value="new weight 1"),+ AttrValuesForSelectableFieldInput(value="new weight 2"),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++[email protected]("creation", [True, False])+def test_validate_selectable_attributes_by_id(+ creation, weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(id="id"),+ ),+ ),+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(id="id1"),+ AttrValuesForSelectableFieldInput(id="id2"),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++[email protected]("creation", [True, False])+def test_validate_selectable_attributes_pass_null_value(+ creation, weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.save(update_fields=["input_type"])++ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(value=None),+ ),+ ),+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(value=None),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++[email protected]("creation", [True, False])+def test_validate_selectable_attribute_by_id_and_value(+ creation, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(id="id", value="new color"),+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.INVALID.value++[email protected]("creation", [True, False])+def test_validate_multiselect_attribute_by_id_and_value(+ creation, weight_attribute, product_type+):+ # given+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(id="id"),+ AttrValuesForSelectableFieldInput(value="new weight"),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.INVALID.value++[email protected]("creation", [True, False])+def test_validate_multiselect_attribute_duplicated_values(+ creation, weight_attribute, product_type+):+ # given+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(value="new weight"),+ AttrValuesForSelectableFieldInput(value="new weight"),+ AttrValuesForSelectableFieldInput(value="new weight 2"),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value++[email protected]("creation", [True, False])+def test_validate_multiselect_attribute_duplicated_ids(+ creation, weight_attribute, product_type+):+ # given+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(id="new weight"),+ AttrValuesForSelectableFieldInput(id="new weight"),+ AttrValuesForSelectableFieldInput(id="new weight 2"),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value++[email protected]("creation", [True, False])+def test_validate_selectable_attribute_max_length_exceeded(+ creation, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])+ col_max = color_attribute.values.model.name.field.max_length++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(value="n" * col_max + "n"),+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.INVALID.value++[email protected]("value", [None, "", " "])[email protected]("creation", [True, False])+def test_validate_selectable_attribute_value_required(+ creation, value, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(value=value),+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.REQUIRED.value++[email protected]("value", [2.56, "2.56", "0", 0, -3.5, "-3.6"])[email protected]("creation", [True, False])+def test_validate_numeric_attributes(creation, value, numeric_attribute, product_type):+ # given+ input_data = [+ (+ numeric_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),+ numeric=value,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++[email protected]("value", [True, "number", "0,56", "e-10", "20k"])[email protected]("creation", [True, False])+def test_validate_numeric_attributes_invalid_number(+ creation, value, numeric_attribute, product_type+):+ # given+ input_data = [+ (+ numeric_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),+ numeric=value,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.INVALID.value++[email protected]("creation", [True, False])+def test_validate_numeric_attributes_pass_null_value(+ creation, numeric_attribute, product_type+):+ # given+ input_data = [+ (+ numeric_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),+ numeric=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++[email protected]("creation", [True, False])+def test_validate_numeric_attributes_value_required(+ creation, numeric_attribute, product_type+):+ # given+ numeric_attribute.value_required = True+ numeric_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ numeric_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),+ numeric=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.REQUIRED.value++def test_clean_file_url_in_attribute_assignment_mixin(site_settings):# givenname = "Test.jpg"@@ -1398,7 +1849,7 @@ def test_prepare_attribute_values(color_attribute):)# when- prepare_attribute_values(color_attribute, values)+ prepare_attribute_values(color_attribute, values.values)# thencolor_attribute.refresh_from_db()@@ -1429,7 +1880,7 @@ def test_prepare_attribute_values_prefer_the_slug_match(color_attribute):)# when- result = prepare_attribute_values(color_attribute, values)+ result = prepare_attribute_values(color_attribute, values.values)# thencolor_attribute.refresh_from_db()@@ -1458,7 +1909,7 @@ def test_prepare_attribute_values_that_gives_the_same_slug(color_attribute):)# when- result = prepare_attribute_values(color_attribute, values)+ result = prepare_attribute_values(color_attribute, values.values)# thencolor_attribute.refresh_from_db()diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 4156873454..7efe7614dd 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -15,7 +15,7 @@ from ..core.connection import (create_connection_slice,filter_connection_queryset,)-from ..core.descriptions import ADDED_IN_31+from ..core.descriptions import ADDED_IN_31, ADDED_IN_39, DEPRECATED_IN_3X_FIELDfrom ..core.enums import MeasurementUnitsEnumfrom ..core.fields import ConnectionField, FilterConnectionField, JSONStringfrom ..core.types import (@@ -368,6 +368,23 @@ class AttributeInput(graphene.InputObjectType):)+class AttributeValueSelectableTypeInput(graphene.InputObjectType):+ id = graphene.ID(required=False, description="ID of an attribute value.")+ value = graphene.String(+ required=False,+ description=(+ "The value or slug of an attribute to resolve. "+ "If the passed value is non-existent, it will be created."+ ),+ )++ class Meta:+ description = (+ "Represents attribute value. If no ID provided, value will be resolved. "+ + ADDED_IN_39+ )++class AttributeValueInput(graphene.InputObjectType):id = graphene.ID(description="ID of the selected attribute.")values = NonNullList(@@ -375,9 +392,23 @@ class AttributeValueInput(graphene.InputObjectType):required=False,description=("The value or slug of an attribute to resolve. "- "If the passed value is non-existent, it will be created."+ "If the passed value is non-existent, it will be created. "+ + DEPRECATED_IN_3X_FIELD),)+ dropdown = AttributeValueSelectableTypeInput(+ required=False,+ description="Attribute value ID." + ADDED_IN_39,+ )+ multiselect = NonNullList(+ AttributeValueSelectableTypeInput,+ required=False,+ description="List of attribute value IDs." + ADDED_IN_39,+ )+ numeric = graphene.String(+ required=False,+ description="Numeric value of an attribute." + ADDED_IN_39,+ )file = graphene.String(required=False,description="URL of the file attribute. Every time, a new value is created.",diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex f1a50502fc..108e2b3198 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -32,10 +32,19 @@ if TYPE_CHECKING:from ...attribute.models import Attribute+@dataclass+class AttrValuesForSelectableFieldInput:+ id: Optional[str] = None+ value: Optional[str] = None++@dataclassclass AttrValuesInput:global_id: str- values: List[str]+ values: Optional[List[str]] = None+ dropdown: Optional[AttrValuesForSelectableFieldInput] = None+ multiselect: Optional[List[AttrValuesForSelectableFieldInput]] = None+ numeric: Optional[str] = Nonereferences: Union[List[str], List[page_models.Page], None] = Nonefile_url: Optional[str] = Nonecontent_type: Optional[str] = None@@ -178,7 +187,6 @@ class AttributeAssignmentMixin:# Temporary storage of the passed ID for error reportingglobal_ids = []-for attribute_input in raw_input:global_id = attribute_input.pop("id", None)if global_id is None:@@ -303,22 +311,33 @@ class AttributeAssignmentMixin::param cleaned_input: the cleaned user input (refer to clean_attributes)"""pre_save_methods_mapping = {- AttributeInputType.FILE: cls._pre_save_file_value,- AttributeInputType.REFERENCE: cls._pre_save_reference_values,- AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,- AttributeInputType.PLAIN_TEXT: cls._pre_save_plain_text_values,- AttributeInputType.NUMERIC: cls._pre_save_numeric_values,AttributeInputType.BOOLEAN: cls._pre_save_boolean_values,AttributeInputType.DATE: cls._pre_save_date_time_values,AttributeInputType.DATE_TIME: cls._pre_save_date_time_values,+ AttributeInputType.DROPDOWN: cls._pre_save_dropdown_value,+ AttributeInputType.FILE: cls._pre_save_file_value,+ AttributeInputType.NUMERIC: cls._pre_save_numeric_values,+ AttributeInputType.MULTISELECT: cls._pre_save_multiselect_values,+ AttributeInputType.PLAIN_TEXT: cls._pre_save_plain_text_values,+ AttributeInputType.REFERENCE: cls._pre_save_reference_values,+ AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,}clean_assignment = []for attribute, attr_values in cleaned_input:- if (input_type := attribute.input_type) in pre_save_methods_mapping:- pre_save_func = pre_save_methods_mapping[input_type]- attribute_values = pre_save_func(instance, attribute, attr_values)- else:+ is_handled_by_values_field = (+ attr_values.values+ and attribute.input_type+ in (+ AttributeInputType.DROPDOWN,+ AttributeInputType.MULTISELECT,+ AttributeInputType.SWATCH,+ )+ )+ if is_handled_by_values_field:attribute_values = cls._pre_save_values(attribute, attr_values)+ else:+ pre_save_func = pre_save_methods_mapping[attribute.input_type]+ attribute_values = pre_save_func(instance, attribute, attr_values)associate_attribute_values_to_instance(instance, attribute, *attribute_values@@ -333,16 +352,60 @@ class AttributeAssignmentMixin:).delete()@classmethod- def _pre_save_values(- cls, attribute: attribute_models.Attribute, attr_values: AttrValuesInput+ def _pre_save_dropdown_value(+ cls,+ _,+ attribute: attribute_models.Attribute,+ attr_values: AttrValuesInput,):- """Lazy-retrieve or create the database objects from the supplied raw values."""- if not attr_values.values:+ if not attr_values.dropdown:return tuple()- result = prepare_attribute_values(attribute, attr_values)+ if id := attr_values.dropdown.id:+ _, attr_value_id = from_global_id_or_error(id)+ model = attribute_models.AttributeValue.objects.get(pk=attr_value_id)+ if not model:+ raise ValidationError("Attribute value with given ID can't be found")+ return (model,)- return tuple(result)+ if attr_value := attr_values.dropdown.value:+ model = prepare_attribute_values(attribute, [attr_value])+ return model++ return tuple()++ @classmethod+ def _pre_save_multiselect_values(+ cls,+ _,+ attribute: attribute_models.Attribute,+ attr_values_input: AttrValuesInput,+ ):+ if not attr_values_input.multiselect:+ return tuple()++ attribute_values: List[attribute_models.AttributeValue] = []+ for attr_value in attr_values_input.multiselect:+ if attr_value.id:+ _, attr_value_id = from_global_id_or_error(attr_value.id)+ attr_value_model = attribute_models.AttributeValue.objects.get(+ pk=attr_value_id+ )+ if not attr_value_model:+ raise ValidationError(+ "Attribute value with given ID can't be found"+ )+ if attr_value_model.id not in [a.id for a in attribute_values]:+ attribute_values.append(attr_value_model)++ if attr_value.value:+ attr_value_model = prepare_attribute_values(+ attribute, [attr_value.value]+ )[0]+ if attr_value_model.id not in [a.id for a in attribute_values]:+ attribute_values.append(attr_value_model)++ return attribute_values@classmethoddef _pre_save_numeric_values(@@ -351,13 +414,34 @@ class AttributeAssignmentMixin:attribute: attribute_models.Attribute,attr_values: AttrValuesInput,):- if not attr_values.values:+ if attr_values.values:+ value = attr_values.values[0]+ elif attr_values.numeric:+ value = attr_values.numeric+ else:return tuple()+defaults = {- "name": attr_values.values[0],+ "name": value,}return cls._update_or_create_value(instance, attribute, defaults)+ @classmethod+ def _pre_save_values(+ cls, attribute: attribute_models.Attribute, attr_values: AttrValuesInput+ ):+ """To be deprecated together with `AttributeValueInput.values` field.++ Lazy-retrieve or create the database objects from the supplied raw values.+ """++ if not attr_values.values:+ return tuple()++ result = prepare_attribute_values(attribute, attr_values.values)++ return tuple(result)+@classmethoddef _pre_save_rich_text_values(cls,@@ -525,10 +609,7 @@ def get_variant_selection_attributes(qs: "QuerySet") -> "QuerySet":)-def prepare_attribute_values(- attribute: attribute_models.Attribute, attr_values: AttrValuesInput-):- values = attr_values.values+def prepare_attribute_values(attribute: attribute_models.Attribute, values: List[str]):slug_to_value_map = {}name_to_value_map = {}for val in attribute.values.filter(Q(name__in=values) | Q(slug__in=values)):@@ -595,7 +676,10 @@ class AttributeInputErrors:"Duplicated attribute values are provided.","DUPLICATED_INPUT_ITEM",)-+ ERROR_ID_AND_VALUE = (+ "Attribute values cannot be assigned by both id and value.",+ "INVALID",+ )# file errorsERROR_NO_FILE_GIVEN = ("Attribute file url cannot be blank.",@@ -640,28 +724,38 @@ def validate_attributes_input(error_code_enum = PageErrorCode if is_page_attributes else ProductErrorCodeattribute_errors: T_ERROR_DICT = defaultdict(list)+ input_type_to_validation_func_mapping = {+ AttributeInputType.BOOLEAN: validate_boolean_input,+ AttributeInputType.DATE: validate_date_time_input,+ AttributeInputType.DATE_TIME: validate_date_time_input,+ AttributeInputType.DROPDOWN: validate_dropdown_input,+ AttributeInputType.FILE: validate_file_attributes_input,+ AttributeInputType.NUMERIC: validate_numeric_input,+ AttributeInputType.MULTISELECT: validate_multiselect_input,+ AttributeInputType.PLAIN_TEXT: validate_plain_text_attributes_input,+ AttributeInputType.REFERENCE: validate_reference_attributes_input,+ AttributeInputType.RICH_TEXT: validate_rich_text_attributes_input,+ }+for attribute, attr_values in input_data:attrs = (attribute,attr_values,attribute_errors,)- input_type_to_validation_func_mapping = {- AttributeInputType.FILE: validate_file_attributes_input,- AttributeInputType.REFERENCE: validate_reference_attributes_input,- AttributeInputType.RICH_TEXT: validate_rich_text_attributes_input,- AttributeInputType.PLAIN_TEXT: validate_plain_text_attributes_input,- AttributeInputType.BOOLEAN: validate_boolean_input,- AttributeInputType.DATE: validate_date_time_input,- AttributeInputType.DATE_TIME: validate_date_time_input,- }- if validation_func := input_type_to_validation_func_mapping.get(- attribute.input_type- ):- validation_func(*attrs)- # validation for other input types- else:+ is_handled_by_values_field = attr_values.values and attribute.input_type in (+ AttributeInputType.DROPDOWN,+ AttributeInputType.MULTISELECT,+ AttributeInputType.NUMERIC,+ AttributeInputType.SWATCH,+ )+ if is_handled_by_values_field:validate_standard_attributes_input(*attrs)+ else:+ validation_func = input_type_to_validation_func_mapping[+ attribute.input_type+ ]+ validation_func(*attrs)errors = prepare_error_list_from_error_attribute_mapping(attribute_errors, error_code_enum@@ -672,7 +766,6 @@ def validate_attributes_input(errors = validate_required_attributes(input_data, attribute_qs, errors, error_code_enum)-return errors@@ -750,6 +843,7 @@ def validate_standard_attributes_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):+ """To be deprecated together with `AttributeValueInput.values` field."""attribute_id = attr_values.global_idif not attr_values.values:@@ -774,6 +868,129 @@ def validate_standard_attributes_input()+def validate_single_selectable_field(+ attribute: "Attribute",+ attr_value: AttrValuesForSelectableFieldInput,+ attribute_errors: T_ERROR_DICT,+ attribute_id: str,+):+ id = attr_value.id+ value = attr_value.value++ if id and value:+ attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(attribute_id)+ return++ if not id and not value and attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(attribute_id)+ return++ if value:+ max_length = attribute.values.model.name.field.max_length # type: ignore+ if not value.strip():+ attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(+ attribute_id+ )+ elif len(value) > max_length:+ attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)++ if id:+ if not id.strip():+ attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(+ attribute_id+ )+++def validate_dropdown_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ attribute_errors: T_ERROR_DICT,+):+ attribute_id = attr_values.global_id+ if not attr_values.dropdown:+ if attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attribute_id+ )+ else:+ validate_single_selectable_field(+ attribute,+ attr_values.dropdown,+ attribute_errors,+ attribute_id,+ )+++def validate_multiselect_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ attribute_errors: T_ERROR_DICT,+):+ attribute_id = attr_values.global_id+ multi_values = attr_values.multiselect+ if not multi_values:+ if attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attribute_id+ )+ else:+ ids = [value.id for value in multi_values if value.id is not None]+ values = [value.value for value in multi_values if value.value is not None]++ if ids and values:+ attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(+ attribute_id+ )+ return++ if not ids and not values and attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attribute_id+ )+ return++ if len(ids) > len(set(ids)) or len(values) > len(set(values)):+ attribute_errors[AttributeInputErrors.ERROR_DUPLICATED_VALUES].append(+ attribute_id+ )+ return++ for attr_value in multi_values:+ validate_single_selectable_field(+ attribute,+ attr_value,+ attribute_errors,+ attribute_id,+ )+++def validate_numeric_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ attribute_errors: T_ERROR_DICT,+):+ attribute_id = attr_values.global_id+ if attr_values.numeric is None:+ if attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attribute_id+ )+ return+ return++ try:+ float(attr_values.numeric) # type: ignore+ except ValueError:+ attribute_errors[AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED].append(+ attribute_id+ )++ if isinstance(attr_values.numeric, bool):+ attribute_errors[AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED].append(+ attribute_id+ )++def validate_date_time_input(attribute: "Attribute",attr_values: "AttrValuesInput",@@ -799,6 +1016,7 @@ def validate_values(values: list,attribute_errors: T_ERROR_DICT,):+ """To be deprecated together with `AttributeValueInput.values` field."""name_field = attribute.values.model.name.field # type: ignoreis_numeric = attribute.input_type == AttributeInputType.NUMERICif get_duplicated_values(values):diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex 7223840ab6..7c74560be0 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -17,6 +17,7 @@ from .....graphql.tests.utils import get_graphql_contentfrom .....plugins.manager import PluginsManagerfrom .....product.error_codes import ProductErrorCodefrom .....product.models import Product+from ....attribute.utils import AttributeInputErrorsMUTATION_UPDATE_PRODUCT = """mutation updateProduct($productId: ID!, $input: ProductInput!) {@@ -1941,3 +1942,799 @@ def test_update_product_slug_with_existing_value(assert errorsassert errors[0]["field"] == "slug"assert errors[0]["message"] == "Product with this Slug already exists."+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_numeric_attribute_value_by_numeric_field(+ updated_webhook_mock,+ staff_api_client,+ product,+ product_type,+ numeric_attribute,+ permission_manage_products,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)+ product_type.product_attributes.add(numeric_attribute)++ new_value = "45.2"++ variables = {+ "productId": product_id,+ "input": {"attributes": [{"id": attribute_id, "numeric": new_value}]},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["errors"] == []++ attributes = data["product"]["attributes"]+ assert len(attributes) == 2+ expected_att_data = {+ "attribute": {"id": attribute_id, "name": numeric_attribute.name},+ "values": [+ {+ "id": ANY,+ "name": new_value,+ "slug": slugify(+ f"{product.id}_{numeric_attribute.id}", allow_unicode=True+ ),+ "reference": None,+ "file": None,+ "boolean": None,+ "plainText": None,+ }+ ],+ }+ assert expected_att_data in attributes++ updated_webhook_mock.assert_called_once_with(product)+++def test_update_product_with_numeric_attribute_by_numeric_field_null_value(+ staff_api_client,+ numeric_attribute,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)+ product_type.product_attributes.add(numeric_attribute)+ slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)+ value = AttributeValue.objects.create(+ attribute=numeric_attribute, slug=slug_value, name="20.0"+ )+ associate_attribute_values_to_instance(product, numeric_attribute, value)++ variables = {+ "productId": product_id,+ "input": {"attributes": [{"id": attribute_id, "numeric": None}]},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["errors"] == []+ assert not data["product"]["attributes"][1]["values"]+++def test_update_product_with_numeric_attribute_by_numeric_field_new_value_not_created(+ staff_api_client,+ numeric_attribute,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)+ product_type.product_attributes.add(numeric_attribute)+ slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)+ value = AttributeValue.objects.create(+ attribute=numeric_attribute, slug=slug_value, name="20.0"+ )+ associate_attribute_values_to_instance(product, numeric_attribute, value)++ value_count = AttributeValue.objects.count()++ new_value = "45.2"++ variables = {+ "productId": product_id,+ "input": {"attributes": [{"id": attribute_id, "numeric": new_value}]},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["errors"] == []++ attributes = data["product"]["attributes"]++ assert len(attributes) == 2+ expected_att_data = {+ "attribute": {"id": attribute_id, "name": numeric_attribute.name},+ "values": [+ {+ "id": ANY,+ "name": new_value,+ "slug": slug_value,+ "reference": None,+ "file": None,+ "boolean": None,+ "plainText": None,+ }+ ],+ }+ assert expected_att_data in attributes++ assert AttributeValue.objects.count() == value_count+ value.refresh_from_db()+ assert value.name == new_value+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_dropdown_attribute_non_existing_value(+ updated_webhook_mock,+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ product_type.product_attributes.add(color_attribute)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {+ "value": "new color",+ },+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ assert data["product"]["attributes"][0]["values"][0]["name"] == "new color"+ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_dropdown_attribute_existing_value(+ updated_webhook_mock,+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ attribute_value = color_attribute.values.model.objects.first()+ attribute_value_id = graphene.Node.to_global_id(+ "AttributeValue", attribute_value.pk+ )+ attribute_value_name = color_attribute.values.model.objects.first().name+ product_type.product_attributes.add(color_attribute)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {+ "id": attribute_value_id,+ },+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ assert data["product"]["attributes"][0]["values"][0]["name"] == attribute_value_name+ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_dropdown_attribute_existing_value_passed_as_new_value(+ updated_webhook_mock,+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ attribute_value = color_attribute.values.model.objects.first()+ attribute_value_id = graphene.Node.to_global_id(+ "AttributeValue", attribute_value.pk+ )+ attribute_value_name = color_attribute.values.model.objects.first().name+ product_type.product_attributes.add(color_attribute)++ value_count = AttributeValue.objects.count()++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {+ "value": attribute_value_name,+ },+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ assert data["product"]["attributes"][0]["values"][0]["id"] == attribute_value_id+ assert AttributeValue.objects.count() == value_count+ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_dropdown_attribute_null_value(+ updated_webhook_mock,+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ product_type.product_attributes.add(color_attribute)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {+ "value": None,+ },+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ assert not data["product"]["attributes"][0]["values"]+ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_multiselect_attribute_non_existing_values(+ updated_webhook_mock,+ staff_api_client,+ product_with_multiple_values_attributes,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product = product_with_multiple_values_attributes+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute = product.attributes.first().attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)++ value_count = AttributeValue.objects.count()++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "multiselect": [{"value": "new mode 1"}, {"value": "new mode 2"}],+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ values = data["product"]["attributes"][0]["values"]+ assert len(values) == 2+ assert values[0]["name"] == "new mode 1"+ assert values[1]["name"] == "new mode 2"+ updated_webhook_mock.assert_called_once_with(product)++ assert AttributeValue.objects.count() == value_count + 2+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_multiselect_attribute_existing_values(+ updated_webhook_mock,+ staff_api_client,+ product_with_multiple_values_attributes,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product = product_with_multiple_values_attributes+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute = product.attributes.first().attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)+ attr_value_1 = product.attributes.first().values.all()[0]+ attr_value_id_1 = graphene.Node.to_global_id("AttributeValue", attr_value_1.pk)+ attr_value_name_1 = product.attributes.first().values.all()[0].name+ attr_value_2 = product.attributes.first().values.all()[1]+ attr_value_id_2 = graphene.Node.to_global_id("AttributeValue", attr_value_2.pk)+ attr_value_name_2 = product.attributes.first().values.all()[1].name++ associate_attribute_values_to_instance(product, attribute, attr_value_1)+ assert len(product.attributes.first().values.all()) == 1++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "multiselect": [{"id": attr_value_id_1}, {"id": attr_value_id_2}],+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ values = data["product"]["attributes"][0]["values"]+ assert len(values) == 2+ assert values[0]["name"] == attr_value_name_1+ assert values[1]["name"] == attr_value_name_2+ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_multiselect_attribute_new_values_not_created(+ updated_webhook_mock,+ staff_api_client,+ product_with_multiple_values_attributes,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product = product_with_multiple_values_attributes+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute = product.attributes.first().attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)+ attr_value_1 = product.attributes.first().values.all()[0]+ attr_value_id_1 = graphene.Node.to_global_id("AttributeValue", attr_value_1.pk)+ attr_value_name_1 = product.attributes.first().values.all()[0].name+ attr_value_2 = product.attributes.first().values.all()[1]+ attr_value_id_2 = graphene.Node.to_global_id("AttributeValue", attr_value_2.pk)+ attr_value_name_2 = product.attributes.first().values.all()[1].name++ value_count = AttributeValue.objects.count()++ assert len(product.attributes.first().values.all()) == 2++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "multiselect": [+ {"value": attr_value_name_1},+ {"value": attr_value_name_2},+ ],+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not errors+ values = data["product"]["attributes"][0]["values"]+ assert len(values) == 2+ assert values[0]["id"] == attr_value_id_1+ assert values[1]["id"] == attr_value_id_2+ assert AttributeValue.objects.count() == value_count+ updated_webhook_mock.assert_called_once_with(product)+++def test_update_product_with_selectable_attribute_by_both_id_and_value(+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ attribute_value_id = color_attribute.values.model.objects.first().id+ product_type.product_attributes.add(color_attribute)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {"id": attribute_value_id, "value": "new color"},+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["message"] == AttributeInputErrors.ERROR_ID_AND_VALUE[0]+++ "value,expected_result",+ [+ ("", AttributeInputErrors.ERROR_NO_VALUE_GIVEN),+ (" ", AttributeInputErrors.ERROR_BLANK_VALUE),+ (None, AttributeInputErrors.ERROR_NO_VALUE_GIVEN),+ ],+)+def test_update_product_with_selectable_attribute_value_required(+ value,+ expected_result,+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ product_type.product_attributes.add(color_attribute)++ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {+ "value": value,+ },+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["message"] == expected_result[0]+++def test_update_product_with_selectable_attribute_exceed_max_length(+ staff_api_client,+ color_attribute,+ product,+ product_type,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)+ product_type.product_attributes.add(color_attribute)+ max_length = color_attribute.values.model.name.field.max_length++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "dropdown": {"value": "a" * max_length + "a"},+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["message"] == AttributeInputErrors.ERROR_MAX_LENGTH[0]+++def test_update_product_with_multiselect_attribute_by_both_id_and_value(+ staff_api_client,+ product_with_multiple_values_attributes,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product = product_with_multiple_values_attributes+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute = product.attributes.first().attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)+ attr_value = product.attributes.first().values.all()[0]+ attr_value_id = graphene.Node.to_global_id("AttributeValue", attr_value.pk)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "multiselect": [{"id": attr_value_id}, {"value": "new mode"}],+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["message"] == AttributeInputErrors.ERROR_ID_AND_VALUE[0]+++def test_update_product_with_multiselect_attribute_by_id_duplicated(+ staff_api_client,+ product_with_multiple_values_attributes,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product = product_with_multiple_values_attributes+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute = product.attributes.first().attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)+ attr_value = product.attributes.first().values.all()[0]+ attr_value_id = graphene.Node.to_global_id("AttributeValue", attr_value.pk)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "multiselect": [{"id": attr_value_id}, {"id": attr_value_id}],+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["message"] == AttributeInputErrors.ERROR_DUPLICATED_VALUES[0]+++def test_update_product_with_multiselect_attribute_by_name_duplicated(+ staff_api_client,+ product_with_multiple_values_attributes,+ permission_manage_products,+ site_settings,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product = product_with_multiple_values_attributes+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute = product.attributes.first().attribute+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)+ attr_value_name = product.attributes.first().values.all()[0].name++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [+ {+ "id": attribute_id,+ "multiselect": [+ {"value": attr_value_name},+ {"value": attr_value_name},+ ],+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["errors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["message"] == AttributeInputErrors.ERROR_DUPLICATED_VALUES[0]diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex e61be71717..5897a3628d 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -17389,10 +17389,31 @@ input AttributeValueInput {id: ID"""- The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created.+ The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created. This field will be removed in Saleor 4.0."""values: [String!]+ """+ Attribute value ID.++ Added in Saleor 3.9.+ """+ dropdown: AttributeValueSelectableTypeInput++ """+ List of attribute value IDs.++ Added in Saleor 3.9.+ """+ multiselect: [AttributeValueSelectableTypeInput!]++ """+ Numeric value of an attribute.++ Added in Saleor 3.9.+ """+ numeric: String+"""URL of the file attribute. Every time, a new value is created."""file: String@@ -17418,6 +17439,21 @@ input AttributeValueInput {dateTime: DateTime}+"""+Represents attribute value. If no ID provided, value will be resolved.++Added in Saleor 3.9.+"""+input AttributeValueSelectableTypeInput {+ """ID of an attribute value."""+ id: ID++ """+ The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created.+ """+ value: String+}+"""Deletes a product.