Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix failing mutations for swatch attributes (#11744)
Iga Karbowiak5c89b4dc5746
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex d70d4aec28..34e9fd44a8 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -417,6 +417,10 @@ class AttributeValueInput(graphene.InputObjectType):required=False,description="Attribute value ID." + ADDED_IN_39,)+ swatch = AttributeValueSelectableTypeInput(+ required=False,+ description="Attribute value ID." + ADDED_IN_39,+ )multiselect = NonNullList(AttributeValueSelectableTypeInput,required=False,diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 85562380b3..844e2c86cb 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -43,6 +43,7 @@ class AttrValuesInput:global_id: strvalues: Optional[List[str]] = Nonedropdown: Optional[AttrValuesForSelectableFieldInput] = None+ swatch: Optional[AttrValuesForSelectableFieldInput] = Nonemultiselect: Optional[List[AttrValuesForSelectableFieldInput]] = Nonenumeric: Optional[str] = Nonereferences: Union[List[str], List[page_models.Page], None] = None@@ -322,6 +323,7 @@ class AttributeAssignmentMixin: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.SWATCH: cls._pre_save_swatch_value,AttributeInputType.FILE: cls._pre_save_file_value,AttributeInputType.NUMERIC: cls._pre_save_numeric_values,AttributeInputType.MULTISELECT: cls._pre_save_multiselect_values,@@ -381,6 +383,29 @@ class AttributeAssignmentMixin:return tuple()+ @classmethod+ def _pre_save_swatch_value(+ cls,+ _,+ attribute: attribute_models.Attribute,+ attr_values: AttrValuesInput,+ ):+ if not attr_values.swatch:+ return tuple()++ if id := attr_values.swatch.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,)++ if attr_value := attr_values.swatch.value:+ model = prepare_attribute_values(attribute, [attr_value])+ return model++ return tuple()+@classmethoddef _pre_save_multiselect_values(cls,@@ -739,6 +764,7 @@ def validate_attributes_input(AttributeInputType.DATE: validate_date_time_input,AttributeInputType.DATE_TIME: validate_date_time_input,AttributeInputType.DROPDOWN: validate_dropdown_input,+ AttributeInputType.SWATCH: validate_swatch_input,AttributeInputType.FILE: validate_file_attributes_input,AttributeInputType.NUMERIC: validate_numeric_input,AttributeInputType.MULTISELECT: validate_multiselect_input,@@ -931,6 +957,26 @@ def validate_dropdown_input()+def validate_swatch_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ attribute_errors: T_ERROR_DICT,+):+ attribute_id = attr_values.global_id+ if not attr_values.swatch:+ if attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attribute_id+ )+ else:+ validate_single_selectable_field(+ attribute,+ attr_values.swatch,+ attribute_errors,+ attribute_id,+ )++def validate_multiselect_input(attribute: "Attribute",attr_values: "AttrValuesInput",diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex beaeed7f53..2ea67da239 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -2126,6 +2126,62 @@ def test_create_product_with_swatch_attribute_new_attribute_value(product_type.product_attributes.set([swatch_attribute])attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.id)+ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": attr_id, "swatch": {"value": new_value}}],+ }+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]+ assert data["errors"] == []+ assert data["product"]["name"] == product_name+ assert data["product"]["slug"] == product_slug+ assert data["product"]["productType"]["name"] == product_type.name+ assert data["product"]["category"]["name"] == category.name+ assert len(data["product"]["attributes"]) == 1+ assert (+ data["product"]["attributes"][0]["attribute"]["slug"] == swatch_attribute.slug+ )+ values = data["product"]["attributes"][0]["values"]+ assert len(values) == 1+ assert values[0]["name"] == new_value+ assert values[0]["slug"] == slugify(new_value)++ swatch_attribute.refresh_from_db()+ assert swatch_attribute.values.count() == values_count + 1+++def test_create_product_with_swatch_attribute_new_value_using_values_field(+ staff_api_client,+ product_type,+ category,+ swatch_attribute,+ permission_manage_products,+):+ query = CREATE_PRODUCT_MUTATION++ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)+ product_name = "test name"+ product_slug = "product-test-slug"++ values_count = swatch_attribute.values.count()++ # Add second attribute+ product_type.product_attributes.set([swatch_attribute])+ attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.id)+ values_count = swatch_attribute.values.count()+ new_value = "Yellow"+# test creating root productvariables = {"input": {@@ -2153,6 +2209,7 @@ def test_create_product_with_swatch_attribute_new_attribute_value()values = data["product"]["attributes"][0]["values"]assert len(values) == 1+ assert len(values) == 1assert values[0]["name"] == new_valueassert values[0]["slug"] == slugify(new_value)@@ -2176,6 +2233,62 @@ def test_create_product_with_swatch_attribute_existing_value(values_count = swatch_attribute.values.count()+ # Add second attribute+ product_type.product_attributes.set([swatch_attribute])+ attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.id)+ existing_value = swatch_attribute.values.first()+ existing_value_id = graphene.Node.to_global_id("AttributeValue", existing_value.id)++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": attr_id, "swatch": {"id": existing_value_id}}],+ }+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]+ assert data["errors"] == []+ assert data["product"]["name"] == product_name+ assert data["product"]["slug"] == product_slug+ assert data["product"]["productType"]["name"] == product_type.name+ assert data["product"]["category"]["name"] == category.name+ assert len(data["product"]["attributes"]) == 1+ assert (+ data["product"]["attributes"][0]["attribute"]["slug"] == swatch_attribute.slug+ )+ values = data["product"]["attributes"][0]["values"]+ assert len(values) == 1+ assert values[0]["name"] == existing_value.name+ assert values[0]["slug"] == existing_value.slug++ swatch_attribute.refresh_from_db()+ assert swatch_attribute.values.count() == values_count+++def test_create_product_with_swatch_attribute_existing_value_using_values_field(+ staff_api_client,+ product_type,+ category,+ swatch_attribute,+ permission_manage_products,+):+ query = CREATE_PRODUCT_MUTATION++ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)+ product_name = "test name"+ product_slug = "product-test-slug"++ values_count = swatch_attribute.values.count()+# Add second attributeproduct_type.product_attributes.set([swatch_attribute])attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.id)diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.pyindex d8f8314f16..98f84eac8e 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py@@ -897,6 +897,193 @@ def test_update_variant_with_boolean_attribute(product_variant_updated.assert_called_once_with(product.variants.last())+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_update_variant_with_swatch_attribute_new_value_created(+ product_variant_updated,+ permission_manage_products,+ product,+ product_type,+ staff_api_client,+ warehouse,+ swatch_attribute,+):+ # given+ product_type.variant_attributes.add(swatch_attribute)+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "123"+ swatch_attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.pk)++ value = "NEW"+ values_count = swatch_attribute.values.count()+ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": [+ {+ "id": swatch_attr_id,+ "swatch": {"value": value},+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ variant.refresh_from_db()+ data = content["productVariant"]++ assert not content["errors"]+ assert data["sku"] == sku+ assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug+ assert data["attributes"][-1]["values"][0]["name"] == value+ assert swatch_attribute.values.count() == values_count + 1+ product_variant_updated.assert_called_once_with(product.variants.last())+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_update_variant_with_swatch_attribute_existing_value(+ product_variant_updated,+ permission_manage_products,+ product,+ product_type,+ staff_api_client,+ warehouse,+ swatch_attribute,+):+ # given+ product_type.variant_attributes.add(swatch_attribute)+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "123"+ swatch_attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.pk)++ value = swatch_attribute.values.first()+ value_id = graphene.Node.to_global_id("AttributeValue", value.id)+ values_count = swatch_attribute.values.count()+ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": [+ {+ "id": swatch_attr_id,+ "swatch": {"id": value_id},+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ variant.refresh_from_db()+ data = content["productVariant"]++ assert not content["errors"]+ assert data["sku"] == sku+ assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug+ assert data["attributes"][-1]["values"][0]["name"] == value.name+ assert swatch_attribute.values.count() == values_count+ product_variant_updated.assert_called_once_with(product.variants.last())+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_update_variant_with_swatch_attribute_use_values(+ product_variant_updated,+ permission_manage_products,+ product,+ product_type,+ staff_api_client,+ warehouse,+ swatch_attribute,+):+ # given+ product_type.variant_attributes.add(swatch_attribute)+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "123"+ swatch_attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.pk)++ value = "NEW"+ values_count = swatch_attribute.values.count()+ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": [+ {"id": swatch_attr_id, "values": [value]},+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ variant.refresh_from_db()+ data = content["productVariant"]++ assert not content["errors"]+ assert data["sku"] == sku+ assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug+ assert data["attributes"][-1]["values"][0]["name"] == value+ assert swatch_attribute.values.count() == values_count + 1+ product_variant_updated.assert_called_once_with(product.variants.last())+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_update_variant_with_swatch_attribute_no_values_given(+ product_variant_updated,+ permission_manage_products,+ product,+ product_type,+ staff_api_client,+ warehouse,+ swatch_attribute,+):+ # given+ product_type.variant_attributes.add(swatch_attribute)+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "123"+ swatch_attr_id = graphene.Node.to_global_id("Attribute", swatch_attribute.pk)++ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": [+ {"id": swatch_attr_id},+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ variant.refresh_from_db()+ data = content["productVariant"]++ assert not content["errors"]+ assert data["sku"] == sku+ assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug+ assert not data["attributes"][-1]["values"]++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")def test_update_variant_with_rich_text_attribute(product_variant_updated,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 341127fc70..650cda01fb 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -17738,6 +17738,13 @@ input AttributeValueInput {"""dropdown: AttributeValueSelectableTypeInput+ """+ Attribute value ID.++ Added in Saleor 3.9.+ """+ swatch: AttributeValueSelectableTypeInput+"""List of attribute value IDs.