Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix assigning attributes by external reference (#18369)
Iga Karbowiakb093ceea356f
diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.pyindex e6e8ca7fa1..5ef78a7204 100644--- a/saleor/attribute/tests/fixtures/attribute.py+++ b/saleor/attribute/tests/fixtures/attribute.py@@ -199,7 +199,7 @@ def multiselect_attribute(db, attribute_generator, attribute_values_generator):filterable_in_dashboard=True,available_in_grid=True,)- slugs = ["choice-1", "choice-1"]+ slugs = ["choice-1", "choice-2"]names = ["Choice 1", "Choice 2"]attribute_values_generator(attribute=attribute,diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex 2d2da6a16a..ecba8d309a 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -1,3 +1,4 @@+import datetimefrom collections import defaultdictimport graphene@@ -7,11 +8,17 @@ from django.core.exceptions import ValidationErrorfrom graphql import GraphQLErrorfrom ....attribute import AttributeInputType+from ....attribute.models import AttributeValue+from ....attribute.utils import associate_attribute_values_to_instancefrom ....product.error_codes import ProductErrorCodefrom ..enums import AttributeValueBulkActionEnumfrom ..shared_filters import validate_attribute_value_inputfrom ..utils.attribute_assignment import AttributeAssignmentMixin-from ..utils.shared import AttrValuesForSelectableFieldInput, AttrValuesInput+from ..utils.shared import (+ AttrValuesForSelectableFieldInput,+ AttrValuesInput,+ has_input_modified_attribute_values,+)from ..utils.type_handlers import (FileAttributeHandler,MultiSelectableAttributeHandler,@@ -1982,6 +1989,37 @@ def test_prepare_attribute_values_that_gives_the_same_slug(color_attribute):assert results[2][1].name == new_value_2+def test_pre_save_multiselect_with_id(+ color_attribute,+ product,+):+ # given+ color_attribute.input_type = AttributeInputType.MULTISELECT+ color_attribute.save(update_fields=["input_type"])++ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ multiselect=[+ AttrValuesForSelectableFieldInput(+ id=graphene.Node.to_global_id("AttributeValue", value.pk)+ )+ for value in color_attribute.values.all()+ ],+ )+ handler = MultiSelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [+ (AttributeValueBulkActionEnum.NONE, value)+ for value in color_attribute.values.all()+ ]++def test_pre_save_multiselect_external_reference_action(color_attribute, product):# givencolor_attribute.input_type = AttributeInputType.MULTISELECT@@ -2010,6 +2048,102 @@ def test_pre_save_multiselect_external_reference_action(color_attribute, product]+def test_pre_save_multiselect_external_reference_and_value(+ color_attribute,+ product,+):+ # given+ color_attribute.input_type = AttributeInputType.MULTISELECT+ color_attribute.save(update_fields=["input_type"])++ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ multiselect=[+ AttrValuesForSelectableFieldInput(+ external_reference=value.external_reference, value=value.name+ )+ for value in color_attribute.values.all()+ ],+ )+ handler = MultiSelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [+ (AttributeValueBulkActionEnum.NONE, value)+ for value in color_attribute.values.all()+ ]+++def test_pre_save_multiselect_external_reference_and_invalid_value(+ multiselect_attribute,+ product,+):+ # given+ values = list(multiselect_attribute.values.all())+ external_refs = []+ for value in values:+ value.external_reference = f"ext-ref-{value.pk}"+ external_refs.append(value.external_reference)++ AttributeValue.objects.bulk_update(values, ["external_reference"])++ values_input = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", multiselect_attribute.pk),+ content_type=None,+ references=[],+ multiselect=[+ AttrValuesForSelectableFieldInput(+ external_reference=external_ref, value="not-matching-value"+ )+ for external_ref in external_refs+ ],+ )+ handler = MultiSelectableAttributeHandler(multiselect_attribute, values_input)++ # when & then+ with pytest.raises(ValidationError) as exc_info:+ handler.pre_save_value(product)++ message = str(exc_info.value)+ assert "Attribute value with external reference" in message+++def test_pre_save_multiselect_external_reference_and_new_value(+ color_attribute,+ product,+):+ # given+ color_attribute.input_type = AttributeInputType.MULTISELECT+ color_attribute.save(update_fields=["input_type"])+ new_value = "New Color"++ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ multiselect=[+ AttrValuesForSelectableFieldInput(+ external_reference="new-external-reference", value=new_value+ )+ ],+ )+ handler = MultiSelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert len(result) == 1+ action, value = result[0]+ assert action == AttributeValueBulkActionEnum.CREATE+ assert value.name == new_value++@pytest.mark.parametrize(("attribute_fixture", "value_payload"),[@@ -2136,3 +2270,745 @@ def test_validate_attribute_value_input_combines_invalid_entries(message = str(exc_info.value)assert "Incorrect input for attributes on position: 0,1,2" in messageassert "do not match the attribute input type" in message+++def test_pre_save_dropdown_with_id(+ color_attribute,+ product,+):+ # given+ first_value = color_attribute.values.first()+ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ dropdown=AttrValuesForSelectableFieldInput(+ id=graphene.Node.to_global_id("AttributeValue", first_value.pk)+ ),+ )+ handler = SelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [(AttributeValueBulkActionEnum.NONE, first_value)]+++def test_pre_save_dropdown_external_reference_action(+ color_attribute,+ product,+):+ # given+ first_value = color_attribute.values.first()+ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ dropdown=AttrValuesForSelectableFieldInput(+ external_reference=first_value.external_reference+ ),+ )+ handler = SelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [(AttributeValueBulkActionEnum.NONE, first_value)]+++def test_pre_save_dropdown_external_reference_and_value(+ color_attribute,+ product,+):+ # given+ first_value = color_attribute.values.first()+ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ dropdown=AttrValuesForSelectableFieldInput(+ external_reference=first_value.external_reference, value=first_value.name+ ),+ )+ handler = SelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [(AttributeValueBulkActionEnum.NONE, first_value)]+++def test_pre_save_dropdown_external_reference_and_new_value(+ color_attribute,+ product,+):+ # given+ new_value = "New Color"++ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ content_type=None,+ references=[],+ dropdown=AttrValuesForSelectableFieldInput(+ external_reference="new-external-reference", value=new_value+ ),+ )+ handler = SelectableAttributeHandler(color_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert len(result) == 1+ action, value = result[0]+ assert action == AttributeValueBulkActionEnum.CREATE+ assert value.name == new_value+++def test_pre_save_swatch_with_id(+ swatch_attribute,+ product,+):+ # given+ first_value = swatch_attribute.values.first()+ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", swatch_attribute.pk),+ content_type=None,+ references=[],+ swatch=AttrValuesForSelectableFieldInput(+ id=graphene.Node.to_global_id("AttributeValue", first_value.pk)+ ),+ )+ handler = SelectableAttributeHandler(swatch_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [(AttributeValueBulkActionEnum.NONE, first_value)]+++def test_pre_save_swatch_external_reference(+ swatch_attribute,+ product,+):+ # given+ first_value = swatch_attribute.values.first()+ external_reference = "swatch-external-reference"+ first_value.external_reference = external_reference+ first_value.save(update_fields=["external_reference"])++ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", swatch_attribute.pk),+ content_type=None,+ references=[],+ swatch=AttrValuesForSelectableFieldInput(external_reference=external_reference),+ )+ handler = SelectableAttributeHandler(swatch_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [(AttributeValueBulkActionEnum.NONE, first_value)]+++def test_pre_save_swatch_external_reference_and_value(+ swatch_attribute,+ product,+):+ # given+ first_value = swatch_attribute.values.first()+ external_reference = "swatch-external-reference"+ first_value.external_reference = external_reference+ first_value.save(update_fields=["external_reference"])+ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", swatch_attribute.pk),+ content_type=None,+ references=[],+ swatch=AttrValuesForSelectableFieldInput(+ external_reference=external_reference, value=first_value.name+ ),+ )+ handler = SelectableAttributeHandler(swatch_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert result == [(AttributeValueBulkActionEnum.NONE, first_value)]+++def test_pre_save_swatch_external_reference_and_new_value(+ swatch_attribute,+ product,+):+ # given+ new_value = "New Color"++ values = AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", swatch_attribute.pk),+ content_type=None,+ references=[],+ swatch=AttrValuesForSelectableFieldInput(+ external_reference="new-external-reference", value=new_value+ ),+ )+ handler = SelectableAttributeHandler(swatch_attribute, values)++ # when+ result = handler.pre_save_value(product)++ # then+ assert len(result) == 1+ action, value = result[0]+ assert action == AttributeValueBulkActionEnum.CREATE+ assert value.name == new_value+++def test_has_input_modified_attribute_values_no_changes_boolean(+ variant, boolean_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(boolean_attribute)+ value = boolean_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {boolean_attribute.id: [boolean_attribute.values.first()]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.GET_OR_CREATE: {+ boolean_attribute: [+ {+ "attribute": boolean_attribute,+ "slug": value.slug,+ "defaults": {+ "name": f"{boolean_attribute.name}: Yes",+ "boolean": True,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_boolean(+ variant, boolean_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(boolean_attribute)+ associate_attribute_values_to_instance(+ variant,+ {boolean_attribute.id: [boolean_attribute.values.first()]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.GET_OR_CREATE: {+ boolean_attribute: [+ {+ "attribute": boolean_attribute,+ "slug": f"{boolean_attribute.id}_False",+ "defaults": {+ "name": f"{boolean_attribute.name}: No",+ "boolean": False,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_dropdown(+ variant, color_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(color_attribute)+ first_value = color_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {color_attribute.id: [first_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.NONE: {color_attribute: [first_value]}+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_dropdown(+ variant, color_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(color_attribute)+ first_value = color_attribute.values.first()+ last_value = color_attribute.values.last()+ associate_attribute_values_to_instance(+ variant,+ {color_attribute.id: [first_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.NONE: {color_attribute: [last_value]}+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_multiselect(+ variant, multiselect_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(multiselect_attribute)+ all_values = list(multiselect_attribute.values.all())+ associate_attribute_values_to_instance(+ variant,+ {multiselect_attribute.id: all_values},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.NONE: {multiselect_attribute: all_values}+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_multiselect_order(+ variant, multiselect_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(multiselect_attribute)+ all_values = list(multiselect_attribute.values.all())+ associate_attribute_values_to_instance(+ variant,+ {multiselect_attribute.id: all_values},+ )+ # Change order of values+ reversed_values = list(reversed(all_values))+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.NONE: {multiselect_attribute: reversed_values}+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_plain_text(+ variant, plain_text_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(plain_text_attribute)+ text_value = plain_text_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {plain_text_attribute.id: [text_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ plain_text_attribute: [+ {+ "attribute": plain_text_attribute,+ "slug": f"{variant.id}_{plain_text_attribute.id}",+ "defaults": {+ "plain_text": text_value.plain_text,+ "name": text_value.name,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_plain_text(+ variant, plain_text_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(plain_text_attribute)+ text_value = plain_text_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {plain_text_attribute.id: [text_value]},+ )+ different_text = "Different text"+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ plain_text_attribute: [+ {+ "attribute": plain_text_attribute,+ "slug": f"{variant.id}_{plain_text_attribute.id}",+ "defaults": {+ "plain_text": different_text,+ "name": different_text[:200],+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_rich_text(+ variant, rich_text_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(rich_text_attribute)+ rich_text_value = rich_text_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {rich_text_attribute.id: [rich_text_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ rich_text_attribute: [+ {+ "attribute": rich_text_attribute,+ "slug": f"{variant.id}_{rich_text_attribute.id}",+ "defaults": {+ "rich_text": rich_text_value.rich_text,+ "name": rich_text_value.name,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_rich_text(+ variant, rich_text_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(rich_text_attribute)+ rich_text_value = rich_text_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {rich_text_attribute.id: [rich_text_value]},+ )+ different_rich_text = {+ "blocks": [{"type": "paragraph", "data": {"text": "New content"}}]+ }+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ rich_text_attribute: [+ {+ "attribute": rich_text_attribute,+ "slug": f"{variant.id}_{rich_text_attribute.id}",+ "defaults": {+ "rich_text": different_rich_text,+ "name": "New content"[:200],+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_numeric(+ variant, numeric_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(numeric_attribute)+ numeric_value = numeric_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {numeric_attribute.id: [numeric_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ numeric_attribute: [+ {+ "attribute": numeric_attribute,+ "slug": f"{variant.id}_{numeric_attribute.id}",+ "defaults": {+ "name": str(numeric_value.numeric),+ "numeric": numeric_value.numeric,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_numeric(+ variant, numeric_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(numeric_attribute)+ numeric_value = numeric_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {numeric_attribute.id: [numeric_value]},+ )+ different_numeric = 100.5+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ numeric_attribute: [+ {+ "attribute": numeric_attribute,+ "slug": f"{variant.id}_{numeric_attribute.id}",+ "defaults": {+ "name": str(different_numeric),+ "numeric": different_numeric,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_date(variant, date_attribute):+ # given+ variant.product.product_type.variant_attributes.add(date_attribute)+ date_value = date_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {date_attribute.id: [date_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ date_attribute: [+ {+ "attribute": date_attribute,+ "slug": f"{variant.id}_{date_attribute.id}",+ "defaults": {+ "name": str(date_value.date_time.date()),+ "date_time": date_value.date_time,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_date(variant, date_attribute):+ # given+ variant.product.product_type.variant_attributes.add(date_attribute)+ date_value = date_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {date_attribute.id: [date_value]},+ )+ different_date = datetime.date(2021, 1, 1)+ different_date_time = datetime.datetime.combine(+ different_date, datetime.time.min, tzinfo=datetime.UTC+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ date_attribute: [+ {+ "attribute": date_attribute,+ "slug": f"{variant.id}_{date_attribute.id}",+ "defaults": {+ "name": str(different_date),+ "date_time": different_date_time,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_no_changes_date_time(+ variant, date_time_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(date_time_attribute)+ date_time_value = date_time_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {date_time_attribute.id: [date_time_value]},+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ date_time_attribute: [+ {+ "attribute": date_time_attribute,+ "slug": f"{variant.id}_{date_time_attribute.id}",+ "defaults": {+ "name": str(date_time_value.date_time),+ "date_time": date_time_value.date_time,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is False+++def test_has_input_modified_attribute_values_with_changes_date_time(+ variant, date_time_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(date_time_attribute)+ date_time_value = date_time_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {date_time_attribute.id: [date_time_value]},+ )+ different_date_time = datetime.datetime(2021, 5, 10, 14, 30, tzinfo=datetime.UTC)+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ date_time_attribute: [+ {+ "attribute": date_time_attribute,+ "slug": f"{variant.id}_{date_time_attribute.id}",+ "defaults": {+ "name": str(different_date_time),+ "date_time": different_date_time,+ },+ }+ ]+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_multiple_attributes(+ variant, color_attribute, size_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(color_attribute, size_attribute)+ color_first = color_attribute.values.first()+ size_first = size_attribute.values.first()+ size_last = size_attribute.values.last()+ associate_attribute_values_to_instance(+ variant,+ {+ color_attribute.id: [color_first],+ size_attribute.id: [size_first],+ },+ )+ # Change only one attribute+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.NONE: {+ color_attribute: [color_first],+ size_attribute: [size_last],+ }+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is True+++def test_has_input_modified_attribute_values_mixed_bulk_actions(+ variant, color_attribute, plain_text_attribute+):+ # given+ variant.product.product_type.variant_attributes.add(+ color_attribute, plain_text_attribute+ )+ color_first = color_attribute.values.first()+ text_value = plain_text_attribute.values.first()+ associate_attribute_values_to_instance(+ variant,+ {+ color_attribute.id: [color_first],+ plain_text_attribute.id: [text_value],+ },+ )+ pre_save_bulk_data = {+ AttributeValueBulkActionEnum.NONE: {color_attribute: [color_first]},+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ plain_text_attribute: [+ {+ "attribute": plain_text_attribute,+ "slug": f"{variant.id}_{plain_text_attribute.id}",+ "defaults": {+ "plain_text": text_value.plain_text,+ "name": text_value.name,+ },+ }+ ]+ },+ }++ # when+ result = has_input_modified_attribute_values(variant, pre_save_bulk_data)++ # then+ assert result is Falsediff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.pyindex 7d022d4dad..1d0018acfe 100644--- a/saleor/graphql/attribute/utils/attribute_assignment.py+++ b/saleor/graphql/attribute/utils/attribute_assignment.py@@ -42,6 +42,9 @@ if TYPE_CHECKING:T_INPUT_MAP = list[tuple["attribute_models.Attribute", "AttrValuesInput"]]+T_PRE_SAVE_BULK = dict[+ AttributeValueBulkActionEnum, dict[attribute_models.Attribute, list]+]class AttributeAssignmentMixin:@@ -270,9 +273,44 @@ class AttributeAssignmentMixin:errors.append(error)@classmethod- def save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):- """Save the cleaned input against the given instance."""- pre_save_bulk: dict = defaultdict(lambda: defaultdict(list))+ def pre_save_values(+ cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP+ ) -> T_PRE_SAVE_BULK:+ """Prepare attribute values data for bulk database operations.++ Example return structure:+ {+ AttributeValueBulkActionEnum.CREATE: {+ <Attribute>: [<AttributeValue>, <AttributeValue>],+ ...+ },+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE: {+ <Attribute>: [+ {+ "attribute": <Attribute>,+ "slug": "instance_id_attribute_id",+ "defaults": {"name": "...", "plain_text": "..."}+ }+ ],+ ...+ },+ AttributeValueBulkActionEnum.GET_OR_CREATE: {+ <Attribute>: [+ {+ "attribute": <Attribute>,+ "slug": "attribute_id_True",+ "defaults": {"name": "Attribute: Yes", "boolean": True}+ }+ ],+ ...+ },+ AttributeValueBulkActionEnum.NONE: {+ <Attribute>: [<AttributeValue>, <AttributeValue>],+ ...+ },+ }+ """+ pre_save_bulk: T_PRE_SAVE_BULK = defaultdict(lambda: defaultdict(list))for attribute, values_input in cleaned_input:is_legacy_path = values_input.values and attribute.input_type in {AttributeInputType.DROPDOWN,@@ -301,6 +339,18 @@ class AttributeAssignmentMixin:for action, value_data in prepared_values:pre_save_bulk[action][attribute].append(value_data)+ return pre_save_bulk++ @classmethod+ def save(+ cls,+ instance: T_INSTANCE,+ cleaned_input: T_INPUT_MAP,+ pre_save_bulk: T_PRE_SAVE_BULK | None = None,+ ):+ """Save the cleaned input against the given instance."""+ if pre_save_bulk is None:+ pre_save_bulk = cls.pre_save_values(instance, cleaned_input)attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)attr_val_map = defaultdict(list)diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.pyindex 30dcefcdf0..cde1ef3ec7 100644--- a/saleor/graphql/attribute/utils/shared.py+++ b/saleor/graphql/attribute/utils/shared.py@@ -1,17 +1,17 @@import datetime+import jsonfrom collections import defaultdictfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, NamedTuple, castfrom django.db.models import Modelfrom django.db.models.expressions import Exists, OuterRef-from django.utils.text import slugifyfrom ....attribute import AttributeEntityType, AttributeInputTypefrom ....attribute import models as attribute_modelsfrom ....page import models as page_modelsfrom ....product import models as product_models-from ...product.utils import get_used_attribute_values_for_variant+from ..enums import AttributeValueBulkActionEnumif TYPE_CHECKING:from ....attribute.models import Attribute@@ -145,34 +145,92 @@ def get_variant_assigned_attribute_value_if_exists(def has_input_modified_attribute_values(variant: product_models.ProductVariant,- attributes_data: list[tuple["Attribute", AttrValuesInput]],+ pre_save_bulk_data: dict[+ AttributeValueBulkActionEnum, dict[attribute_models.Attribute, list]+ ],) -> bool:- """Compare already assigned attribute values with values from AttrValuesInput.+ """Compare already assigned attribute values with the input values.++ The change in the attribute values order is also considered a modification.Return:`False` if the attribute values are equal, otherwise `True`."""if variant.product_id is not None:- assigned_attributes = get_used_attribute_values_for_variant(variant)- input_attribute_values: defaultdict[str, list[str]] = defaultdict(list)- for attr, attr_data in attributes_data:- values = get_values_from_attribute_values_input(attr, attr_data)- if attr_data.global_id is not None:- input_attribute_values[attr_data.global_id].extend(values)+ assigned_attributes = get_attribute_to_values_map_for_variant(variant)+ input_attribute_values = get_values_from_pre_save_bulk_data(pre_save_bulk_data)if input_attribute_values != assigned_attributes:return Truereturn False-def get_values_from_attribute_values_input(- attribute: attribute_models.Attribute, attribute_data: AttrValuesInput-) -> list[str]:- """Format attribute values of type FILE."""- if attribute.input_type == AttributeInputType.FILE:- return (- [slugify(attribute_data.file_url.split("/")[-1])]- if attribute_data.file_url- else []- )- return attribute_data.values or []+def get_attribute_to_values_map_for_variant(+ variant: product_models.ProductVariant,+) -> dict[int, list]:+ """Create a dict of attributes values for variant.++ Sample result is:+ {+ "attribute_pk": [AttributeValue1, AttributeValue2],+ "attribute_pk": [AttributeValue3]+ }+ """+ attribute_values: defaultdict[int, list[str | None | datetime.datetime]] = (+ defaultdict(list)+ )+ for assigned_variant_attribute in variant.attributes.all():+ attribute = assigned_variant_attribute.attribute+ attribute_id = attribute.pk+ for attr_value in assigned_variant_attribute.values.all():+ if attribute.input_type == AttributeInputType.PLAIN_TEXT:+ attribute_values[attribute_id].append(attr_value.plain_text)+ elif attribute.input_type == AttributeInputType.RICH_TEXT:+ attribute_values[attribute_id].append(json.dumps(attr_value.rich_text))+ elif attribute.input_type == AttributeInputType.NUMERIC:+ attribute_values[attribute_id].append(str(attr_value.numeric))+ elif attribute.input_type in [+ AttributeInputType.DATE,+ AttributeInputType.DATE_TIME,+ ]:+ attribute_values[attribute_id].append(attr_value.date_time)+ else:+ attribute_values[attribute_id].append(attr_value.slug)+ return attribute_values+++def get_values_from_pre_save_bulk_data(+ pre_save_bulk_data: dict[+ AttributeValueBulkActionEnum, dict[attribute_models.Attribute, list]+ ],+) -> dict[int, list[str | None | datetime.datetime]]:+ input_type_to_field_and_action = {+ AttributeInputType.PLAIN_TEXT: ("plain_text", None),+ AttributeInputType.RICH_TEXT: ("rich_text", json.dumps),+ AttributeInputType.NUMERIC: ("numeric", str),+ AttributeInputType.DATE: ("date_time", None),+ AttributeInputType.DATE_TIME: ("date_time", None),+ }+ input_attribute_values: defaultdict[int, list[str | None | datetime.datetime]] = (+ defaultdict(list)+ )+ for action, attributes in pre_save_bulk_data.items():+ for attr, values_data in attributes.items():+ values = []+ if action == AttributeValueBulkActionEnum.GET_OR_CREATE:+ values = [value["slug"] for value in values_data]+ elif action == AttributeValueBulkActionEnum.UPDATE_OR_CREATE:+ field_name, transform = input_type_to_field_and_action.get(+ attr.input_type, (None, None)+ )+ if field_name:+ values = [+ transform(value["defaults"][field_name])+ if transform+ else value["defaults"][field_name]+ for value in values_data+ ]+ else:+ values = [value.slug for value in values_data]+ input_attribute_values[attr.pk].extend(values)+ return input_attribute_valuesdiff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.pyindex ccc8f2e0c6..5080becb20 100644--- a/saleor/graphql/attribute/utils/type_handlers.py+++ b/saleor/graphql/attribute/utils/type_handlers.py@@ -15,7 +15,6 @@ from ....attribute import models as attribute_modelsfrom ....attribute.models import AttributeValuefrom ....core.utils import (generate_unique_slug,- prepare_unique_attribute_value_slug,prepare_unique_slug,)from ....core.utils.editorjs import clean_editor_js@@ -166,6 +165,27 @@ class AttributeTypeHandler(abc.ABC):return results+ def prepare_attribute_values_with_external_reference(+ self, values: list[tuple[str, str]]+ ) -> list[tuple]:+ existing_slugs = self.get_existing_slugs(self.attribute, [v[1] for v in values])++ results = []+ for ext_ref, value_str in values:+ unique_slug = prepare_unique_slug(+ slugify(unidecode(value_str)), existing_slugs+ )+ new_value = AttributeValue(+ attribute=self.attribute,+ name=value_str,+ slug=unique_slug,+ external_reference=ext_ref,+ )+ results.append((AttributeValueBulkActionEnum.CREATE, new_value))+ existing_slugs.add(unique_slug)++ return results+@staticmethoddef get_existing_slugs(attribute: attribute_models.Attribute, values: list[str]):lookup = Q()@@ -265,39 +285,59 @@ class SelectableAttributeHandler(AttributeTypeHandler):)if ext_ref and value:- slug = prepare_unique_attribute_value_slug(- self.attribute, slugify(unidecode(value))- )- value_obj = AttributeValue(- attribute=self.attribute,- name=value,- slug=slug,- external_reference=ext_ref,- )- return [(AttributeValueBulkActionEnum.CREATE, value_obj)]+ return self._parse_external_reference_and_value(ext_ref, value)if ext_ref:- value = attribute_models.AttributeValue.objects.get( # type: ignore[assignment]+ value_instance = attribute_models.AttributeValue.objects.filter(external_reference=ext_ref- )- if not value:+ ).first()+ if not value_instance:raise ValidationError("Attribute value with given externalReference can't be found")- return [(AttributeValueBulkActionEnum.NONE, value)]+ return [(AttributeValueBulkActionEnum.NONE, value_instance)]if id:_, attr_value_id = from_global_id_or_error(id)- value = attribute_models.AttributeValue.objects.get(pk=attr_value_id) # type: ignore[assignment]- if not value:+ value_instance = attribute_models.AttributeValue.objects.filter(+ pk=attr_value_id+ ).first()+ if not value_instance:raise ValidationError("Attribute value with given ID can't be found")- return [(AttributeValueBulkActionEnum.NONE, value)]+ return [(AttributeValueBulkActionEnum.NONE, value_instance)]if value:return self.prepare_attribute_values(self.attribute, [value])return []+ def _parse_external_reference_and_value(+ self, external_reference: str, attr_value: str | None+ ) -> list[tuple[AttributeValueBulkActionEnum, AttributeValue]]:+ """Get or create an AttributeValue by external reference."""+ value_instance = attribute_models.AttributeValue.objects.filter(+ external_reference=external_reference+ ).first()+ if value_instance:+ if value_instance.name != attr_value:+ raise ValidationError(+ f"Attribute value with external reference '{external_reference}' already exists "+ f"with different value '{value_instance.name}'."+ )+ return [+ (+ AttributeValueBulkActionEnum.NONE,+ value_instance,+ )+ ]+ if not attr_value:+ raise ValidationError(+ f"Attribute value with given external reference can't be found: {external_reference}"+ )+ return self.prepare_attribute_values_with_external_reference(+ [(external_reference, attr_value or external_reference)]+ )+class MultiSelectableAttributeHandler(SelectableAttributeHandler):"""Handler for Multiselect attribute type."""@@ -353,27 +393,73 @@ class MultiSelectableAttributeHandler(SelectableAttributeHandler):if not multi_values:return []+ ext_refs = [+ value.external_reference+ for value in multi_values+ if value.external_reference+ ]+ ids = [+ from_global_id_or_error(v_input.id, "AttributeValue")[1]+ for v_input in multi_values+ if v_input.id+ ]+ ext_ref_to_value_map = self.attribute.values.filter(+ external_reference__in=ext_refs+ ).in_bulk(field_name="external_reference")+ id_to_value_map = self.attribute.values.filter(id__in=ids).in_bulk()+results = []values_to_create = []- pks_to_fetch = []- ext_refs_to_fetch = []+ external_refs_with_value_to_create = []+ invalid_ids = []+ invalid_ext_refs = []+ invalid_ext_refs_with_current_value = []for v_input in multi_values:if v_input.id:_, pk = from_global_id_or_error(v_input.id, "AttributeValue")- pks_to_fetch.append(pk)+ if value_instance := id_to_value_map.get(int(pk)):+ results.append((AttributeValueBulkActionEnum.NONE, value_instance))+ else:+ invalid_ids.append(v_input.id)elif v_input.external_reference and not v_input.value:- ext_refs_to_fetch.append(v_input.external_reference)+ if value_instance := ext_ref_to_value_map.get(+ v_input.external_reference+ ):+ results.append((AttributeValueBulkActionEnum.NONE, value_instance))+ else:+ invalid_ext_refs.append(v_input.external_reference)+ elif v_input.external_reference and v_input.value:+ if value_instance := ext_ref_to_value_map.get(+ v_input.external_reference+ ):+ if value_instance.name != v_input.value:+ invalid_ext_refs_with_current_value.append(+ (v_input.external_reference, value_instance.name)+ )+ continue+ results.append((AttributeValueBulkActionEnum.NONE, value_instance))+ continue+ external_refs_with_value_to_create.append(+ (v_input.external_reference, v_input.value)+ )elif v_input.value:values_to_create.append(v_input.value)- # Fetch existing values by PK and external reference- existing_values = self.attribute.values.filter(- Q(pk__in=pks_to_fetch) | Q(external_reference__in=ext_refs_to_fetch)- )- results.extend(- [(AttributeValueBulkActionEnum.NONE, val) for val in existing_values]- )+ if invalid_ids:+ raise ValidationError(+ f"Attribute value(s) with given ID(s) can't be found: {', '.join(invalid_ids)}"+ )+ if invalid_ext_refs:+ raise ValidationError(+ f"Attribute value(s) with given external reference(s) can't be found: {', '.join(invalid_ext_refs)}"+ )+ if invalid_ext_refs_with_current_value:+ error_messages = [+ f"Attribute value with external reference '{ext_ref}' already exists with different value '{existing_value}'."+ for ext_ref, existing_value in invalid_ext_refs_with_current_value+ ]+ raise ValidationError("/n".join(error_messages))# Prepare new valuesif values_to_create:@@ -381,6 +467,14 @@ class MultiSelectableAttributeHandler(SelectableAttributeHandler):self.prepare_attribute_values(self.attribute, values_to_create))+ # Prepare new values with external references+ if external_refs_with_value_to_create:+ results.extend(+ self.prepare_attribute_values_with_external_reference(+ external_refs_with_value_to_create+ )+ )+return resultsdiff --git a/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py b/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.pyindex 4816f2ec18..abe63592f6 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py@@ -1,12 +1,11 @@-from collections import defaultdict-+import graphenefrom django.core.exceptions import ValidationErrorfrom .....attribute import models as attribute_modelsfrom .....product.error_codes import ProductErrorCode+from .....product.models import ProductTypefrom ....attribute.utils.shared import (AttrValuesInput,- get_values_from_attribute_values_input,)T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]@@ -51,20 +50,27 @@ def clean_preorder_settings(cleaned_input: dict):cleaned_input["preorder_end_date"] = preorder_settings.get("end_date")-def validate_duplicated_attribute_values(- attributes_data: T_INPUT_MAP,- used_attribute_values: list[dict[str, list[str]]],-):- attribute_values: defaultdict[str, list[str]] = defaultdict(list)- for attr, attr_data in attributes_data:- values = get_values_from_attribute_values_input(attr, attr_data)- if attr_data.global_id:- attribute_values[attr_data.global_id].extend(values)+def clean_variant_attributes(product_type: "ProductType", attributes: list[dict]):+ variant_attributes_ids = set()+ variant_attributes_external_refs = set()+ for attr_id, external_ref in product_type.variant_attributes.values_list(+ "id", "external_reference"+ ):+ if external_ref:+ variant_attributes_external_refs.add(external_ref)+ variant_attributes_ids.add(graphene.Node.to_global_id("Attribute", attr_id))- if attribute_values in used_attribute_values:+ attributes_ids = {attr["id"] for attr in attributes if attr.get("id") or []}+ attrs_external_refs = {+ attr["external_reference"]+ for attr in attributes+ if attr.get("external_reference") or []+ }+ invalid_attributes = attributes_ids - variant_attributes_ids+ invalid_attributes |= attrs_external_refs - variant_attributes_external_refs+ if len(invalid_attributes) > 0:raise ValidationError(- "Duplicated attribute values for product variant.",- code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,- params={"attributes": attribute_values.keys()},+ "Given attributes are not a variant attributes.",+ code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.value,+ params={"attributes": invalid_attributes},)- used_attribute_values.append(attribute_values)diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.pyindex 47cded4f4e..bbbaba67be 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py@@ -28,7 +28,6 @@ from ...types import ProductVariantfrom ...utils import (clean_variant_sku,create_stocks,- get_used_variants_attribute_values,)from ..product.product_create import StockInputfrom . import product_variant_cleaner as cleaner@@ -156,24 +155,12 @@ class ProductVariantCreate(DeprecatedModelMutation):def clean_attributes(cls, cleaned_input: dict, instance: models.ProductVariant):product = cls.get_product(cleaned_input)product_type = product.product_type- used_attribute_values = get_used_variants_attribute_values(product)- variant_attributes_ids = {- graphene.Node.to_global_id("Attribute", attr_id)- for attr_id in list(- product_type.variant_attributes.all().values_list("pk", flat=True)- )- }-- attributes = cleaned_input.get("attributes")- attributes_ids = {attr["id"] for attr in attributes or []}- invalid_attributes = attributes_ids - variant_attributes_ids- if len(invalid_attributes) > 0:- raise ValidationError(- "Given attributes are not a variant attributes.",- code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.value,- params={"attributes": invalid_attributes},- )+ attributes = cleaned_input.get("attributes") or []+ try:+ cleaner.clean_variant_attributes(product_type, attributes)+ except ValidationError as e:+ raise ValidationError({"attributes": e}) from e# Run the validation only if product type is configurableif product_type.has_variants:@@ -187,9 +174,6 @@ class ProductVariantCreate(DeprecatedModelMutation):cleaned_attributes: T_INPUT_MAP = (AttributeAssignmentMixin.clean_input(attributes, attributes_qs))- cleaner.validate_duplicated_attribute_values(- cleaned_attributes, used_attribute_values- )cleaned_input["attributes"] = cleaned_attributeselif product_type.variant_attributes.filter(value_required=True):# if attributes were not provided on creation@@ -259,7 +243,10 @@ class ProductVariantCreate(DeprecatedModelMutation):cls.create_variant_stocks(instance, stocks)attributes = cleaned_input.get("attributes")if attributes:- AttributeAssignmentMixin.save(instance, attributes)+ try:+ AttributeAssignmentMixin.save(instance, attributes)+ except ValidationError as e:+ raise ValidationError({"attributes": e}) from eif not instance.name:generate_and_set_variant_name(instance, cleaned_input.get("sku"))diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.pyindex d9900a498d..6d4e4d8d3e 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py@@ -27,7 +27,7 @@ from ....core.validators import validate_one_of_args_is_in_mutationfrom ....meta.inputs import MetadataInputfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import ProductVariant-from ...utils import clean_variant_sku, get_used_variants_attribute_values+from ...utils import clean_variant_skufrom ..utils import PRODUCT_VARIANT_UPDATE_FIELDSfrom . import product_variant_cleaner as cleanerfrom .product_variant_create import ProductVariantInput@@ -118,30 +118,36 @@ class ProductVariantUpdate(DeprecatedModelMutation):cleaner.clean_weight(cleaned_input)cleaner.clean_quantity_limit(cleaned_input)- attribute_modified = cls.clean_attributes(cleaned_input, instance)+ cls.clean_attributes(cleaned_input, instance)if "sku" in cleaned_input:cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))cleaner.clean_preorder_settings(cleaned_input)- return cleaned_input, attribute_modified+ return cleaned_input@classmethoddef clean_attributes(cls, cleaned_input: dict, instance: models.ProductVariant):- attribute_modified = Falseproduct = instance.productproduct_type = product.product_type- used_attribute_values = get_used_variants_attribute_values(product)- variant_attributes_ids = {- graphene.Node.to_global_id("Attribute", attr_id)- for attr_id in list(- product_type.variant_attributes.all().values_list("pk", flat=True)- )+ variant_attributes_ids = set()+ variant_attributes_external_refs = set()+ for attr_id, external_ref in product_type.variant_attributes.values_list(+ "id", "external_reference"+ ):+ if external_ref:+ variant_attributes_external_refs.add(external_ref)+ variant_attributes_ids.add(graphene.Node.to_global_id("Attribute", attr_id))++ attributes = cleaned_input.get("attributes") or []+ attributes_ids = {attr["id"] for attr in attributes if attr.get("id") or []}+ attrs_external_refs = {+ attr["external_reference"]+ for attr in attributes+ if attr.get("external_reference") or []}-- attributes = cleaned_input.get("attributes")- attributes_ids = {attr["id"] for attr in attributes or []}invalid_attributes = attributes_ids - variant_attributes_ids+ invalid_attributes |= attrs_external_refs - variant_attributes_external_refsif len(invalid_attributes) > 0:raise ValidationError("Given attributes are not a variant attributes.",@@ -163,14 +169,6 @@ class ProductVariantUpdate(DeprecatedModelMutation):attributes, attributes_qs, creation=False))- # if assigned attributes is getting updated run duplicated attribute validation- attribute_modified = has_input_modified_attribute_values(- instance, cleaned_attributes- )- if attribute_modified:- cleaner.validate_duplicated_attribute_values(- cleaned_attributes, used_attribute_values- )cleaned_input["attributes"] = cleaned_attributesexcept ValidationError as e:@@ -182,8 +180,6 @@ class ProductVariantUpdate(DeprecatedModelMutation):ProductErrorCode.INVALID.value,)- return attribute_modified-@classmethoddef set_track_inventory(cls, _info, instance, cleaned_input):track_inventory = cleaned_input.get("track_inventory")@@ -200,8 +196,7 @@ class ProductVariantUpdate(DeprecatedModelMutation):cls,instance_tracker: InstanceTracker,cleaned_input,- attribute_modified: bool,- ) -> tuple[bool, bool]:+ ) -> tuple[bool, bool, bool]:instance = cast(models.ProductVariant, instance_tracker.instance)modified_instance_fields = instance_tracker.get_modified_fields()metadata_modified = (@@ -221,9 +216,8 @@ class ProductVariantUpdate(DeprecatedModelMutation):refresh_product_search_index = True# handle attributes+ attribute_modified = cls._save_attributes(instance, cleaned_input)if attribute_modified:- attributes_data = cleaned_input.get("attributes")- AttributeAssignmentMixin.save(instance, attributes_data)refresh_product_search_index = True# handle product@@ -238,7 +232,28 @@ class ProductVariantUpdate(DeprecatedModelMutation):if product_update_fields:instance.product.save(update_fields=product_update_fields)- return bool(modified_instance_fields), metadata_modified+ return bool(modified_instance_fields), metadata_modified, attribute_modified++ @classmethod+ def _save_attributes(cls, instance, cleaned_input) -> bool:+ attribute_modified = False+ if attributes_data := cleaned_input.get("attributes"):+ try:+ pre_save_bulk = AttributeAssignmentMixin.pre_save_values(+ instance, attributes_data+ )+ if attribute_modified := has_input_modified_attribute_values(+ instance,+ pre_save_bulk,+ ):+ AttributeAssignmentMixin.save(+ instance,+ attributes_data,+ pre_save_bulk,+ )+ except ValidationError as e:+ raise ValidationError({"attributes": e}) from e+ return attribute_modified@classmethoddef construct_instance(cls, instance, cleaned_input) -> models.ProductVariant:@@ -317,15 +332,15 @@ class ProductVariantUpdate(DeprecatedModelMutation):instance = cast(models.ProductVariant, instance)instance_tracker = InstanceTracker(instance, cls.FIELDS_TO_TRACK)- cleaned_input, attribute_modified = cls.clean_input(info, instance, input)+ cleaned_input = cls.clean_input(info, instance, input)cls.handle_metadata(instance, cleaned_input)cls.construct_instance(instance, cleaned_input)cls.clean_instance(info, instance)- variant_modified, metadata_modified = cls._save(- instance_tracker, cleaned_input, attribute_modified+ variant_modified, metadata_modified, attribute_modified = cls._save(+ instance_tracker, cleaned_input)cls._save_m2m(info, instance, cleaned_input)cls._post_save_action(diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex 5c23904a82..eaffc3c45e 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -2232,6 +2232,159 @@ def test_product_bulk_create_with_variants(assert attribute_assignment.values.count() == 1+def test_product_bulk_create_with_variants_and_attributes_by_external_reference(+ staff_api_client,+ product_type,+ category,+ size_attribute,+ description_json,+ permission_manage_products,+):+ # given+ description_json = json.dumps(description_json)+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)++ product_name_1 = "test name 1"+ product_name_2 = "test name 2"+ base_product_slug = "product-test-slug"+ product_charge_taxes = True+ product_tax_rate = "STANDARD"++ product_type.product_attributes.add(size_attribute)+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)+ attribute_external_ref = "size"+ size_attribute.external_reference = attribute_external_ref+ size_attribute.save(update_fields=["external_reference"])++ attribute_value = size_attribute.values.first()+ value_external_ref = "size-value-external-ref"+ attribute_value.external_reference = value_external_ref+ attribute_value.save(update_fields=["external_reference"])++ sku_1 = str(uuid4())[:12]+ variant_1_name = "new-variant-1-name"++ sku_2 = str(uuid4())[:12]+ variant_2_name = "new-variant-2-name"++ sku_3 = str(uuid4())[:12]+ variant_3_name = "new-variant-3-name"++ variants_prod_1 = [+ {+ "sku": sku_1,+ "weight": 2.5,+ "trackInventory": True,+ "name": variant_1_name,+ "attributes": [+ {+ "id": size_attr_id,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attribute_value.name,+ },+ }+ ],+ },+ {+ "sku": sku_2,+ "weight": 2.5,+ "trackInventory": True,+ "name": variant_2_name,+ "attributes": [+ {+ "externalReference": attribute_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attribute_value.name,+ },+ }+ ],+ },+ ]++ variants_prod_2 = [+ {+ "sku": sku_3,+ "weight": 2.5,+ "trackInventory": True,+ "name": variant_3_name,+ "attributes": [+ {+ "id": size_attr_id,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attribute_value.name,+ },+ }+ ],+ }+ ]++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_1,+ "slug": f"{base_product_slug}-1",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "weight": 2,+ "variants": variants_prod_1,+ },+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_2,+ "slug": f"{base_product_slug}-2",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "variants": variants_prod_2,+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ products = Product.objects.all()+ product_1_variants = products[0].variants.all()+ product_2_variants = products[1].variants.all()++ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert data["results"][0]["product"]["variants"]+ assert data["results"][1]["product"]["variants"]+ assert len(products) == 2+ assert len(product_1_variants) == 2+ assert len(product_2_variants) == 1++ for variant in product_1_variants:+ assert variant.name in [variant_1_name, variant_2_name]+ assert variant.sku in [sku_1, sku_2]+ attribute_assignment = variant.attributes.first()+ assert variant.attributes.count() == 1+ assert attribute_assignment.attribute == size_attribute+ assert attribute_assignment.values.count() == 1++ for variant in product_2_variants:+ assert variant.name == variant_3_name+ assert variant.sku == sku_3+ attribute_assignment = variant.attributes.first()+ assert variant.attributes.count() == 1+ assert attribute_assignment.attribute == size_attribute+ assert attribute_assignment.values.count() == 1++def test_product_bulk_create_with_variants_with_duplicated_sku(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.pyindex 0bb9518023..1879b7fb1e 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py@@ -395,6 +395,66 @@ def test_product_variant_bulk_create_by_attribute_external_ref(assert expected_assigned_choice_attribute in assigned_attributes+def test_product_variant_bulk_create_by_attribute_external_ref_and_value(+ staff_api_client,+ product,+ color_attribute,+ permission_manage_products,+):+ # given+ product_variant_count = ProductVariant.objects.count()+ product.product_type.variant_attributes.add(color_attribute)++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_external_ref = color_attribute.external_reference++ value_external_ref = "value-external-ref"+ attribute_value = color_attribute.values.last()+ attribute_value.external_reference = value_external_ref+ attribute_value.save(update_fields=["external_reference"])++ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [+ {+ "externalReference": attribute_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attribute_value.name,+ },+ }+ ],+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkCreate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert (+ data["results"][0]["productVariant"]["attributes"][1]["attribute"]["slug"]+ == color_attribute.slug+ )+ assert (+ data["results"][0]["productVariant"]["attributes"][1]["values"][0]["slug"]+ == attribute_value.slug+ )++def test_product_variant_bulk_create_return_error_when_attribute_external_ref_and_id(staff_api_client,product,diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.pyindex 63090ccc2c..b0806c29bf 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py@@ -1029,7 +1029,7 @@ def test_product_variant_bulk_update_with_ref_attributes_and_reference_types_def)-def test_product_variant_bulk_update_with_ref_attributes__refs_not_in_available_choices(+def test_product_variant_bulk_update_with_ref_attributes_refs_not_in_available_choices(staff_api_client,product,product_type,@@ -1112,6 +1112,69 @@ def test_product_variant_bulk_update_with_ref_attributes__refs_not_in_available_assert result["errors"][0]["path"] == "attributes"+@patch(+ "saleor.graphql.product.bulk_mutations."+ "product_variant_bulk_update.get_webhooks_for_event"+)+def test_product_variant_bulk_update_attributes_by_external_reference(+ mocked_get_webhooks_for_event,+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+ any_webhook,+ settings,+ multiselect_attribute,+ color_attribute,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ variant = variant_with_many_stocks+ product_id = graphene.Node.to_global_id("Product", variant.product_id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ product = variant.product+ product.product_type.variant_attributes.add(color_attribute)+ attribute_external_ref = color_attribute.external_reference++ value_external_ref = "value-external-ref"+ attribute_value = color_attribute.values.last()+ attribute_value.external_reference = value_external_ref+ attribute_value.save(update_fields=["external_reference"])++ variants = [+ {+ "id": variant_id,+ "attributes": [+ {+ "externalReference": attribute_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attribute_value.name,+ },+ }+ ],+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkUpdate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ for rule in get_active_catalogue_promotion_rules():+ assert rule.variants_dirty++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)@mock.patch("saleor.graphql.product.bulk_mutations.product_variant_bulk_update.ProductVariantBulkUpdate.call_event"diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.pyindex 1c6ac5779e..8c8e1c6180 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py@@ -2035,41 +2035,51 @@ def test_create_product_variant_missing_required_attributes(assert not product.variants.filter(sku=sku).exists()-def test_create_product_variant_duplicated_attributes(+def test_create_product_variant_existing_values(staff_api_client,product_with_variant_with_two_attributes,color_attribute,- size_attribute,permission_manage_products,):+ # givenquery = CREATE_VARIANT_MUTATIONproduct = product_with_variant_with_two_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)- size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.id)+ color_value = color_attribute.values.first().namesku = str(uuid4())[:12]variables = {"input": {"product": product_id,"sku": sku,"attributes": [- {"id": color_attribute_id, "values": ["red"]},- {"id": size_attribute_id, "values": ["small"]},+ {"id": color_attribute_id, "values": [color_value]},],}}++ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)- assert content["data"]["productVariantCreate"]["errors"]- assert content["data"]["productVariantCreate"]["errors"][0] == {- "field": "attributes",- "code": ProductErrorCode.DUPLICATED_INPUT_ITEM.name,- "message": ANY,- "attributes": [color_attribute_id, size_attribute_id],++ # then+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert not content["errors"]+ data = content["productVariant"]+ assert data["sku"] == sku+ assert data["attributes"][0]["attribute"]["slug"] == color_attribute.slug+ assert data["attributes"][0]["values"][0]["slug"] == color_value.lower()++ assigned_attributes = data["assignedAttributes"]+ expected_assigned_choice_attribute = {+ "attribute": {"slug": color_attribute.slug},+ "choice": {+ "name": color_value,+ "slug": color_value.lower(),+ },}- assert not product.variants.filter(sku=sku).exists()+ assert expected_assigned_choice_attribute in assigned_attributesdef test_create_variant_invalid_variant_attributes(@@ -2778,3 +2788,174 @@ def test_variant_create_product_with_default_track_inventory(data["productVariant"]["trackInventory"]== site_settings.track_inventory_by_default)+++def test_create_product_variant_with_attribute_by_external_reference_value_created(+ staff_api_client,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute = product_type.variant_attributes.first()+ attr_external_ref = "test-attribute-ext-ref"+ attribute.external_reference = attr_external_ref+ attribute.save(update_fields=["external_reference"])++ values_count = attribute.values.count()+ value_external_ref = "test-value-ext-ref"+ value = "test-value"++ name = "Test variant"+ sku = "test-sku"++ variables = {+ "input": {+ "product": product_id,+ "name": name,+ "sku": sku,+ "attributes": [+ {+ "externalReference": attr_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": value,+ },+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert not content["errors"]+ data = content["productVariant"]+ assert data["name"] == name+ assert data["sku"] == sku+ assert len(data["attributes"]) == 1+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug+ assert data["attributes"][0]["values"][0]["slug"] == value+ attribute.refresh_from_db()+ assert attribute.values.count() == values_count + 1+++def test_create_product_variant_with_attributes_by_external_reference_existing_vale(+ staff_api_client,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute = product_type.variant_attributes.first()+ attr_external_ref = "test-attribute-ext-ref"+ attribute.external_reference = attr_external_ref+ attribute.save(update_fields=["external_reference"])++ value = attribute.values.first()+ value_external_ref = "test-value-ext-ref"+ value.external_reference = value_external_ref+ value.save(update_fields=["external_reference"])+ values_count = attribute.values.count()++ name = "Test variant"+ sku = "test-sku"++ variables = {+ "input": {+ "product": product_id,+ "name": name,+ "sku": sku,+ "attributes": [+ {+ "externalReference": attr_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": value.name,+ },+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert not content["errors"]+ data = content["productVariant"]+ assert data["name"] == name+ assert data["sku"] == sku+ assert len(data["attributes"]) == 1+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug+ assert data["attributes"][0]["values"][0]["name"] == value.name++ attribute.refresh_from_db()+ assert attribute.values.count() == values_count+++def test_create_product_variant_with_attributes_by_external_reference_invalid_value(+ staff_api_client,+ product,+ product_type,+ permission_manage_products,+):+ # given attributes input with external ref but value that does not match+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute = product_type.variant_attributes.first()+ attr_external_ref = "test-attribute-ext-ref"+ attribute.external_reference = attr_external_ref+ attribute.save(update_fields=["external_reference"])++ value = attribute.values.first()+ value_external_ref = "test-value-ext-ref"+ value.external_reference = value_external_ref+ value.save(update_fields=["external_reference"])+ attr_value = "test-value"++ name = "Test variant"+ sku = "test-sku"++ variables = {+ "input": {+ "product": product_id,+ "name": name,+ "sku": sku,+ "attributes": [+ {+ "externalReference": attr_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attr_value,+ },+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert len(content["errors"]) == 1+ assert not content["productVariant"]+ assert content["errors"][0]["field"] == "attributes"+ assert content["errors"][0]["code"] == "INVALID"diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.pyindex d185f30218..7118ad3452 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py@@ -1927,7 +1927,7 @@ def test_update_product_variant_clear_attributes(variant_attr.refresh_from_db()-def test_update_product_variant_with_duplicated_attribute(+def test_update_product_variant_with_existing_values(staff_api_client,product_with_variant_with_two_attributes,color_attribute,@@ -1954,6 +1954,9 @@ def test_update_product_variant_with_duplicated_attribute(assert variant2.attributes.first().values.first().slug == "blue"assert variant2.attributes.last().values.first().slug == "big"+ color_attr_values_count = color_attribute.values.count()+ size_attr_values_count = size_attribute.values.count()+variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)@@ -1975,10 +1978,14 @@ def test_update_product_variant_with_duplicated_attribute(data = content["data"]["productVariantUpdate"]errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "attributes"- assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name- assert set(errors[0]["attributes"]) == {color_attribute_id, size_attribute_id}+ assert not errors+ variant_data = data["productVariant"]+ assert variant_data+ assert len(variant_data["attributes"]) == 2+ color_attribute.refresh_from_db()+ size_attribute.refresh_from_db()+ assert color_attribute.values.count() == color_attr_values_count+ assert size_attribute.values.count() == size_attr_values_countdef test_update_product_variant_with_current_file_attribute(@@ -2038,7 +2045,7 @@ def test_update_product_variant_with_current_file_attribute(assert expected_assigned_attribute in assigned_attributes-def test_update_product_variant_with_duplicated_file_attribute(+def test_update_product_variant_with_existing_file_attribute(staff_api_client,product_with_variant_with_file_attribute,file_attribute,@@ -2046,26 +2053,14 @@ def test_update_product_variant_with_duplicated_file_attribute():product = product_with_variant_with_file_attributevariant = product.variants.first()- variant2 = product.variants.first()-- variant2.pk = None- variant2.sku = str(uuid4())[:12]- variant2.save()file_attr_value = file_attribute.values.last()associate_attribute_values_to_instance(- variant2, {file_attribute.id: [file_attr_value]}+ variant, {file_attribute.id: [file_attr_value]})sku = str(uuid4())[:12]- assert not variant.sku == sku-- assert set(variant.attributes.first().values.values_list("slug", flat=True)) == {- "test_filetxt"- }- assert set(variant2.attributes.first().values.values_list("slug", flat=True)) == {- "test_filejpeg"- }+ values_count = file_attribute.values.count()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)file_attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)file_url = f"https://example.com{settings.MEDIA_URL}{file_attr_value.file_url}"@@ -2085,11 +2080,12 @@ def test_update_product_variant_with_duplicated_file_attribute(content = get_graphql_content(response)data = content["data"]["productVariantUpdate"]- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "attributes"- assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name- assert set(errors[0]["attributes"]) == {file_attribute_id}+ assert not data["errors"]+ variant_data = data["productVariant"]+ assert variant_data+ assert len(variant_data["attributes"]) == 1+ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_countdef test_update_product_variant_with_file_attribute_new_value_is_not_created(@@ -2970,6 +2966,148 @@ def test_update_product_variant_with_reference_attributes_ref_not_in_available_c}+def test_update_product_variant_attribute_by_external_reference_value_created(+ staff_api_client,+ variant,+ product_type,+ permission_manage_products,+):+ # given+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ attribute = product_type.variant_attributes.first()+ attr_external_ref = "test-attribute-ext-ref"+ attribute.external_reference = attr_external_ref+ attribute.save(update_fields=["external_reference"])++ values_count = attribute.values.count()+ value_external_ref = "test-value-ext-ref"+ value = "test-value"++ variables = {+ "id": variant_id,+ "attributes": [+ {+ "externalReference": attr_external_ref,+ "dropdown": {"externalReference": value_external_ref, "value": value},+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ assert not content["errors"]+ data = content["productVariant"]+ assert len(data["attributes"]) == 1+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug+ assert data["attributes"][0]["values"][0]["slug"] == value+ attribute.refresh_from_db()+ assert attribute.values.count() == values_count + 1+++def test_update_product_variant_attribute_by_external_reference_existing_value(+ staff_api_client,+ variant,+ product_type,+ permission_manage_products,+):+ # given+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ attribute = product_type.variant_attributes.first()+ attr_external_ref = "test-attribute-ext-ref"+ attribute.external_reference = attr_external_ref+ attribute.save(update_fields=["external_reference"])++ value_external_ref = "test-value-ext-ref"+ value = attribute.values.create(+ name="Big", slug="big", external_reference=value_external_ref+ )+ values_count = attribute.values.count()++ variables = {+ "id": variant_id,+ "attributes": [+ {+ "externalReference": attr_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": value.name,+ },+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ assert not content["errors"]+ data = content["productVariant"]+ assert len(data["attributes"]) == 1+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug+ assert data["attributes"][0]["values"][0]["name"] == value.name+ attribute.refresh_from_db()+ assert attribute.values.count() == values_count+++def test_update_product_variant_attribute_by_external_reference_invalid_value(+ staff_api_client,+ variant,+ product_type,+ permission_manage_products,+):+ # given attributes input with external ref but value that does not match+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ attribute = product_type.variant_attributes.first()+ attr_external_ref = "test-attribute-ext-ref"+ attribute.external_reference = attr_external_ref+ attribute.save(update_fields=["external_reference"])++ value = attribute.values.first()+ value_external_ref = "test-value-ext-ref"+ value.external_reference = value_external_ref+ value.save(update_fields=["external_reference"])+ attr_value = "test-value"++ variables = {+ "id": variant_id,+ "attributes": [+ {+ "externalReference": attr_external_ref,+ "dropdown": {+ "externalReference": value_external_ref,+ "value": attr_value,+ },+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ assert len(content["errors"]) == 1+ assert not content["productVariant"]+ assert content["errors"][0]["field"] == "attributes"+ assert content["errors"][0]["code"] == "INVALID"++def test_update_product_variant_with_price_does_not_raise_price_validation_error(staff_api_client, variant, size_attribute, permission_manage_products):