Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Refactor attribute assignement (#17954)

Iga Karbowiakf7e62982e621
diff --git a/saleor/graphql/attribute/tests/benchmark/test_attribute.py b/saleor/graphql/attribute/tests/benchmark/test_attribute.py
index 42fdcc664a..18d7019595 100644
--- a/saleor/graphql/attribute/tests/benchmark/test_attribute.py
+++ b/saleor/graphql/attribute/tests/benchmark/test_attribute.py
@@ -2,7 +2,7 @@ import graphene
import pytest
from .....attribute.models import AttributeTranslation, AttributeValueTranslation
-from ....attribute.utils import associate_attribute_values_to_instance
+from .....attribute.utils import associate_attribute_values_to_instance
from ....tests.utils import get_graphql_content
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index ada2934111..6256208680 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -1,24 +1,24 @@
+from collections import defaultdict
+
import graphene
import pytest
from django.conf import settings
from django.core.exceptions import ValidationError
from ....attribute import AttributeInputType
-from ....attribute.models import AttributeValue
-from ....page.error_codes import PageErrorCode
from ....product.error_codes import ProductErrorCode
from ..enums import AttributeValueBulkActionEnum
-from ..utils import (
- AttributeAssignmentMixin,
- AttrValuesForSelectableFieldInput,
- AttrValuesInput,
- prepare_attribute_values,
- validate_attributes_input,
+from ..utils.attribute_assignment import AttributeAssignmentMixin
+from ..utils.shared import AttrValuesForSelectableFieldInput, AttrValuesInput
+from ..utils.type_handlers import (
+ FileAttributeHandler,
+ MultiSelectableAttributeHandler,
+ SelectableAttributeHandler,
)
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_product(
+def test_clean_input_for_product(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -28,43 +28,31 @@ def test_validate_attributes_input_for_product(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["b"],
+ },
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_product_no_values_given(
+def test_clean_attribute_input_for_product_no_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -74,40 +62,29 @@ def test_validate_attributes_input_for_product_no_values_given(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
@@ -116,7 +93,7 @@ def test_validate_attributes_input_for_product_no_values_given(
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_product_too_many_values_given(
+def test_clean_attribute_input_for_product_too_many_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -128,48 +105,39 @@ def test_validate_attributes_input_for_product_too_many_values_given(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["abc", "efg"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["a", "b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["abc", "efg"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["a", "b", "c"],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.INVALID.value
- assert error.params["attributes"] == [
+ assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", color_attribute.pk)
- ]
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_product_empty_values_given(
+def test_clean_attribute_input_for_product_empty_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -181,40 +149,31 @@ def test_validate_attributes_input_for_product_empty_values_given(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a", None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[" "],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a", None],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": [" "],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
@@ -222,50 +181,45 @@ def test_validate_attributes_input_for_product_empty_values_given(
}
-def test_validate_attributes_input_for_product_lack_of_required_attribute(
+def test_clean_attribute_input_for_product_lack_of_required_attribute(
weight_attribute, color_attribute, product_type
):
# given
- product_attributes = product_type.product_attributes.all()
- attr = product_attributes.first()
- attr.value_required = True
- attr.save(update_fields=["value_required"])
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_attributes,
- is_page_attributes=False,
- creation=True,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=True,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
- graphene.Node.to_global_id("Attribute", attr.pk)
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
}
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_product_creation_multiple_errors(
+def test_clean_attribute_input_for_product_creation_multiple_errors(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -277,51 +231,46 @@ def test_validate_attributes_input_for_product_creation_multiple_errors(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["a", "b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": [None],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["a", "b"],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 2
- assert {error.code for error in errors} == {
+ assert len(exc_info.value.error_list) == 2
+ assert {error.code for error in exc_info.value.error_list} == {
ProductErrorCode.INVALID.value,
ProductErrorCode.REQUIRED.value,
}
- assert {attr for error in errors for attr in error.params["attributes"]} == {
+ assert {
+ attr
+ for error in exc_info.value.error_list
+ for attr in error.params["attributes"]
+ } == {
graphene.Node.to_global_id("Attribute", attr.pk)
for attr in [weight_attribute, color_attribute]
}
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_page(
+def test_clean_attribute_input_for_page(
creation, weight_attribute, color_attribute, page_type
):
# given
@@ -331,43 +280,31 @@ def test_validate_attributes_input_for_page(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ page_type.page_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["b"],
+ },
]
# when
- errors = validate_attributes_input(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
page_type.page_attributes.all(),
is_page_attributes=True,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_page_no_values_given(
+def test_clean_attribute_input_for_page_no_values_given(
creation, weight_attribute, color_attribute, page_type
):
# given
@@ -377,41 +314,30 @@ def test_validate_attributes_input_for_page_no_values_given(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ page_type.page_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- page_type.page_attributes.all(),
- is_page_attributes=True,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ page_type.page_attributes.all(),
+ is_page_attributes=True,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
- assert error.code == PageErrorCode.REQUIRED.value
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
for attr in [weight_attribute, color_attribute]
@@ -419,7 +345,7 @@ def test_validate_attributes_input_for_page_no_values_given(
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_page_too_many_values_given(
+def test_clean_attribute_input_for_page_too_many_values_given(
creation, weight_attribute, color_attribute, page_type
):
# given
@@ -431,48 +357,39 @@ def test_validate_attributes_input_for_page_too_many_values_given(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ page_type.page_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["abc", "efg"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["a", "b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["abc", "efg"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["a", "b"],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- page_type.page_attributes.all(),
- is_page_attributes=True,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ page_type.page_attributes.all(),
+ is_page_attributes=True,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
- assert error.code == PageErrorCode.INVALID.value
- assert error.params["attributes"] == [
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", color_attribute.pk)
- ]
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_for_page_empty_values_given(
+def test_clean_attribute_input_for_page_empty_values_given(
creation, weight_attribute, color_attribute, page_type
):
# given
@@ -484,48 +401,39 @@ def test_validate_attributes_input_for_page_empty_values_given(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ page_type.page_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a", None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[" "],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a", None],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": [" "],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- page_type.page_attributes.all(),
- is_page_attributes=True,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ page_type.page_attributes.all(),
+ is_page_attributes=True,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
- assert error.code == PageErrorCode.REQUIRED.value
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
for attr in [weight_attribute, color_attribute]
}
-def test_validate_attributes_input_for_page_lack_of_required_attribute(
+def test_clean_attribute_input_for_page_lack_of_required_attribute(
weight_attribute, color_attribute, page_type
):
# given
@@ -537,34 +445,31 @@ def test_validate_attributes_input_for_page_lack_of_required_attribute(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ page_type.page_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
]
# when
- errors = validate_attributes_input(
- input_data, page_attributes, is_page_attributes=True, creation=True
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data, page_attributes, is_page_attributes=True, creation=True
+ )
# then
- assert len(errors) == 1
- error = errors[0]
- assert error.code == PageErrorCode.REQUIRED.value
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
}
-def test_validate_attributes_input_for_page_multiple_errors(
+def test_clean_attribute_input_for_page_multiple_errors(
weight_attribute, color_attribute, page_type
):
# given
@@ -576,51 +481,45 @@ def test_validate_attributes_input_for_page_multiple_errors(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ page_type.page_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["a", "b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["a", "b"],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- page_type.page_attributes.all(),
- is_page_attributes=True,
- creation=True,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ page_type.page_attributes.all(),
+ is_page_attributes=True,
+ creation=True,
+ )
# then
- assert len(errors) == 2
- assert {error.code for error in errors} == {
- PageErrorCode.INVALID.value,
- PageErrorCode.REQUIRED.value,
+ assert len(exc_info.value.error_list) == 2
+ assert {error.code for error in exc_info.value.error_list} == {
+ ProductErrorCode.INVALID.value,
+ ProductErrorCode.REQUIRED.value,
}
- assert {attr for error in errors for attr in error.params["attributes"]} == {
+ assert {
+ attr
+ for error in exc_info.value.error_list
+ for attr in error.params["attributes"]
+ } == {
graphene.Node.to_global_id("Attribute", attr.pk)
for attr in [weight_attribute, color_attribute]
}
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input(
+def test_clean_variant_attribute_input(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -630,42 +529,31 @@ def test_validate_attributes_input(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["b"],
+ },
]
- attributes = product_type.variant_attributes.all()
-
- # when
- errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, creation=creation
+ # when & then
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.variant_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_no_values_given(
+def test_clean_variant_attribute_input_no_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -675,39 +563,29 @@ def test_validate_attributes_input_no_values_given(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ },
]
- attributes = product_type.variant_attributes.all()
-
# when
- errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, creation=creation
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.variant_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
@@ -716,51 +594,43 @@ def test_validate_attributes_input_no_values_given(
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_duplicated_values_given(
+def test_clean_variant_attribute_duplicated_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
- color_attribute.value_required = True
color_attribute.input_type = AttributeInputType.MULTISELECT
- color_attribute.save(update_fields=["value_required"])
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required", "input_type"])
weight_attribute.value_required = True
weight_attribute.input_type = AttributeInputType.MULTISELECT
- weight_attribute.save(update_fields=["value_required"])
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["test", "new", "test"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["test", "test"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["test", "new", "test"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["test", "test"],
+ },
]
- attributes = product_type.variant_attributes.all()
-
# when
- errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, creation=creation
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.variant_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
@@ -769,114 +639,83 @@ def test_validate_attributes_duplicated_values_given(
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_not_required_variant_selection_attributes_input_no_values_given(
+def test_clean_variant_attribute_input_empty_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
- color_attribute.value_required = False
color_attribute.input_type = AttributeInputType.MULTISELECT
+ color_attribute.value_required = False
color_attribute.save(update_fields=["value_required", "input_type"])
weight_attribute.value_required = False
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
- # To be verified.
- product_type.variant_attributes.add(weight_attribute)
- product_type.variant_attributes.add(color_attribute)
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ },
]
- attributes = product_type.variant_attributes.all()
- # when
- errors = validate_attributes_input(
+ # when & then
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
- attributes,
+ product_type.variant_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_too_many_values_given(
+def test_clean_variant_attribute_too_many_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
color_attribute.value_required = True
- color_attribute.save(update_fields=["value_required"])
+ color_attribute.save(update_fields=["value_required", "input_type"])
weight_attribute.value_required = True
- weight_attribute.save(update_fields=["value_required"])
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["abc", "efg"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["a", "b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["abc", "efg"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["a", "b"],
+ },
]
- attributes = product_type.variant_attributes.all()
-
- # when
- errors = validate_attributes_input(
- input_data,
- attributes,
- is_page_attributes=False,
- creation=creation,
- )
+ # when & then
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.variant_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
- # then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.INVALID.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
- for attr in [weight_attribute, color_attribute]
+ for attr in [color_attribute, weight_attribute]
}
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_input_empty_values_given(
+def test_clean_variant_attribute_empty_values_given(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -886,146 +725,126 @@ def test_validate_attributes_input_empty_values_given(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=[" "],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": [None],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": [" "],
+ },
]
- attributes = product_type.variant_attributes.all()
-
- # when
- errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, creation=creation
- )
+ # when & then
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.variant_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
- # then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", attr.pk)
- for attr in [weight_attribute, color_attribute]
+ for attr in [color_attribute, weight_attribute]
}
-def test_validate_attributes_input_multiple_errors(
- weight_attribute, color_attribute, product_type
[email protected]("creation", [True, False])
+def test_clean_variant_attribute_input_multiple_errors(
+ 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.value_required = True
+ weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.variant_attributes.add(color_attribute, weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=[None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- values=["a", "b"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": [None],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "values": ["a", "b"],
+ },
]
- attributes = product_type.variant_attributes.all()
-
# when
- errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, creation=True
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.variant_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 2
- assert {error.code for error in errors} == {
+ assert len(exc_info.value.error_list) == 2
+ assert {error.code for error in exc_info.value.error_list} == {
ProductErrorCode.INVALID.value,
ProductErrorCode.REQUIRED.value,
}
- assert {attr for error in errors for attr in error.params["attributes"]} == {
+ assert {
+ attr
+ for error in exc_info.value.error_list
+ for attr in error.params["attributes"]
+ } == {
graphene.Node.to_global_id("Attribute", attr.pk)
for attr in [weight_attribute, color_attribute]
}
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_with_file_input_type_for_product(
- creation, weight_attribute, file_attribute, product_type
+def test_clean_attributes_with_file_input_type_for_product(
+ creation, weight_attribute, file_attribute, product_type, site_settings
):
# given
file_attribute.value_required = True
file_attribute.save(update_fields=["value_required"])
-
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(weight_attribute, file_attribute)
+
+ domain = site_settings.site.domain
+ file_url = f"http://{domain}{settings.MEDIA_URL}test_file.jpeg"
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- file_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),
- values=[],
- file_url="test_file.jpeg",
- content_type="image/jpeg",
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),
+ "file": file_url,
+ "content_type": "image/jpeg",
+ },
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_with_file_input_type_for_product_no_file_given(
+def test_clean_attributes_with_file_input_type_for_product_no_file_given(
creation, weight_attribute, file_attribute, product_type
):
# given
@@ -1035,48 +854,38 @@ def test_validate_attributes_with_file_input_type_for_product_no_file_given(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(weight_attribute, file_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- file_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),
- values=[],
- file_url="",
- content_type="image/jpeg",
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
- graphene.Node.to_global_id("Attribute", file_attribute.pk)
+ graphene.Node.to_global_id("Attribute", attr.pk) for attr in [file_attribute]
}
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_given(
+def test_clean_not_required_attrs_with_file_input_type_for_product_no_file_given(
creation, weight_attribute, file_attribute, product_type
):
# given
@@ -1086,43 +895,30 @@ def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_gi
weight_attribute.value_required = False
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(weight_attribute, file_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- file_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),
- values=[],
- file_url="",
- content_type="image/jpeg",
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),
+ },
]
# when
- errors = validate_attributes_input(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_attributes_with_file_input_type_for_product_empty_file_value(
+def test_clean_attributes_with_file_input_type_for_product_empty_file_value(
creation, weight_attribute, file_attribute, product_type
):
# given
@@ -1132,40 +928,31 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(weight_attribute, file_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- values=["a"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
- (
- file_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),
- values=[],
- file_url=" ",
- content_type="image/jpeg",
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "values": ["a"],
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),
+ "values": [" "],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", file_attribute.pk)
@@ -1173,71 +960,62 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_numeric_attributes_input_for_product(
+def test_clean_numeric_attributes_input_for_product(
creation, numeric_attribute, product_type
):
# given
numeric_attribute.value_required = True
numeric_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- values=["12.34"],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ "values": ["12.34"],
+ },
]
# when
- errors = validate_attributes_input(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
- )
-
- # then
- assert not errors
+ )
@pytest.mark.parametrize("value", ["qvd", "12.se", " "])
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_numeric_attributes_input_for_product_not_numeric_value_given(
+def test_clean_numeric_attributes_input_for_product_not_numeric_value_given(
creation, value, numeric_attribute, product_type
):
# given
numeric_attribute.value_required = True
numeric_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- values=[value],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ "values": [value],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.INVALID.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
@@ -1252,30 +1030,27 @@ def test_validate_numeric_attributes_input_for_product_blank_value(
numeric_attribute.value_required = True
numeric_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- values=[None],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ "values": [None],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
@@ -1290,30 +1065,26 @@ def test_validate_numeric_attributes_input_none_as_values(
numeric_attribute.value_required = True
numeric_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- values=None,
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.REQUIRED.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
@@ -1328,30 +1099,27 @@ def test_validate_numeric_attributes_input_for_product_more_than_one_value_given
numeric_attribute.value_required = True
numeric_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- values=["12", 1, 123],
- file_url=None,
- content_type=None,
- references=[],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ "values": ["12", 1, 123],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
# then
- assert len(errors) == 1
- error = errors[0]
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
assert error.code == ProductErrorCode.INVALID.value
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
@@ -1371,37 +1139,31 @@ def test_validate_selectable_attributes_by_value(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
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"),
- ],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(value="new color"),
+ },
+ {
+ "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(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
def test_validate_selectable_attributes_by_id(
@@ -1416,40 +1178,34 @@ def test_validate_selectable_attributes_by_id(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
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"),
- ],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(id="id"),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "multiselect": [
+ AttrValuesForSelectableFieldInput(id="id1"),
+ AttrValuesForSelectableFieldInput(id="id2"),
+ ],
+ },
]
# when
- errors = validate_attributes_input(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attributes_pass_null_value(
+def test_clean_selectable_attributes_pass_null_value(
creation, weight_attribute, color_attribute, product_type
):
# given
@@ -1459,39 +1215,31 @@ def test_validate_selectable_attributes_pass_null_value(
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["input_type"])
+ product_type.product_attributes.add(color_attribute, weight_attribute)
+
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),
- ],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(value=None),
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "multiselect": [AttrValuesForSelectableFieldInput(value=None)],
+ },
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # no errors should be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attribute_by_id_and_value(
+def test_clean_selectable_attribute_by_id_and_value(
creation, color_attribute, product_type
):
# given
@@ -1499,31 +1247,38 @@ def test_validate_selectable_attribute_by_id_and_value(
color_attribute.value_required = True
color_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute)
+
input_data = [
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- dropdown=AttrValuesForSelectableFieldInput(id="id", value="new color"),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(
+ value="new color",
+ id="id",
),
- ),
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attribute_by_external_reference(
+def test_clean_selectable_attribute_by_external_reference(
creation, color_attribute, product_type
):
# given
@@ -1531,33 +1286,30 @@ def test_validate_selectable_attribute_by_external_reference(
color_attribute.value_required = True
color_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute)
+
input_data = [
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- dropdown=AttrValuesForSelectableFieldInput(
- external_reference=color_attribute.external_reference,
- value="new color",
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(
+ value="new color",
+ external_reference=color_attribute.external_reference,
),
- )
+ },
]
# when
- errors = validate_attributes_input(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attribute_by_id_and_external_reference(
+def test_clean_selectable_attribute_by_id_and_external_reference(
creation, color_attribute, product_type
):
# given
@@ -1565,33 +1317,38 @@ def test_validate_selectable_attribute_by_id_and_external_reference(
color_attribute.value_required = True
color_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute)
+
input_data = [
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- dropdown=AttrValuesForSelectableFieldInput(
- id="id", external_reference="external_reference"
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(
+ id="id",
+ external_reference="external_reference",
),
- )
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attribute_by_value_and_external_reference(
+def test_clean_selectable_attribute_by_value_and_external_reference(
creation, color_attribute, product_type
):
# given
@@ -1599,32 +1356,30 @@ def test_validate_selectable_attribute_by_value_and_external_reference(
color_attribute.value_required = True
color_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute)
+
input_data = [
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- dropdown=AttrValuesForSelectableFieldInput(
- value="new color", external_reference="external_reference"
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "dropdown": AttrValuesForSelectableFieldInput(
+ value="new color",
+ external_reference="external_reference",
),
- )
+ },
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # no errors should be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_multiselect_attribute_by_id_and_value(
+def test_clean_multiselect_attribute_by_id_and_value(
creation, weight_attribute, product_type
):
# given
@@ -1632,34 +1387,38 @@ def test_validate_multiselect_attribute_by_id_and_value(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- multiselect=[
- AttrValuesForSelectableFieldInput(id="id"),
- AttrValuesForSelectableFieldInput(value="new weight"),
- ],
- ),
- ),
+ {
+ "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,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", weight_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_multiselect_attribute_duplicated_values(
+def test_clean_multiselect_attribute_duplicated_values(
creation, weight_attribute, product_type
):
# given
@@ -1667,35 +1426,39 @@ def test_validate_multiselect_attribute_duplicated_values(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(weight_attribute)
+
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"),
- ],
- ),
- ),
+ {
+ "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,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", weight_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_multiselect_attribute_duplicated_ids(
+def test_clean_multiselect_attribute_duplicated_ids(
creation, weight_attribute, product_type
):
# given
@@ -1703,35 +1466,39 @@ def test_validate_multiselect_attribute_duplicated_ids(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(weight_attribute)
+
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"),
- ],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "multiselect": [
+ AttrValuesForSelectableFieldInput(id="newWeight"),
+ AttrValuesForSelectableFieldInput(id="newWeight"),
+ AttrValuesForSelectableFieldInput(id="newWeight2"),
+ ],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", weight_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_multiselect_attribute_duplicated_external_refs(
+def test_clean_multiselect_attribute_duplicated_external_refs(
creation, weight_attribute, product_type
):
# given
@@ -1739,35 +1506,39 @@ def test_validate_multiselect_attribute_duplicated_external_refs(
weight_attribute.value_required = True
weight_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(weight_attribute)
+
input_data = [
- (
- weight_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),
- multiselect=[
- AttrValuesForSelectableFieldInput(external_reference="newWeight"),
- AttrValuesForSelectableFieldInput(external_reference="newWeight"),
- AttrValuesForSelectableFieldInput(external_reference="newWeight2"),
- ],
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", weight_attribute.pk),
+ "multiselect": [
+ AttrValuesForSelectableFieldInput(external_reference="newWeight"),
+ AttrValuesForSelectableFieldInput(external_reference="newWeight"),
+ AttrValuesForSelectableFieldInput(external_reference="newWeight2"),
+ ],
+ },
]
# when
- errors = validate_attributes_input(
- input_data,
- product_type.product_attributes.all(),
- is_page_attributes=False,
- creation=creation,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", weight_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attribute_max_length_exceeded(
+def test_clean_selectable_attribute_max_length_exceeded(
creation, color_attribute, product_type
):
# given
@@ -1776,32 +1547,36 @@ def test_validate_selectable_attribute_max_length_exceeded(
color_attribute.save(update_fields=["value_required", "input_type"])
col_max = color_attribute.values.model.name.field.max_length
+ product_type.product_attributes.add(color_attribute)
+
input_data = [
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- dropdown=AttrValuesForSelectableFieldInput(value="n" * col_max + "n"),
- ),
- ),
+ {
+ "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,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ }
[email protected]("value", [None, "", " "])
[email protected]("value", [None, ""])
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_selectable_attribute_value_required(
+def test_clean_selectable_attribute_value_required(
creation, value, color_attribute, product_type
):
# given
@@ -1809,54 +1584,58 @@ def test_validate_selectable_attribute_value_required(
color_attribute.value_required = True
color_attribute.save(update_fields=["value_required", "input_type"])
+ product_type.product_attributes.add(color_attribute)
+
input_data = [
- (
- color_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),
- dropdown=AttrValuesForSelectableFieldInput(value=value),
- ),
- ),
+ {
+ "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,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ }
@pytest.mark.parametrize("value", [2.56, "2.56", "0", 0, -3.5, "-3.6"])
@pytest.mark.parametrize("creation", [True, False])
def test_validate_numeric_attributes(creation, value, numeric_attribute, product_type):
# given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- numeric=value,
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ "numeric": value,
+ },
]
# when
- errors = validate_attributes_input(
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("value", [True, "number", "0,56", "e-10", "20k"])
@pytest.mark.parametrize("creation", [True, False])
@@ -1864,85 +1643,91 @@ def test_validate_numeric_attributes_invalid_number(
creation, value, numeric_attribute, product_type
):
# given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ product_type.product_attributes.add(numeric_attribute)
+
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- numeric=value,
- ),
- ),
+ {
+ "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,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_numeric_attributes_pass_null_value(
+def test_clean_numeric_attributes_pass_null_value(
creation, numeric_attribute, product_type
):
# given
+ product_type.product_attributes.add(numeric_attribute)
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- numeric=None,
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ "numeric": None,
+ },
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # no errors should be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_numeric_attributes_value_required(
+def test_clean_numeric_attributes_value_required(
creation, numeric_attribute, product_type
):
# given
numeric_attribute.value_required = True
numeric_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(numeric_attribute)
input_data = [
- (
- numeric_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
- numeric=None,
- ),
- ),
+ {
+ "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,
- )
+ with pytest.raises(ValidationError) as exc_info:
+ AttributeAssignmentMixin.clean_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
+ assert len(exc_info.value.error_list) == 1
+ error = exc_info.value.error_list[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ }
@pytest.mark.parametrize("creation", [True, False])
@@ -1952,114 +1737,108 @@ def test_validate_rich_text_attributes_input_for_product_only_embed_block(
# given
rich_text_attribute.value_required = True
rich_text_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(rich_text_attribute)
input_data = [
- (
- rich_text_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id(
- "Attribute", rich_text_attribute.pk
- ),
- values=["12.34"],
- file_url=None,
- content_type=None,
- references=[],
- rich_text={
- "time": 1670422589533,
- "blocks": [
- {
- "id": "6sWdDeIffS",
- "type": "embed",
- "data": {
- "service": "youtube",
- "source": "https://www.youtube.com/watch?v=xyz",
- "embed": "https://www.youtube.com/embed/xyz",
- "width": 580,
- "height": 320,
- "caption": "How To Use",
- },
- }
- ],
- "version": "2.22.2",
- },
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", rich_text_attribute.pk),
+ "rich_text": {
+ "time": 1670422589533,
+ "blocks": [
+ {
+ "id": "6sWdDeIffS",
+ "type": "embed",
+ "data": {
+ "service": "youtube",
+ "source": "https://www.youtube.com/watch?v=xyz",
+ "embed": "https://www.youtube.com/embed/xyz",
+ "width": 580,
+ "height": 320,
+ "caption": "How To Use",
+ },
+ }
+ ],
+ "version": "2.22.2",
+ },
+ }
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
@pytest.mark.parametrize("creation", [True, False])
-def test_validate_rich_text_attributes_input_for_product_only_image_block(
+def test_clean_rich_text_attributes_input_for_product_only_image_block(
creation, rich_text_attribute, product_type
):
# given
rich_text_attribute.value_required = True
rich_text_attribute.save(update_fields=["value_required"])
+ product_type.product_attributes.add(rich_text_attribute)
input_data = [
- (
- rich_text_attribute,
- AttrValuesInput(
- global_id=graphene.Node.to_global_id(
- "Attribute", rich_text_attribute.pk
- ),
- values=["12.34"],
- file_url=None,
- content_type=None,
- references=[],
- rich_text={
- "time": 1670422589533,
- "blocks": [
- {
- "id": "6n7TFTMU8y",
- "type": "image",
- "data": {
- "file": {"url": "https://codex.so/public/codex2x.png"},
- "caption": "",
- "withBorder": False,
- "stretched": False,
- "withBackground": False,
- },
- }
- ],
- },
- ),
- ),
+ {
+ "id": graphene.Node.to_global_id("Attribute", rich_text_attribute.pk),
+ "rich_text": {
+ "time": 1670422589533,
+ "blocks": [
+ {
+ "id": "6n7TFTMU8y",
+ "type": "image",
+ "data": {
+ "file": {"url": "https://codex.so/public/codex2x.png"},
+ "caption": "",
+ "withBorder": False,
+ "stretched": False,
+ "withBackground": False,
+ },
+ }
+ ],
+ "version": "2.22.2",
+ },
+ }
]
- # when
- errors = validate_attributes_input(
+ # when & then
+ # error shouldn't be raised
+ AttributeAssignmentMixin.clean_input(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
creation=creation,
)
- # then
- assert not errors
-
-def test_clean_file_url_in_attribute_assignment_mixin(site_settings):
+def test_clean_file_url(site_settings, file_attribute):
# given
name = "Test.jpg"
domain = site_settings.site.domain
url = f"http://{domain}{settings.MEDIA_URL}{name}"
+ file_handler = FileAttributeHandler(
+ file_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),
+ values=[],
+ file_url=url,
+ content_type=None,
+ references=[],
+ ),
+ )
+ errors = defaultdict(list)
+
# when
- result = AttributeAssignmentMixin._clean_file_url(url, ProductErrorCode)
+ file_handler.clean_and_validate(errors)
# then
- assert result == name
+ assert not errors
+ assert file_handler.values_input.file_url == name
@pytest.mark.parametrize(
@@ -2071,10 +1850,26 @@ def test_clean_file_url_in_attribute_assignment_mixin(site_settings):
"/ab/cd.jpg",
],
)
-def test_clean_file_url_in_attribute_assignment_mixin_invalid_url(file_url):
+def test_clean_file_url_in_attribute_assignment_mixin_invalid_url(
+ file_url, file_attribute
+):
+ # given
+ file_handler = FileAttributeHandler(
+ file_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),
+ values=[],
+ file_url=file_url,
+ content_type=None,
+ references=[],
+ ),
+ )
+ errors = defaultdict(list)
+
# when & then
- with pytest.raises(ValidationError):
- AttributeAssignmentMixin._clean_file_url(file_url, ProductErrorCode)
+ file_handler.clean_and_validate(errors)
+
+ assert errors
def test_prepare_attribute_values(color_attribute):
@@ -2090,12 +1885,17 @@ def test_prepare_attribute_values(color_attribute):
content_type=None,
references=[],
)
+ handler = SelectableAttributeHandler(color_attribute, values)
# when
- values_to_create = prepare_attribute_values(color_attribute, values.values)[1]
- AttributeValue.objects.bulk_create(values_to_create)
+ results = handler.prepare_attribute_values(color_attribute, values.values)
# then
+ pre_save_bulk = defaultdict(lambda: defaultdict(list))
+ for action, value_data in results:
+ pre_save_bulk[action][color_attribute].append(value_data)
+ AttributeAssignmentMixin._bulk_create_pre_save_values(pre_save_bulk)
+
color_attribute.refresh_from_db()
assert color_attribute.values.count() == attr_values_count + 1
assert color_attribute.values.last().name == new_value
@@ -2123,15 +1923,24 @@ def test_prepare_attribute_values_prefer_the_slug_match(color_attribute):
content_type=None,
references=[],
)
+ handler = SelectableAttributeHandler(color_attribute, values)
# when
- result, values_to_create = prepare_attribute_values(color_attribute, values.values)
- AttributeValue.objects.bulk_create(values_to_create)
+ results = handler.prepare_attribute_values(color_attribute, values.values)
# then
+ pre_save_bulk = defaultdict(lambda: defaultdict(list))
+ for action, value_data in results:
+ pre_save_bulk[action][color_attribute].append(value_data)
+ AttributeAssignmentMixin._bulk_create_pre_save_values(pre_save_bulk)
+
color_attribute.refresh_from_db()
assert color_attribute.values.count() == attr_values_count
- assert result == [existing_value, existing_value, second_val]
+ assert [result[1] for result in results] == [
+ existing_value,
+ existing_value,
+ second_val,
+ ]
def test_prepare_attribute_values_that_gives_the_same_slug(color_attribute):
@@ -2154,23 +1963,26 @@ def test_prepare_attribute_values_that_gives_the_same_slug(color_attribute):
content_type=None,
references=[],
)
+ handler = SelectableAttributeHandler(color_attribute, values)
# when
- result, values_to_create = prepare_attribute_values(color_attribute, values.values)
- AttributeValue.objects.bulk_create(values_to_create)
+ results = handler.prepare_attribute_values(color_attribute, values.values)
# then
+ pre_save_bulk = defaultdict(lambda: defaultdict(list))
+ for action, value_data in results:
+ pre_save_bulk[action][color_attribute].append(value_data)
+ AttributeAssignmentMixin._bulk_create_pre_save_values(pre_save_bulk)
+
color_attribute.refresh_from_db()
assert color_attribute.values.count() == attr_values_count + 2
- assert len(result) == 3
- assert result[0] == existing_value
- assert result[1].name == new_value
- assert result[2].name == new_value_2
+ assert len(results) == 3
+ assert results[0][1] == existing_value
+ assert results[1][1].name == new_value
+ assert results[2][1].name == new_value_2
-def test_attribute_assignment_mixin_pre_save_multiselect_external_reference_action(
- color_attribute,
-):
+def test_pre_save_multiselect_external_reference_action(color_attribute, product):
# given
color_attribute.input_type = AttributeInputType.MULTISELECT
color_attribute.save(update_fields=["input_type"])
@@ -2186,11 +1998,10 @@ def test_attribute_assignment_mixin_pre_save_multiselect_external_reference_acti
for value in color_attribute.values.all()
],
)
+ handler = MultiSelectableAttributeHandler(color_attribute, values)
# when
- result = AttributeAssignmentMixin._pre_save_multiselect_values(
- None, color_attribute, values
- )
+ result = handler.pre_save_value(product)
# then
assert result == [
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 91c8165f80..73f4a03e3e 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -56,15 +56,13 @@ from .filters import (
search_attribute_values,
)
from .sorters import AttributeChoicesSortingInput
-from .utils import AttributeAssignmentMixin
+from .utils.shared import ENTITY_TYPE_MAPPING
def get_reference_pk(attribute, root: models.AttributeValue) -> None | int:
if attribute.input_type != AttributeInputType.REFERENCE:
return None
- reference_field = AttributeAssignmentMixin.ENTITY_TYPE_MAPPING[
- attribute.entity_type
- ].value_field
+ reference_field = ENTITY_TYPE_MAPPING[attribute.entity_type].value_field
reference_pk = getattr(root, f"{reference_field}_id", None)
if reference_pk is None:
return None
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
deleted file mode 100644
index f84e2ede74..0000000000
--- a/saleor/graphql/attribute/utils.py
+++ /dev/null
@@ -1,1655 +0,0 @@
-import datetime
-import re
-from collections import defaultdict
-from collections.abc import Iterable
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, NamedTuple
-
-import graphene
-from django.core.exceptions import ValidationError
-from django.db.models import Model, Q
-from django.db.models.expressions import Exists, OuterRef
-from django.template.defaultfilters import truncatechars
-from django.utils.text import slugify
-from graphql.error import GraphQLError
-from text_unidecode import unidecode
-
-from ...attribute import AttributeEntityType, AttributeInputType
-from ...attribute import models as attribute_models
-from ...attribute.models import AttributeValue
-from ...attribute.utils import associate_attribute_values_to_instance
-from ...core.utils import (
- generate_unique_slug,
- prepare_unique_attribute_value_slug,
- prepare_unique_slug,
-)
-from ...core.utils.editorjs import clean_editor_js
-from ...core.utils.url import get_default_storage_root_url
-from ...page import models as page_models
-from ...page.error_codes import PageErrorCode
-from ...product import models as product_models
-from ...product.error_codes import ProductErrorCode
-from ..core.utils import from_global_id_or_error, get_duplicated_values
-from ..core.validators import validate_one_of_args_is_in_mutation
-from ..product.utils import get_used_attribute_values_for_variant
-from ..utils import get_nodes
-from .enums import AttributeValueBulkActionEnum
-
-if TYPE_CHECKING:
- from django.db.models import QuerySet
-
- from ...attribute.models import Attribute
-
-
-@dataclass
-class AttrValuesForSelectableFieldInput:
- id: str | None = None
- external_reference: str | None = None
- value: str | None = None
-
-
-@dataclass
-class AttrValuesInput:
- global_id: str
- external_reference: str | None = None
- values: list[str] | None = None
- dropdown: AttrValuesForSelectableFieldInput | None = None
- swatch: AttrValuesForSelectableFieldInput | None = None
- multiselect: list[AttrValuesForSelectableFieldInput] | None = None
- numeric: str | None = None
- references: list[str] | list[page_models.Page] | None = None
- file_url: str | None = None
- content_type: str | None = None
- rich_text: dict | None = None
- plain_text: str | None = None
- boolean: bool | None = None
- date: datetime.date | None = None
- date_time: datetime.datetime | None = None
-
-
-T_INSTANCE = product_models.Product | product_models.ProductVariant | page_models.Page
-T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]
-T_ERROR_DICT = dict[tuple[str, str], list]
-
-
-class EntityTypeData(NamedTuple):
- model: type[Model]
- name_field: str
- value_field: str
-
-
-class AttributeAssignmentMixin:
- """Handles cleaning of the attribute input and creating the proper relations.
-
- 1. You should first call ``clean_input``, to transform and attempt to resolve
- the provided input into actual objects. It will then perform a few
- checks to validate the operations supplied by the user are possible and allowed.
- 2. Once everything is ready and all your data is saved inside a transaction,
- you shall call ``save`` with the cleaned input to build all the required
- relations. Once the ``save`` call is done, you are safe from continuing working
- or to commit the transaction.
-
- Note: you shall never call ``save`` outside of a transaction and never before
- the targeted instance owns a primary key. Failing to do so, the relations will
- be unable to build or might only be partially built.
- """
-
- # Defines the entity type corresponding model, the model field that should be used
- # to create the value name, and relation field responsible for reference.
- # Should be updated every time, the new `AttributeEntityType` value is added.
- ENTITY_TYPE_MAPPING = {
- AttributeEntityType.PAGE: EntityTypeData(
- page_models.Page, "title", "reference_page"
- ),
- AttributeEntityType.PRODUCT: EntityTypeData(
- product_models.Product, "name", "reference_product"
- ),
- AttributeEntityType.PRODUCT_VARIANT: EntityTypeData(
- product_models.ProductVariant, "name", "reference_variant"
- ),
- AttributeEntityType.CATEGORY: EntityTypeData(
- product_models.Category, "name", "reference_category"
- ),
- AttributeEntityType.COLLECTION: EntityTypeData(
- product_models.Collection, "name", "reference_collection"
- ),
- }
-
- @classmethod
- def _resolve_attribute_nodes(
- cls,
- qs: "QuerySet",
- error_class,
- *,
- global_ids: list[str],
- external_references: Iterable[str],
- pks: Iterable[int],
- ):
- """Retrieve attributes nodes from given global IDs or external reference."""
-
- nodes: list[attribute_models.Attribute] = list(
- qs.filter(
- Q(pk__in=pks) | Q(external_reference__in=external_references)
- ).iterator(chunk_size=1000)
- )
-
- if not nodes:
- raise ValidationError(
- (
- f"Could not resolve to a node: ids={global_ids}, "
- f"external_references={external_references}."
- ),
- code=error_class.NOT_FOUND.value,
- )
-
- nodes_pk_list = set()
- nodes_external_reference_list = set()
-
- for node in nodes:
- nodes_pk_list.add(node.pk)
- nodes_external_reference_list.add(node.external_reference)
-
- for pk, global_id in zip(pks, global_ids, strict=False):
- if pk not in nodes_pk_list:
- raise ValidationError(
- f"Could not resolve {global_id!r} to Attribute",
- code=error_class.NOT_FOUND.value,
- )
-
- for external_ref in external_references:
- if external_ref not in nodes_external_reference_list:
- raise ValidationError(
- f"Could not resolve {external_ref} to Attribute",
- code=error_class.NOT_FOUND.value,
- )
-
- return nodes
-
- @classmethod
- def _resolve_attribute_global_id(cls, error_class, global_id: str) -> int:
- """Resolve an Attribute global ID into an internal ID (int)."""
- try:
- graphene_type, internal_id = from_global_id_or_error(
- global_id, only_type="Attribute"
- )
- except GraphQLError as e:
- raise ValidationError(str(e), code=error_class.GRAPHQL_ERROR.value) from e
- if not internal_id.isnumeric():
- raise ValidationError(
- f"An invalid ID value was passed: {global_id}",
- code=error_class.INVALID.value,
- )
- return int(internal_id)
-
- @classmethod
- def _get_assigned_attribute_value_if_exists(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- lookup_field: str,
- value,
- ):
- assignment = instance.attributes.filter( # type:ignore[union-attr]
- assignment__attribute=attribute, **{f"values__{lookup_field}": value}
- ).first()
-
- return (
- None
- if assignment is None
- else assignment.values.filter(**{lookup_field: value}).first()
- )
-
- @classmethod
- def _create_value_instance(cls, attribute, attr_value, external_ref):
- return (
- (
- AttributeValueBulkActionEnum.CREATE,
- AttributeValue(
- external_reference=external_ref,
- attribute=attribute,
- name=attr_value,
- slug=prepare_unique_attribute_value_slug(
- attribute, slugify(unidecode(attr_value))
- ),
- ),
- ),
- )
-
- @classmethod
- def clean_input(
- cls,
- raw_input: dict,
- attributes_qs: "QuerySet",
- creation: bool = True,
- is_page_attributes: bool = False,
- ) -> T_INPUT_MAP:
- """Resolve and prepare the input for further checks.
-
- :param raw_input: The user's attributes input.
- :param attributes_qs:
- A queryset of attributes, the attribute values must be prefetched.
- Prefetch is needed by ``_pre_save_values`` during save.
- :param creation: Whether the input is from creation mutation.
- :param is_page_attributes: Whether the input is for page type or not.
-
- :raises ValidationError: contain the message.
- :return: The resolved data
- """
- error_class: type[PageErrorCode | ProductErrorCode] = (
- PageErrorCode if is_page_attributes else ProductErrorCode
- )
-
- # Mapping to associate the input values back to the resolved attribute nodes
- pks = {}
- external_references_values_map = {}
-
- # Temporary storage of the passed ID for error reporting
- global_ids = []
-
- for attribute_input in raw_input:
- global_id = attribute_input.pop("id", None)
- external_reference = attribute_input.pop("external_reference", None)
-
- try:
- validate_one_of_args_is_in_mutation(
- "id",
- global_id,
- "external_reference",
- external_reference,
- use_camel_case=True,
- )
- except ValidationError as e:
- raise ValidationError(
- e.message,
- code=error_class.REQUIRED.value,
- ) from e
-
- values = AttrValuesInput(
- global_id=global_id,
- external_reference=external_reference,
- values=attribute_input.pop("values", []),
- file_url=cls._clean_file_url(
- attribute_input.pop("file", None), error_class
- ),
- **attribute_input,
- )
-
- if global_id:
- internal_id = cls._resolve_attribute_global_id(error_class, global_id)
- global_ids.append(global_id)
- pks[internal_id] = values
-
- if external_reference:
- external_references_values_map[external_reference] = values
-
- attributes = cls._resolve_attribute_nodes(
- attributes_qs,
- error_class,
- global_ids=global_ids,
- external_references=external_references_values_map.keys(),
- pks=pks.keys(),
- )
-
- attr_with_invalid_references = []
- cleaned_input = []
-
- for attribute in attributes:
- key = pks.get(attribute.pk)
- if not key:
- key = external_references_values_map[attribute.external_reference]
-
- if attribute.input_type == AttributeInputType.REFERENCE:
- try:
- key = cls._validate_references(error_class, attribute, key)
- except GraphQLError:
- attr_with_invalid_references.append(attribute)
- cleaned_input.append((attribute, key))
-
- if attr_with_invalid_references:
- raise ValidationError(
- "Provided references are invalid. Some of the nodes "
- "do not exist or are different types than types defined "
- "in attribute entity type.",
- code=error_class.INVALID.value,
- )
-
- cls._validate_attributes_input(
- cleaned_input,
- attributes_qs,
- creation=creation,
- is_page_attributes=is_page_attributes,
- )
-
- return cleaned_input
-
- @staticmethod
- def _clean_file_url(file_url: str | None, error_class):
- # extract storage path from file URL
- storage_root_url = get_default_storage_root_url()
- if file_url and not file_url.startswith(storage_root_url):
- raise ValidationError(
- "The file_url must be the path to the default storage.",
- code=error_class.INVALID.value,
- )
- return (
- re.sub(storage_root_url, "", file_url) if file_url is not None else file_url
- )
-
- @classmethod
- def _validate_references(
- cls, error_class, attribute: attribute_models.Attribute, values: AttrValuesInput
- ) -> AttrValuesInput:
- references = values.references
- if not references:
- return values
-
- if not attribute.entity_type:
- # FIXME: entity type is nullable for whatever reason
- raise ValidationError(
- "Invalid reference type.", code=error_class.INVALID.value
- )
- entity_model = cls.ENTITY_TYPE_MAPPING[attribute.entity_type].model
- try:
- ref_instances = get_nodes(
- references, attribute.entity_type, model=entity_model
- )
- values.references = ref_instances
- return values
- except GraphQLError as e:
- raise ValidationError(
- "Invalid reference type.", code=error_class.INVALID.value
- ) from e
-
- @classmethod
- def _validate_attributes_input(
- cls,
- cleaned_input: T_INPUT_MAP,
- attribute_qs: "QuerySet",
- *,
- creation: bool,
- is_page_attributes: bool,
- ):
- """Check the cleaned attribute input.
-
- An Attribute queryset is supplied.
-
- - ensure all required attributes are passed
- - ensure the values are correct
-
- :raises ValidationError: when an invalid operation was found.
- """
- if errors := validate_attributes_input(
- cleaned_input,
- attribute_qs,
- is_page_attributes=is_page_attributes,
- creation=creation,
- ):
- raise ValidationError(errors)
-
- @classmethod
- def save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):
- """Save the cleaned input into the database against the given instance.
-
- Note: this should always be run inside a transaction.
-
- :param instance: the product or variant to associate the attribute against.
- :param cleaned_input: the cleaned user input (refer to clean_attributes)
- """
- pre_save_methods_mapping = {
- 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.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,
- 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 = []
- pre_save_bulk = defaultdict(
- lambda: defaultdict(list) # type: ignore[var-annotated]
- )
- attr_val_map = defaultdict(list)
-
- for attribute, attr_values in cleaned_input:
- 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)
-
- if not attribute_values:
- # to ensure that attribute will be present in variable `pre_save_bulk`,
- # so function `associate_attribute_values_to_instance` will be called
- # properly for all attributes, even in case when attribute has no values
- pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(
- attribute, []
- )
- else:
- for key, value in attribute_values:
- pre_save_bulk[key][attribute].append(value)
-
- attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)
-
- for attribute, values in attribute_and_values.items():
- if not values:
- clean_assignment.append(attribute.pk)
- else:
- attr_val_map[attribute.pk].extend(values)
-
- associate_attribute_values_to_instance(instance, attr_val_map)
-
- # drop attribute assignment model when values are unassigned from instance
- if clean_assignment:
- instance.attributes.filter( # type:ignore[union-attr]
- assignment__attribute_id__in=clean_assignment
- ).delete()
-
- @classmethod
- def _pre_save_dropdown_value(
- cls,
- _,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if not attr_values.dropdown:
- return ()
-
- attr_value = attr_values.dropdown.value
- external_ref = attr_values.dropdown.external_reference
-
- if external_ref and attr_value:
- return cls._create_value_instance(attribute, attr_value, external_ref)
-
- if external_ref:
- value = attribute_models.AttributeValue.objects.get(
- external_reference=external_ref
- )
- if not value:
- raise ValidationError(
- "Attribute value with given externalReference can't be found"
- )
- return ((AttributeValueBulkActionEnum.NONE, value),)
-
- if id := attr_values.dropdown.id:
- _, attr_value_id = from_global_id_or_error(id)
- value = attribute_models.AttributeValue.objects.get(pk=attr_value_id)
- if not value:
- raise ValidationError("Attribute value with given ID can't be found")
- return ((AttributeValueBulkActionEnum.NONE, value),)
-
- if attr_value:
- return cls._prepare_attribute_values(attribute, [attr_value])
-
- return ()
-
- @classmethod
- def _pre_save_swatch_value(
- cls,
- _,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if not attr_values.swatch:
- return ()
-
- attr_value = attr_values.swatch.value
- external_ref = attr_values.swatch.external_reference
-
- if external_ref and attr_value:
- value = cls._create_value_instance(attribute, attr_value, external_ref)
- return value
-
- if external_ref:
- value = attribute_models.AttributeValue.objects.filter(
- external_reference=external_ref
- ).first()
- if not value:
- raise ValidationError(
- "Attribute value with given externalReference can't be found"
- )
- return (
- (
- AttributeValueBulkActionEnum.NONE,
- value,
- ),
- )
-
- if id := attr_values.swatch.id:
- _, attr_value_id = from_global_id_or_error(id)
- value = attribute_models.AttributeValue.objects.filter(
- pk=attr_value_id
- ).first()
- if not value:
- raise ValidationError("Attribute value with given ID can't be found")
- return (
- (
- AttributeValueBulkActionEnum.NONE,
- value,
- ),
- )
-
- if attr_value := attr_values.swatch.value:
- return cls._prepare_attribute_values(attribute, [attr_value])
-
- return ()
-
- @classmethod
- def _pre_save_multiselect_values(
- cls,
- _,
- attribute: attribute_models.Attribute,
- attr_values_input: AttrValuesInput,
- ):
- if not attr_values_input.multiselect:
- return ()
-
- attribute_values: list[attribute_models.AttributeValue] = []
- for attr_value in attr_values_input.multiselect:
- external_ref = attr_value.external_reference
-
- if external_ref and attr_value.value:
- return cls._create_value_instance(
- attribute, attr_value.value, external_ref
- )
-
- if external_ref:
- value = attribute_models.AttributeValue.objects.get(
- external_reference=external_ref
- )
- if not value:
- raise ValidationError(
- "Attribute value with given externalReference can't be found"
- )
- attribute_values.append(value)
-
- 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][0]
- attr_value_model.save()
- if attr_value_model.id not in [a.id for a in attribute_values]:
- attribute_values.append(attr_value_model)
-
- return [
- (AttributeValueBulkActionEnum.NONE, value) for value in attribute_values
- ]
-
- @classmethod
- def _pre_save_numeric_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if attr_values.values:
- value = attr_values.values[0]
- elif attr_values.numeric:
- value = attr_values.numeric
- else:
- return ()
-
- defaults = {
- "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 ()
-
- return cls._prepare_attribute_values(attribute, attr_values.values)
-
- @classmethod
- def _pre_save_rich_text_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if not attr_values.rich_text:
- return ()
- defaults = {
- "rich_text": attr_values.rich_text,
- "name": truncatechars(
- clean_editor_js(attr_values.rich_text, to_string=True), 200
- ),
- }
- return cls._update_or_create_value(instance, attribute, defaults)
-
- @classmethod
- def _pre_save_plain_text_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if not attr_values.plain_text:
- return ()
- defaults = {
- "plain_text": attr_values.plain_text,
- "name": truncatechars(attr_values.plain_text, 200),
- }
- return cls._update_or_create_value(instance, attribute, defaults)
-
- @classmethod
- def _pre_save_boolean_values(
- cls,
- _instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if attr_values.boolean is None:
- return ()
-
- boolean = bool(attr_values.boolean)
- value = {
- "attribute": attribute,
- "slug": slugify(unidecode(f"{attribute.id}_{boolean}")),
- "defaults": {
- "name": f"{attribute.name}: {'Yes' if boolean else 'No'}",
- "boolean": boolean,
- },
- }
- return ((AttributeValueBulkActionEnum.GET_OR_CREATE, value),)
-
- @classmethod
- def _pre_save_date_time_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- is_date_attr = attribute.input_type == AttributeInputType.DATE
- tz = datetime.UTC
- if is_date_attr:
- if not attr_values.date:
- return ()
- value = str(attr_values.date)
- date_time = datetime.datetime(
- attr_values.date.year,
- attr_values.date.month,
- attr_values.date.day,
- 0,
- 0,
- tzinfo=tz,
- )
- else:
- if not attr_values.date_time:
- return ()
- value = str(attr_values.date_time)
- date_time = attr_values.date_time
- defaults = {"name": value, "date_time": date_time}
- return cls._update_or_create_value(instance, attribute, defaults)
-
- @classmethod
- def _update_or_create_value(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- value_defaults: dict,
- ):
- slug = slugify(unidecode(f"{instance.id}_{attribute.id}"))
- value = {
- "attribute": attribute,
- "slug": slug,
- "defaults": value_defaults,
- }
- return ((AttributeValueBulkActionEnum.UPDATE_OR_CREATE, value),)
-
- @classmethod
- def _pre_save_reference_values(
- cls,
- instance,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- """Lazy-retrieve or create the database objects from the supplied raw values.
-
- Slug value is generated based on instance and reference entity id.
- """
- if not attr_values.references or not attribute.entity_type:
- return ()
-
- entity_data = cls.ENTITY_TYPE_MAPPING[attribute.entity_type]
- field_name = entity_data.name_field
-
- reference_list = []
- attr_value_field = entity_data.value_field
- for ref in attr_values.references:
- name = getattr(ref, field_name)
- if attribute.entity_type == AttributeEntityType.PRODUCT_VARIANT:
- name = f"{ref.product.name}: {name}" # type: ignore[union-attr]
-
- reference_list.append(
- (
- AttributeValueBulkActionEnum.GET_OR_CREATE,
- {
- "attribute": attribute,
- "slug": slugify(
- unidecode(f"{instance.id}_{ref.id}") # type: ignore[union-attr]
- ),
- "defaults": {"name": name},
- attr_value_field: ref,
- },
- )
- )
-
- return reference_list
-
- @classmethod
- def _pre_save_file_value(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_value: AttrValuesInput,
- ):
- """Create database file attribute value object from the supplied value.
-
- For every URL new value must be created as file attribute can be removed
- separately from every instance.
- """
- file_url = attr_value.file_url
- if not file_url:
- return ()
- name = file_url.split("/")[-1]
- # don't create new value when assignment already exists
- value = cls._get_assigned_attribute_value_if_exists(
- instance, attribute, "file_url", attr_value.file_url
- )
- if value is None:
- value = AttributeValue(
- attribute=attribute,
- file_url=file_url,
- name=name,
- content_type=attr_value.content_type,
- )
- value.slug = generate_unique_slug(value, name)
- return ((AttributeValueBulkActionEnum.CREATE, value),)
- return ((None, value),)
-
- @classmethod
- def _prepare_attribute_values(cls, attribute, values):
- results, values_to_create = prepare_attribute_values(attribute, values)
- return [
- (AttributeValueBulkActionEnum.NONE, record)
- for record in results
- if record not in values_to_create
- ] + [
- (AttributeValueBulkActionEnum.CREATE, record) for record in values_to_create
- ]
-
- @classmethod
- def _bulk_create_pre_save_values(cls, pre_save_bulk):
- results: dict[Attribute, list[AttributeValue]] = defaultdict(list)
-
- for action, attribute_data in pre_save_bulk.items():
- for attribute, values in attribute_data.items():
- if action == AttributeValueBulkActionEnum.CREATE:
- values = AttributeValue.objects.bulk_create(values)
- elif action == AttributeValueBulkActionEnum.UPDATE_OR_CREATE:
- values = AttributeValue.objects.bulk_update_or_create(values)
- elif action == AttributeValueBulkActionEnum.GET_OR_CREATE:
- values = AttributeValue.objects.bulk_get_or_create(values)
- else:
- # ensuring that empty values will be added to results,
- # so assignments will be removed properly in that case
- results.setdefault(attribute, [])
-
- results[attribute].extend(values)
-
- return results
-
-
-class PageAttributeAssignmentMixin(AttributeAssignmentMixin):
- # TODO: Merge the code here with the mixin above
- # after the refactor of Page <> Attribute and
- # Product <> Attribute dedicated mixins
- # should me merged into AttributeAssignmentMixin
-
- @classmethod
- def _get_assigned_attribute_value_if_exists(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- lookup_field: str,
- value,
- ):
- assigned_values = attribute_models.AssignedPageAttributeValue.objects.filter(
- page_id=instance.pk
- )
-
- return attribute_models.AttributeValue.objects.filter(
- Exists(assigned_values.filter(value_id=OuterRef("id"))),
- attribute_id=attribute.pk,
- **{lookup_field: value},
- ).first()
-
- @classmethod
- def save(
- cls,
- instance: T_INSTANCE,
- cleaned_input: T_INPUT_MAP,
- ):
- """Save the cleaned input into the database against the given instance.
-
- Note: this should always be ran inside a transaction.
- :param instance: the product or variant to associate the attribute against.
- :param cleaned_input: the cleaned user input (refer to clean_attributes)
- """
- pre_save_methods_mapping = {
- 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.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,
- 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 = []
- pre_save_bulk = defaultdict(
- lambda: defaultdict(list) # type: ignore[var-annotated]
- )
- attr_val_map = defaultdict(list)
-
- for attribute, attr_values in cleaned_input:
- 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)
-
- if not attribute_values:
- # to ensure that attribute will be present in variable `pre_save_bulk`,
- # so function `associate_attribute_values_to_instance` will be called
- # properly for all attributes, even in case when attribute has no values
- pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(
- attribute, []
- )
- else:
- for key, value in attribute_values:
- pre_save_bulk[key][attribute].append(value)
-
- attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)
-
- for attribute, values in attribute_and_values.items():
- if not values:
- clean_assignment.append(attribute.pk)
- else:
- attr_val_map[attribute.pk].extend(values)
-
- associate_attribute_values_to_instance(instance, attr_val_map)
-
- if clean_assignment:
- values = attribute_models.AttributeValue.objects.filter(
- attribute_id__in=clean_assignment
- )
- attribute_models.AssignedPageAttributeValue.objects.filter(
- Exists(values.filter(id=OuterRef("value_id"))),
- page_id=instance.pk,
- ).delete()
-
-
-class ProductAttributeAssignmentMixin(AttributeAssignmentMixin):
- # TODO: merge the code here with the mixin above
- # when all attribute relations are cleaned up
-
- @classmethod
- def _get_assigned_attribute_value_if_exists(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- lookup_field: str,
- value,
- ):
- assigned_values = attribute_models.AssignedProductAttributeValue.objects.filter(
- product_id=instance.pk
- )
-
- return attribute_models.AttributeValue.objects.filter(
- Exists(assigned_values.filter(value_id=OuterRef("id"))),
- attribute_id=attribute.pk,
- **{lookup_field: value},
- ).first()
-
- @classmethod
- def save(
- cls,
- instance: T_INSTANCE,
- cleaned_input: T_INPUT_MAP,
- ):
- """Save the cleaned input into the database against the given instance.
-
- Note: this should always be ran inside a transaction.
-
- :param instance: the product or variant to associate the attribute against.
- :param cleaned_input: the cleaned user input (refer to clean_attributes)
- """
- pre_save_methods_mapping = {
- 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.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,
- 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 = []
- pre_save_bulk = defaultdict(
- lambda: defaultdict(list) # type: ignore[var-annotated]
- )
- attr_val_map = defaultdict(list)
- for attribute, attr_values in cleaned_input:
- 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)
-
- if not attribute_values:
- # to ensure that attribute will be present in variable `pre_save_bulk`,
- # so function `associate_attribute_values_to_instance` will be called
- # properly for all attributes, even in case when attribute has no values
- pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(
- attribute, []
- )
- else:
- for key, value in attribute_values:
- pre_save_bulk[key][attribute].append(value)
-
- attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)
-
- for attribute, values in attribute_and_values.items():
- if not values:
- clean_assignment.append(attribute.pk)
- else:
- attr_val_map[attribute.pk].extend(values)
-
- associate_attribute_values_to_instance(instance, attr_val_map)
-
- if clean_assignment:
- values = attribute_models.AttributeValue.objects.filter(
- attribute_id__in=clean_assignment
- )
- attribute_models.AssignedProductAttributeValue.objects.filter(
- Exists(values.filter(id=OuterRef("value_id"))),
- product_id=instance.pk,
- ).delete()
-
-
-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)):
- slug_to_value_map[val.slug] = val
- name_to_value_map[val.name] = val
-
- existing_slugs = get_existing_slugs(attribute, values)
-
- result = []
- values_to_create = []
- for value in values:
- # match the value firstly by slug then by name
- value_obj = slug_to_value_map.get(value) or name_to_value_map.get(value)
- if value_obj:
- result.append(value_obj)
- else:
- slug = prepare_unique_slug(slugify(unidecode(value)), existing_slugs)
- instance = attribute_models.AttributeValue(
- attribute=attribute, name=value, slug=slug
- )
- result.append(instance)
-
- values_to_create.append(instance)
-
- # the set of existing slugs must be updated to not generate accidentally
- # the same slug for two or more values
- existing_slugs.add(slug)
-
- # extend name to slug value to not create two elements with the same name
- name_to_value_map[instance.name] = instance
-
- return result, values_to_create
-
-
-def get_existing_slugs(attribute: attribute_models.Attribute, values: list[str]):
- lookup = Q()
- for value in values:
- lookup |= Q(slug__startswith=slugify(unidecode(value)))
-
- existing_slugs = set(attribute.values.filter(lookup).values_list("slug", flat=True))
- return existing_slugs
-
-
-class AttributeInputErrors:
- """Define error message and error code for given error.
-
- All used error codes must be specified in PageErrorCode and ProductErrorCode.
- """
-
- ERROR_NO_VALUE_GIVEN = (
- "Attribute expects a value but none were given.",
- "REQUIRED",
- )
- ERROR_MORE_THAN_ONE_VALUE_GIVEN = (
- "Attribute must take only one value.",
- "INVALID",
- )
- ERROR_BLANK_VALUE = (
- "Attribute values cannot be blank.",
- "REQUIRED",
- )
- ERROR_DUPLICATED_VALUES = (
- "Duplicated attribute values are provided.",
- "DUPLICATED_INPUT_ITEM",
- )
- ERROR_ID_AND_VALUE = (
- "Attribute values cannot be assigned by both id and value.",
- "INVALID",
- )
- ERROR_ID_AND_EXTERNAL_REFERENCE = (
- "Attribute values cannot be assigned by both id and external reference.",
- "INVALID",
- )
- ERROR_NO_ID_OR_EXTERNAL_REFERENCE = (
- "Attribute id or external reference has to be provided.",
- "REQUIRED",
- )
- # file errors
- ERROR_NO_FILE_GIVEN = (
- "Attribute file url cannot be blank.",
- "REQUIRED",
- )
- ERROR_BLANK_FILE_VALUE = (
- "Attribute expects a file url but none were given.",
- "REQUIRED",
- )
-
- # reference errors
- ERROR_NO_REFERENCE_GIVEN = (
- "Attribute expects an reference but none were given.",
- "REQUIRED",
- )
-
- # numeric errors
- ERROR_NUMERIC_VALUE_REQUIRED = (
- "Numeric value is required.",
- "INVALID",
- )
-
- # text errors
- ERROR_MAX_LENGTH = (
- "Attribute value length is exceeded.",
- "INVALID",
- )
-
-
-def validate_attributes_input(
- input_data: list[tuple["Attribute", "AttrValuesInput"]],
- attribute_qs: "QuerySet",
- *,
- is_page_attributes: bool,
- creation: bool,
-):
- """Validate attribute input.
-
- - ensure all required attributes are passed
- - ensure the values are correct for a products or a page
- """
-
- error_code_enum = PageErrorCode if is_page_attributes else ProductErrorCode
- attribute_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.SWATCH: validate_swatch_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,
- )
- 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
- )
- # Check if all required attributes are in input only when instance is created.
- # We should allow updating any instance attributes.
- if creation:
- errors = validate_required_attributes(
- input_data, attribute_qs, errors, error_code_enum
- )
- return errors
-
-
-def validate_file_attributes_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- value = attr_values.file_url
- if not value:
- if attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_FILE_GIVEN].append(
- attr_identifier
- )
- elif not value.strip():
- attribute_errors[AttributeInputErrors.ERROR_BLANK_FILE_VALUE].append(
- attr_identifier
- )
-
-
-def validate_reference_attributes_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- references = attr_values.references
- if not references:
- if attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_REFERENCE_GIVEN].append(
- attr_identifier
- )
-
-
-def validate_boolean_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- value = attr_values.boolean
-
- if attribute.value_required and value is None:
- attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(attr_identifier)
-
-
-def validate_rich_text_attributes_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- text = clean_editor_js(attr_values.rich_text or {}, to_string=True)
-
- if not text.strip() and attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
-
-
-def validate_plain_text_attributes_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
-
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- if (
- not attr_values.plain_text or not attr_values.plain_text.strip()
- ) and attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
-
-
-def validate_standard_attributes_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- """To be deprecated together with `AttributeValueInput.values` field."""
- attr_identifier = attr_values.global_id or attr_values.external_reference
-
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- if not attr_values.values:
- if attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
- elif (
- attribute.input_type != AttributeInputType.MULTISELECT
- and len(attr_values.values) != 1
- ):
- attribute_errors[AttributeInputErrors.ERROR_MORE_THAN_ONE_VALUE_GIVEN].append(
- attr_identifier
- )
-
- if attr_values.values is not None:
- validate_values(
- attr_identifier,
- attribute,
- attr_values.values,
- attribute_errors,
- )
-
-
-def validate_single_selectable_field(
- attribute: "Attribute",
- attr_value: AttrValuesForSelectableFieldInput,
- attribute_errors: T_ERROR_DICT,
- attr_identifier: str,
-):
- id = attr_value.id
- value = attr_value.value
- external_reference = attr_value.external_reference
-
- if id and external_reference:
- attribute_errors[AttributeInputErrors.ERROR_ID_AND_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- if id and value:
- attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(
- attr_identifier
- )
- return
-
- if not id and not external_reference and not value and attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
- return
-
- if value:
- max_length = attribute.values.model.name.field.max_length
- if not value.strip():
- attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(
- attr_identifier
- )
- elif max_length and len(value) > max_length:
- attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(
- attr_identifier
- )
-
- value_identifier = id or external_reference
- if value_identifier:
- if not value_identifier.strip():
- attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(
- attr_identifier
- )
-
-
-def validate_dropdown_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- if not attr_values.dropdown:
- if attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
- else:
- validate_single_selectable_field(
- attribute,
- attr_values.dropdown,
- attribute_errors,
- attr_identifier,
- )
-
-
-def validate_swatch_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- if not attr_values.swatch:
- if attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
- else:
- validate_single_selectable_field(
- attribute,
- attr_values.swatch,
- attribute_errors,
- attr_identifier,
- )
-
-
-def validate_multiselect_input(
- attribute: "Attribute",
- attr_values: "AttrValuesInput",
- attribute_errors: T_ERROR_DICT,
-):
- attr_identifier = attr_values.global_id or attr_values.external_reference
- if not attr_identifier:
- attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(
- attr_identifier
- )
- return
-
- multi_values = attr_values.multiselect
- if not multi_values:
- if attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
- 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]
- external_refs = [
- value.external_reference
- for value in multi_values
- if value.external_reference is not None
- ]
- if ids and values:
- attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(
- attr_identifier
- )
- return
- if not ids and not external_refs and not values and attribute.value_required:
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_identifier
- )
- return
-
- if (
- len(ids) > len(set(ids))
- or len(values) > len(set(values))
- or len(external_refs) > len(set(external_refs))
- ):
- attribute_errors[AttributeInputErrors.ERROR_DUPLICATED_VALUES].append(
- attr_identifier
- )
- return
-
- for attr_value in multi_values:
- validate_single_selectable_field(
- attribute,
- attr_value,
- attribute_errors,
- attr_identifier,
- )
-
-
-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)
- 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",
- attribute_errors: T_ERROR_DICT,
-):
- is_blank_date = (
- attribute.input_type == AttributeInputType.DATE and not attr_values.date
- )
- is_blank_date_time = (
- attribute.input_type == AttributeInputType.DATE_TIME
- and not attr_values.date_time
- )
-
- if attribute.value_required and (is_blank_date or is_blank_date_time):
- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
- attr_values.global_id
- )
-
-
-def validate_values(
- attr_identifier: str,
- attribute: "Attribute",
- values: list,
- attribute_errors: T_ERROR_DICT,
-):
- """To be deprecated together with `AttributeValueInput.values` field."""
- name_field = attribute.values.model.name.field
- is_numeric = attribute.input_type == AttributeInputType.NUMERIC
- if get_duplicated_values(values):
- attribute_errors[AttributeInputErrors.ERROR_DUPLICATED_VALUES].append(
- attr_identifier
- )
- for value in values:
- if value is None or (not is_numeric and not value.strip()):
- attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(
- attr_identifier
- )
- elif is_numeric:
- try:
- float(value)
- except ValueError:
- attribute_errors[
- AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED
- ].append(attr_identifier)
- elif name_field.max_length and len(value) > name_field.max_length:
- attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(
- attr_identifier
- )
-
-
-def validate_required_attributes(
- input_data: list[tuple["Attribute", "AttrValuesInput"]],
- attribute_qs: "QuerySet",
- errors: list[ValidationError],
- error_code_enum,
-):
- """Ensure all required attributes are supplied."""
-
- supplied_attribute_pk = [attribute.pk for attribute, _ in input_data]
-
- missing_required_attributes = attribute_qs.filter(
- Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)
- )
-
- if missing_required_attributes:
- ids = [
- graphene.Node.to_global_id("Attribute", attr.pk)
- for attr in missing_required_attributes
- ]
- error = ValidationError(
- "All attributes flagged as having a value required must be supplied.",
- code=error_code_enum.REQUIRED.value,
- params={"attributes": ids},
- )
- errors.append(error)
-
- return errors
-
-
-def prepare_error_list_from_error_attribute_mapping(
- attribute_errors: T_ERROR_DICT, error_code_enum
-):
- errors = []
- for error_data, attributes in attribute_errors.items():
- error_msg, error_type = error_data
- error = ValidationError(
- error_msg,
- code=getattr(error_code_enum, error_type).value,
- params={"attributes": attributes},
- )
- errors.append(error)
-
- return errors
-
-
-def has_input_modified_attribute_values(
- variant: product_models.ProductVariant, attributes_data: T_INPUT_MAP
-) -> bool:
- """Compare already assigned attribute values with values from AttrValuesInput.
-
- 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)
- if input_attribute_values != assigned_attributes:
- return True
- return 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 []
diff --git a/saleor/graphql/attribute/utils/__init__.py b/saleor/graphql/attribute/utils/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.py
new file mode 100644
index 0000000000..ca26dd1982
--- /dev/null
+++ b/saleor/graphql/attribute/utils/attribute_assignment.py
@@ -0,0 +1,369 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, cast
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.db.models import Q
+from django.db.models.expressions import Exists, OuterRef
+from graphql.error import GraphQLError
+
+from ....attribute import AttributeInputType
+from ....attribute import models as attribute_models
+from ....attribute.models import AttributeValue
+from ....attribute.utils import associate_attribute_values_to_instance
+from ....page.error_codes import PageErrorCode
+from ....product import models as product_models
+from ....product.error_codes import ProductErrorCode
+from ...core.utils import from_global_id_or_error
+from ...core.validators import validate_one_of_args_is_in_mutation
+from ..enums import AttributeValueBulkActionEnum
+from .shared import (
+ T_ERROR_DICT,
+ T_INSTANCE,
+ AttrValuesInput,
+ get_assignment_model_and_fk,
+)
+from .type_handlers import (
+ AttributeTypeHandler,
+ BooleanAttributeHandler,
+ DateTimeAttributeHandler,
+ FileAttributeHandler,
+ LegacyValuesHandler,
+ MultiSelectableAttributeHandler,
+ NumericAttributeHandler,
+ PlainTextAttributeHandler,
+ ReferenceAttributeHandler,
+ RichTextAttributeHandler,
+ SelectableAttributeHandler,
+)
+
+if TYPE_CHECKING:
+ from django.db.models import QuerySet
+
+
+T_INPUT_MAP = list[tuple["attribute_models.Attribute", "AttrValuesInput"]]
+
+
+class AttributeAssignmentMixin:
+ """Handles cleaning, validation, and saving of attribute data."""
+
+ HANDLER_MAPPING = {
+ AttributeInputType.DROPDOWN: SelectableAttributeHandler,
+ AttributeInputType.SWATCH: SelectableAttributeHandler,
+ AttributeInputType.MULTISELECT: MultiSelectableAttributeHandler,
+ AttributeInputType.FILE: FileAttributeHandler,
+ AttributeInputType.REFERENCE: ReferenceAttributeHandler,
+ AttributeInputType.RICH_TEXT: RichTextAttributeHandler,
+ AttributeInputType.PLAIN_TEXT: PlainTextAttributeHandler,
+ AttributeInputType.NUMERIC: NumericAttributeHandler,
+ AttributeInputType.DATE: DateTimeAttributeHandler,
+ AttributeInputType.DATE_TIME: DateTimeAttributeHandler,
+ AttributeInputType.BOOLEAN: BooleanAttributeHandler,
+ }
+
+ @classmethod
+ def _resolve_attribute_nodes(
+ cls,
+ qs: "QuerySet",
+ error_class,
+ *,
+ id_map: dict[int, str],
+ ext_ref_set: set[str],
+ ):
+ """Retrieve attributes nodes from given identifiers."""
+ nodes = list(
+ qs.filter(Q(pk__in=id_map.keys()) | Q(external_reference__in=ext_ref_set))
+ )
+
+ resolved_pks = {node.pk for node in nodes}
+ resolved_ext_refs = {node.external_reference for node in nodes}
+
+ missing_pks = [gid for pk, gid in id_map.items() if pk not in resolved_pks]
+ missing_ext_refs = list(ext_ref_set - resolved_ext_refs)
+
+ if missing_pks or missing_ext_refs:
+ missing = [f"ID: {gid}" for gid in missing_pks] + [
+ f"ExtRef: {ref}" for ref in missing_ext_refs
+ ]
+ raise ValidationError(
+ f"Could not resolve attributes: {', '.join(missing)}.",
+ code=error_class.NOT_FOUND.value,
+ )
+ return nodes
+
+ @classmethod
+ def clean_input(
+ cls,
+ raw_input: list[dict],
+ attributes_qs: "QuerySet",
+ creation: bool = True,
+ is_page_attributes: bool = False,
+ ) -> T_INPUT_MAP:
+ """Resolve, validate, and prepare attribute input."""
+ error_class = PageErrorCode if is_page_attributes else ProductErrorCode
+
+ id_to_values_input_map, ext_ref_to_values_input_map = (
+ cls._prepare_attribute_input_maps(raw_input, error_class)
+ )
+
+ attributes = cls._resolve_attribute_nodes(
+ attributes_qs,
+ error_class,
+ id_map={pk: v.global_id for pk, v in id_to_values_input_map.items()}, # type: ignore[misc]
+ ext_ref_set=set(ext_ref_to_values_input_map.keys()),
+ )
+
+ cleaned_input = cls._validate_and_clean_attributes(
+ attributes,
+ attributes_qs,
+ id_to_values_input_map,
+ ext_ref_to_values_input_map,
+ error_class,
+ creation,
+ )
+
+ return cleaned_input
+
+ @classmethod
+ def _prepare_attribute_input_maps(
+ cls, raw_input: list[dict], error_class
+ ) -> tuple[dict[int, AttrValuesInput], dict[str, AttrValuesInput]]:
+ """Prepare maps for attribute input based on IDs and external references."""
+ id_map: dict[int, AttrValuesInput] = {}
+ ext_ref_map: dict[str, AttrValuesInput] = {}
+
+ for attr_input in raw_input:
+ gid = attr_input.pop("id", None)
+ ext_ref = attr_input.pop("external_reference", None)
+
+ try:
+ validate_one_of_args_is_in_mutation(
+ "id", gid, "external_reference", ext_ref, use_camel_case=True
+ )
+ except ValidationError as e:
+ raise ValidationError(e.message, code=error_class.REQUIRED.value) from e
+
+ values = AttrValuesInput(
+ global_id=gid,
+ external_reference=ext_ref,
+ values=attr_input.pop("values", []),
+ file_url=attr_input.pop("file", None),
+ **attr_input,
+ )
+ if gid:
+ pk = cls._resolve_attribute_global_id(error_class, gid)
+ id_map[int(pk)] = values
+ if ext_ref:
+ ext_ref_map[ext_ref] = values
+
+ return id_map, ext_ref_map
+
+ @classmethod
+ def _validate_and_clean_attributes(
+ cls,
+ attributes: list[attribute_models.Attribute],
+ attributes_qs: "QuerySet[attribute_models.Attribute]",
+ id_to_values_input_map: dict[int, AttrValuesInput],
+ ext_ref_to_values_input_map: dict[str, AttrValuesInput],
+ error_class,
+ creation: bool,
+ ) -> T_INPUT_MAP:
+ """Validate and clean attribute inputs."""
+ cleaned_input = []
+ attribute_errors: T_ERROR_DICT = defaultdict(list)
+
+ for attribute in attributes:
+ values_input = id_to_values_input_map.get(
+ attribute.pk
+ ) or ext_ref_to_values_input_map.get(attribute.external_reference) # type: ignore[arg-type]
+ values_input = cast(AttrValuesInput, values_input)
+
+ is_legacy_path = values_input.values and attribute.input_type in {
+ AttributeInputType.DROPDOWN,
+ AttributeInputType.MULTISELECT,
+ AttributeInputType.SWATCH,
+ AttributeInputType.NUMERIC,
+ }
+
+ handler_class: type[LegacyValuesHandler | AttributeTypeHandler]
+ if is_legacy_path:
+ handler_class = LegacyValuesHandler
+ else:
+ handler_class = cls.HANDLER_MAPPING[attribute.input_type]
+
+ if handler_class:
+ handler = handler_class(attribute, values_input)
+ handler.clean_and_validate(attribute_errors)
+
+ cleaned_input.append((attribute, values_input))
+
+ errors = cls.prepare_error_list_from_error_attribute_mapping(
+ attribute_errors, error_class
+ )
+
+ if creation:
+ cls._validate_required_attributes(attributes_qs, cleaned_input, errors)
+
+ if errors:
+ raise ValidationError(errors)
+
+ return cleaned_input
+
+ @classmethod
+ def _resolve_attribute_global_id(cls, error_class, global_id: str) -> int:
+ """Resolve an Attribute global ID into an internal ID (int)."""
+ try:
+ graphene_type, internal_id = from_global_id_or_error(
+ global_id, only_type="Attribute"
+ )
+ except GraphQLError as e:
+ raise ValidationError(str(e), code=error_class.GRAPHQL_ERROR.value) from e
+ if not internal_id.isnumeric():
+ raise ValidationError(
+ f"An invalid ID value was passed: {global_id}",
+ code=error_class.INVALID.value,
+ )
+ return int(internal_id)
+
+ @staticmethod
+ def prepare_error_list_from_error_attribute_mapping(
+ attribute_errors: T_ERROR_DICT, error_code_enum
+ ):
+ errors = []
+ for error_data, attributes in attribute_errors.items():
+ error_msg, error_type = error_data
+ error = ValidationError(
+ error_msg,
+ code=getattr(error_code_enum, error_type).value,
+ params={"attributes": attributes},
+ )
+ errors.append(error)
+
+ return errors
+
+ @classmethod
+ def _validate_required_attributes(
+ cls,
+ attributes_qs: "QuerySet[attribute_models.Attribute]",
+ cleaned_input: T_INPUT_MAP,
+ errors: list[ValidationError],
+ ):
+ """Validate that all required attributes are provided."""
+ supplied_pks = {attr.pk for attr, _ in cleaned_input}
+ missing_required = attributes_qs.filter(
+ Q(value_required=True) & ~Q(pk__in=supplied_pks)
+ )
+ if missing_required:
+ missing_ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in missing_required
+ ]
+ error = ValidationError(
+ "All attributes flagged as having a value required must be supplied.",
+ code=ProductErrorCode.REQUIRED.value,
+ params={"attributes": missing_ids},
+ )
+ 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))
+ for attribute, values_input in cleaned_input:
+ is_legacy_path = values_input.values and attribute.input_type in {
+ AttributeInputType.DROPDOWN,
+ AttributeInputType.MULTISELECT,
+ AttributeInputType.SWATCH,
+ AttributeInputType.NUMERIC,
+ }
+
+ handler_class: type[AttributeTypeHandler] | None = None
+ if is_legacy_path:
+ handler_class = LegacyValuesHandler
+ else:
+ handler_class = cls.HANDLER_MAPPING.get(attribute.input_type)
+
+ if not handler_class:
+ continue
+
+ handler = handler_class(attribute, values_input)
+ prepared_values = handler.pre_save_value(instance)
+
+ if not prepared_values:
+ pre_save_bulk[AttributeValueBulkActionEnum.NONE].setdefault(
+ attribute, []
+ )
+ else:
+ for action, value_data in prepared_values:
+ pre_save_bulk[action][attribute].append(value_data)
+
+ attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)
+
+ attr_val_map = defaultdict(list)
+ clean_assignment_pks = []
+ for attribute, values in attribute_and_values.items():
+ if not values:
+ clean_assignment_pks.append(attribute.pk)
+ else:
+ attr_val_map[attribute.pk].extend(values)
+
+ associate_attribute_values_to_instance(instance, attr_val_map)
+
+ cls._clean_assignments(instance, clean_assignment_pks)
+
+ @classmethod
+ def _clean_assignments(cls, instance: T_INSTANCE, clean_assignment_pks: list[int]):
+ """Clean attribute assignments from the given instance."""
+ if not clean_assignment_pks:
+ return
+
+ values_to_unassign = attribute_models.AttributeValue.objects.filter(
+ attribute_id__in=clean_assignment_pks
+ )
+ # variant has old attribute structure so need to handle it differently
+ if isinstance(instance, product_models.ProductVariant):
+ cls._clean_variants_assignment(instance, clean_assignment_pks)
+ return
+ assignment_model, instance_fk = get_assignment_model_and_fk(instance)
+ assignment_model.objects.filter(
+ Exists(values_to_unassign.filter(id=OuterRef("value_id"))),
+ **{instance_fk: instance.pk},
+ ).delete()
+
+ @classmethod
+ def _clean_variants_assignment(cls, instance: T_INSTANCE, attribute_ids: list[int]):
+ attribute_variant = Exists(
+ attribute_models.AttributeVariant.objects.filter(
+ pk=OuterRef("assignment_id"),
+ attribute_id__in=attribute_ids,
+ )
+ )
+ attribute_models.AssignedVariantAttribute.objects.filter(
+ attribute_variant
+ ).filter(
+ variant_id=instance.id,
+ ).delete()
+
+ @classmethod
+ def _bulk_create_pre_save_values(cls, pre_save_bulk):
+ """Execute bulk database operations based on prepared data."""
+ results: dict[attribute_models.Attribute, list[AttributeValue]] = defaultdict(
+ list
+ )
+
+ for action, attribute_data in pre_save_bulk.items():
+ for attribute, values in attribute_data.items():
+ if action == AttributeValueBulkActionEnum.CREATE:
+ values = AttributeValue.objects.bulk_create(values)
+ elif action == AttributeValueBulkActionEnum.UPDATE_OR_CREATE:
+ values = AttributeValue.objects.bulk_update_or_create(values)
+ elif action == AttributeValueBulkActionEnum.GET_OR_CREATE:
+ values = AttributeValue.objects.bulk_get_or_create(values)
+ else:
+ # ensuring that empty values will be added to results,
+ # so assignments will be removed properly in that case
+ results.setdefault(attribute, [])
+
+ results[attribute].extend(values)
+
+ return results
diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.py
new file mode 100644
index 0000000000..b38c27641c
--- /dev/null
+++ b/saleor/graphql/attribute/utils/shared.py
@@ -0,0 +1,160 @@
+import datetime
+from collections import defaultdict
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, NamedTuple, cast
+
+from django.db.models import Model
+from django.db.models.expressions import Exists, OuterRef
+from django.utils.text import slugify
+
+from ....attribute import AttributeEntityType, AttributeInputType
+from ....attribute import models as attribute_models
+from ....page import models as page_models
+from ....product import models as product_models
+from ...product.utils import get_used_attribute_values_for_variant
+
+if TYPE_CHECKING:
+ from ....attribute.models import Attribute
+
+T_INSTANCE = product_models.Product | product_models.ProductVariant | page_models.Page
+T_ERROR_DICT = dict[tuple[str, str], list]
+
+
+@dataclass
+class AttrValuesForSelectableFieldInput:
+ id: str | None = None
+ external_reference: str | None = None
+ value: str | None = None
+
+
+@dataclass
+class AttrValuesInput:
+ global_id: str | None
+ external_reference: str | None = None
+ values: list[str] | None = None
+ dropdown: AttrValuesForSelectableFieldInput | None = None
+ swatch: AttrValuesForSelectableFieldInput | None = None
+ multiselect: list[AttrValuesForSelectableFieldInput] | None = None
+ numeric: str | None = None
+ references: list[str] | list[page_models.Page] | None = None
+ file_url: str | None = None
+ content_type: str | None = None
+ rich_text: dict | None = None
+ plain_text: str | None = None
+ boolean: bool | None = None
+ date: datetime.date | None = None
+ date_time: datetime.datetime | None = None
+
+
+class EntityTypeData(NamedTuple):
+ """Defines metadata for a referenceable entity type."""
+
+ model: type[Model]
+ name_field: str
+ value_field: str
+
+
+ENTITY_TYPE_MAPPING = {
+ AttributeEntityType.PAGE: EntityTypeData(
+ page_models.Page, "title", "reference_page"
+ ),
+ AttributeEntityType.PRODUCT: EntityTypeData(
+ product_models.Product, "name", "reference_product"
+ ),
+ AttributeEntityType.PRODUCT_VARIANT: EntityTypeData(
+ product_models.ProductVariant, "name", "reference_variant"
+ ),
+ AttributeEntityType.CATEGORY: EntityTypeData(
+ product_models.Category, "name", "reference_category"
+ ),
+ AttributeEntityType.COLLECTION: EntityTypeData(
+ product_models.Collection, "name", "reference_collection"
+ ),
+}
+
+
+def get_assignment_model_and_fk(instance: T_INSTANCE):
+ if isinstance(instance, page_models.Page):
+ return attribute_models.AssignedPageAttributeValue, "page_id"
+ if isinstance(instance, product_models.Product):
+ return attribute_models.AssignedProductAttributeValue, "product_id"
+ raise NotImplementedError(
+ f"Assignment for {type(instance).__name__} not implemented."
+ )
+
+
+def get_assigned_attribute_value_if_exists(
+ instance: T_INSTANCE, attribute: "Attribute", lookup_field: str, value
+):
+ """Unified method to find an existing assigned value."""
+ if isinstance(instance, product_models.ProductVariant):
+ # variant has old attribute structure so need to handle it differently
+ return get_variant_assigned_attribute_value_if_exists(
+ instance, attribute, lookup_field, value
+ )
+
+ assignment_model, instance_fk = get_assignment_model_and_fk(instance)
+ assigned_values = assignment_model.objects.filter(**{instance_fk: instance.pk})
+ return attribute_models.AttributeValue.objects.filter(
+ Exists(assigned_values.filter(value_id=OuterRef("id"))),
+ attribute_id=attribute.pk,
+ **{lookup_field: value},
+ ).first()
+
+
+def get_variant_assigned_attribute_value_if_exists(
+ instance: T_INSTANCE, attribute: "Attribute", lookup_field: str, value: str
+):
+ variant = cast(product_models.ProductVariant, instance)
+ attribute_variant = Exists(
+ attribute_models.AttributeVariant.objects.filter(
+ pk=OuterRef("assignment_id"),
+ attribute_id=attribute.pk,
+ )
+ )
+ assigned_variant = Exists(
+ attribute_models.AssignedVariantAttribute.objects.filter(
+ attribute_variant
+ ).filter(
+ variant_id=variant.pk,
+ values=OuterRef("pk"),
+ )
+ )
+ return attribute_models.AttributeValue.objects.filter(
+ assigned_variant, **{lookup_field: value}
+ ).first()
+
+
+def has_input_modified_attribute_values(
+ variant: product_models.ProductVariant,
+ attributes_data: list[tuple["Attribute", AttrValuesInput]],
+) -> bool:
+ """Compare already assigned attribute values with values from AttrValuesInput.
+
+ 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)
+ if input_attribute_values != assigned_attributes:
+ return True
+ return 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 []
diff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.py
new file mode 100644
index 0000000000..d5cd6beb12
--- /dev/null
+++ b/saleor/graphql/attribute/utils/type_handlers.py
@@ -0,0 +1,675 @@
+import abc
+import datetime
+import re
+from typing import TYPE_CHECKING
+
+from django.core.exceptions import ValidationError
+from django.db.models import Q
+from django.template.defaultfilters import truncatechars
+from django.utils.text import slugify
+from graphql.error import GraphQLError
+from text_unidecode import unidecode
+
+from ....attribute import AttributeEntityType, AttributeInputType
+from ....attribute import models as attribute_models
+from ....attribute.models import AttributeValue
+from ....core.utils import (
+ generate_unique_slug,
+ prepare_unique_attribute_value_slug,
+ prepare_unique_slug,
+)
+from ....core.utils.editorjs import clean_editor_js
+from ....core.utils.url import get_default_storage_root_url
+from ...core.utils import from_global_id_or_error, get_duplicated_values
+from ...utils import get_nodes
+from ..enums import AttributeValueBulkActionEnum
+from .shared import (
+ ENTITY_TYPE_MAPPING,
+ T_ERROR_DICT,
+ T_INSTANCE,
+ AttrValuesForSelectableFieldInput,
+ AttrValuesInput,
+ get_assigned_attribute_value_if_exists,
+)
+
+if TYPE_CHECKING:
+ from ....attribute.models import Attribute
+
+
+class AttributeInputErrors:
+ """Defines error messages and codes for attribute validation."""
+
+ # General Errors
+ VALUE_REQUIRED = ("Attribute expects a value but none were given.", "REQUIRED")
+ BLANK_VALUE = ("Attribute values cannot be blank.", "REQUIRED")
+ DUPLICATED_VALUES = (
+ "Duplicated attribute values are provided.",
+ "DUPLICATED_INPUT_ITEM",
+ )
+ INVALID_INPUT = ("Invalid value provided for attribute.", "INVALID")
+ MORE_THAN_ONE_VALUE = (
+ "Attribute must take only one value.",
+ "INVALID",
+ )
+
+ ID_AND_VALUE_PROVIDED = (
+ "Attribute values cannot be assigned by both id and value.",
+ "INVALID",
+ )
+ ID_AND_EXTERNAL_REFERENCE_PROVIDED = (
+ "Attribute values cannot be assigned by both id and external reference",
+ "INVALID",
+ )
+ MAX_LENGTH_EXCEEDED = ("Attribute value length is exceeded.", "INVALID")
+
+ # File Errors
+ FILE_URL_REQUIRED = ("A file URL is required for this attribute.", "REQUIRED")
+ INVALID_FILE_URL = (
+ "The file_url must be the path to the default storage.",
+ "INVALID",
+ )
+
+ # Reference Errors
+ REFERENCE_REQUIRED = ("A reference is required for this attribute.", "REQUIRED")
+ INVALID_REFERENCE = ("Invalid reference type.", "INVALID")
+
+ # Numeric Errors
+ ERROR_NUMERIC_VALUE_REQUIRED = ("Numeric value is required.", "INVALID")
+
+
+class AttributeTypeHandler(abc.ABC):
+ """Abstract base class for attribute type-specific logic."""
+
+ def __init__(
+ self,
+ attribute: "Attribute",
+ values_input: AttrValuesInput,
+ ):
+ self.attribute = attribute
+ self.values_input = values_input
+ self.attribute_identifier = (
+ values_input.global_id or values_input.external_reference
+ )
+ self.attr_identifier = values_input.global_id or values_input.external_reference
+
+ @abc.abstractmethod
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ """Clean, resolve, and validate input values."""
+
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def pre_save_value(
+ self, instance: T_INSTANCE
+ ) -> list[tuple[AttributeValueBulkActionEnum, dict | AttributeValue]]:
+ """Prepare attribute value data for bulk database operations."""
+
+ raise NotImplementedError
+
+ def _update_or_create_value(
+ self,
+ instance: T_INSTANCE,
+ value_defaults: dict,
+ ):
+ slug = slugify(unidecode(f"{instance.id}_{self.attribute.id}"))
+ value = {
+ "attribute": self.attribute,
+ "slug": slug,
+ "defaults": value_defaults,
+ }
+ return [
+ (AttributeValueBulkActionEnum.UPDATE_OR_CREATE, value),
+ ]
+
+ @classmethod
+ def prepare_attribute_values(
+ cls, attribute: attribute_models.Attribute, values: list[str]
+ ) -> list[tuple]:
+ slug_to_value_map = {}
+ name_to_value_map = {}
+ for val in attribute.values.filter(Q(name__in=values) | Q(slug__in=values)):
+ slug_to_value_map[val.slug] = val
+ name_to_value_map[val.name] = val
+
+ existing_slugs = cls.get_existing_slugs(attribute, values)
+
+ results = []
+ for value_str in values:
+ value_obj = slug_to_value_map.get(value_str) or name_to_value_map.get(
+ value_str
+ )
+
+ if value_obj:
+ results.append((AttributeValueBulkActionEnum.NONE, value_obj))
+ else:
+ # If no existing value is found, prepare a new one for creation.
+ unique_slug = prepare_unique_slug(
+ slugify(unidecode(value_str)), existing_slugs
+ )
+ new_value = AttributeValue(
+ attribute=attribute, name=value_str, slug=unique_slug
+ )
+ results.append((AttributeValueBulkActionEnum.CREATE, new_value))
+
+ # the set of existing slugs must be updated to not generate
+ # accidentally the same slug for two or more values
+ existing_slugs.add(unique_slug)
+
+ # extend name to slug value to not create two elements with the same name
+ name_to_value_map[new_value.name] = new_value
+
+ return results
+
+ @staticmethod
+ def get_existing_slugs(attribute: attribute_models.Attribute, values: list[str]):
+ lookup = Q()
+ for value in values:
+ lookup |= Q(slug__startswith=slugify(unidecode(value)))
+
+ existing_slugs = set(
+ attribute.values.filter(lookup).values_list("slug", flat=True)
+ )
+ return existing_slugs
+
+
+class SelectableAttributeHandler(AttributeTypeHandler):
+ """Handler for Dropdown and Swatch attribute types."""
+
+ def get_selectable_input(self) -> AttrValuesForSelectableFieldInput | None:
+ """Get the specific input object for dropdown or swatch."""
+
+ if self.attribute.input_type == AttributeInputType.DROPDOWN:
+ return self.values_input.dropdown
+ if self.attribute.input_type == AttributeInputType.SWATCH:
+ return self.values_input.swatch
+ return None
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ selectable_input = self.get_selectable_input()
+
+ if not selectable_input:
+ if self.attribute.value_required:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+ return
+
+ self._validate_selectable_field(
+ selectable_input,
+ value_required=self.attribute.value_required,
+ attribute_errors=attribute_errors,
+ )
+
+ def _validate_selectable_field(
+ self,
+ attr_value_input: AttrValuesForSelectableFieldInput,
+ value_required: bool,
+ attribute_errors: T_ERROR_DICT,
+ ):
+ """Validate a single input for a selectable field."""
+ id = attr_value_input.id
+ value = attr_value_input.value
+ external_reference = attr_value_input.external_reference
+
+ if id and external_reference:
+ attribute_errors[
+ AttributeInputErrors.ID_AND_EXTERNAL_REFERENCE_PROVIDED
+ ].append(self.attr_identifier)
+ return
+
+ if id and value:
+ attribute_errors[AttributeInputErrors.ID_AND_VALUE_PROVIDED].append(
+ self.attr_identifier
+ )
+ return
+
+ if not id and not external_reference and not value and value_required:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attr_identifier
+ )
+ return
+
+ if value:
+ max_length = self.attribute.values.model.name.field.max_length
+ if not value.strip():
+ attribute_errors[AttributeInputErrors.BLANK_VALUE].append(
+ self.attr_identifier
+ )
+ elif max_length and len(value) > max_length:
+ attribute_errors[AttributeInputErrors.MAX_LENGTH_EXCEEDED].append(
+ self.attr_identifier
+ )
+
+ value_identifier = id or external_reference
+ if value_identifier:
+ if not value_identifier.strip():
+ attribute_errors[AttributeInputErrors.BLANK_VALUE].append(
+ self.attr_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ selectable_input = self.get_selectable_input()
+ if not selectable_input:
+ return []
+
+ id, value, ext_ref = (
+ selectable_input.id,
+ selectable_input.value,
+ selectable_input.external_reference,
+ )
+
+ 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)]
+
+ if ext_ref:
+ value = attribute_models.AttributeValue.objects.get( # type: ignore[assignment]
+ external_reference=ext_ref
+ )
+ if not value:
+ raise ValidationError(
+ "Attribute value with given externalReference can't be found"
+ )
+ return [(AttributeValueBulkActionEnum.NONE, value)]
+
+ 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:
+ raise ValidationError("Attribute value with given ID can't be found")
+ return [(AttributeValueBulkActionEnum.NONE, value)]
+
+ if value:
+ return self.prepare_attribute_values(self.attribute, [value])
+
+ return []
+
+
+class MultiSelectableAttributeHandler(SelectableAttributeHandler):
+ """Handler for Multiselect attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ multi_values = self.values_input.multiselect
+
+ if not multi_values:
+ if self.attribute.value_required:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+ return
+
+ 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]
+ external_refs = [
+ value.external_reference
+ for value in multi_values
+ if value.external_reference is not None
+ ]
+ if ids and values:
+ attribute_errors[AttributeInputErrors.ID_AND_VALUE_PROVIDED].append(
+ self.attribute_identifier
+ )
+ elif (
+ not ids
+ and not external_refs
+ and not values
+ and self.attribute.value_required
+ ):
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+ elif (
+ len(ids) > len(set(ids))
+ or len(values) > len(set(values))
+ or len(external_refs) > len(set(external_refs))
+ ):
+ attribute_errors[AttributeInputErrors.DUPLICATED_VALUES].append(
+ self.attribute_identifier
+ )
+
+ for value_input in multi_values:
+ self._validate_selectable_field(
+ value_input,
+ value_required=self.attribute.value_required,
+ attribute_errors=attribute_errors,
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ multi_values = self.values_input.multiselect
+ if not multi_values:
+ return []
+
+ results = []
+ values_to_create = []
+ pks_to_fetch = []
+ ext_refs_to_fetch = []
+
+ 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)
+ elif v_input.external_reference and not v_input.value:
+ ext_refs_to_fetch.append(v_input.external_reference)
+ 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]
+ )
+
+ # Prepare new values
+ if values_to_create:
+ results.extend(
+ self.prepare_attribute_values(self.attribute, values_to_create)
+ )
+
+ return results
+
+
+class FileAttributeHandler(AttributeTypeHandler):
+ """Handler for File attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ storage_root_url = get_default_storage_root_url()
+ file_url = self.values_input.file_url
+ if self.attribute.value_required and (not file_url or not file_url.strip()):
+ attribute_errors[AttributeInputErrors.FILE_URL_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ if file_url and not file_url.startswith(storage_root_url):
+ attribute_errors[AttributeInputErrors.INVALID_FILE_URL].append(
+ self.attribute_identifier
+ )
+
+ self.values_input.file_url = (
+ re.sub(storage_root_url, "", file_url) if file_url is not None else file_url
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ file_url = self.values_input.file_url
+ if not file_url:
+ return []
+
+ # File attributes should be unique per assignment, so we create a new value
+ # unless this exact URL is already assigned to this instance.
+ value = get_assigned_attribute_value_if_exists(
+ instance, self.attribute, "file_url", file_url
+ )
+ if value:
+ return [(AttributeValueBulkActionEnum.NONE, value)]
+
+ name = file_url.split("/")[-1]
+ value_obj = AttributeValue(
+ attribute=self.attribute,
+ file_url=file_url,
+ name=name,
+ content_type=self.values_input.content_type,
+ )
+ value_obj.slug = generate_unique_slug(value_obj, name)
+ return [(AttributeValueBulkActionEnum.CREATE, value_obj)]
+
+
+class ReferenceAttributeHandler(AttributeTypeHandler):
+ """Handler for Reference attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ """Resolve Graphene IDs and then validate the result.
+
+ Modifies `self.values_input.references` in place.
+ """
+ references = self.values_input.references
+
+ if not references:
+ if self.attribute.value_required:
+ attribute_errors[AttributeInputErrors.REFERENCE_REQUIRED].append(
+ self.attribute_identifier
+ )
+ return
+
+ if not self.attribute.entity_type:
+ attribute_errors[AttributeInputErrors.INVALID_INPUT].append(
+ self.attribute_identifier
+ )
+ return
+ entity_data = ENTITY_TYPE_MAPPING[self.attribute.entity_type]
+
+ try:
+ ref_instances = get_nodes(
+ references, self.attribute.entity_type, model=entity_data.model
+ )
+ self.values_input.references = ref_instances
+ except GraphQLError:
+ self.values_input.references = []
+ attribute_errors[AttributeInputErrors.INVALID_REFERENCE].append(
+ self.attribute_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ references = self.values_input.references
+ entity_type = self.attribute.entity_type
+ if not references or not entity_type:
+ return []
+
+ entity_data = ENTITY_TYPE_MAPPING[entity_type]
+ results = []
+ for ref in references:
+ name = getattr(ref, entity_data.name_field)
+ if entity_type == AttributeEntityType.PRODUCT_VARIANT:
+ name = f"{ref.product.name}: {name}" # type: ignore[union-attr]
+
+ # Reference values are unique per referenced entity
+ slug = slugify(unidecode(f"{instance.id}_{ref.id}")) # type: ignore[union-attr]
+ defaults = {"name": name}
+ value_data = {
+ "attribute": self.attribute,
+ "slug": slug,
+ "defaults": defaults,
+ entity_data.value_field: ref,
+ }
+ results.append((AttributeValueBulkActionEnum.GET_OR_CREATE, value_data))
+ return results
+
+
+class PlainTextAttributeHandler(AttributeTypeHandler):
+ """Handler for Plain Text attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ plain_text = self.values_input.plain_text
+ if self.attribute.value_required and (not plain_text or not plain_text.strip()):
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ plain_text = self.values_input.plain_text
+ if plain_text is None:
+ return []
+
+ defaults = {
+ "plain_text": plain_text,
+ "name": truncatechars(plain_text, 200),
+ }
+ return self._update_or_create_value(instance, defaults)
+
+
+class RichTextAttributeHandler(AttributeTypeHandler):
+ """Handler for Rich Text attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ text = clean_editor_js(self.values_input.rich_text or {}, to_string=True)
+
+ if not text.strip() and self.attribute.value_required:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ rich_text = self.values_input.rich_text
+ if rich_text is None:
+ return []
+
+ defaults = {
+ "rich_text": rich_text,
+ "name": truncatechars(clean_editor_js(rich_text, to_string=True), 200),
+ }
+ return self._update_or_create_value(instance, defaults)
+
+
+class NumericAttributeHandler(AttributeTypeHandler):
+ """Handler for Numeric attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ numeric_val = self.values_input.numeric
+ if self.attribute.value_required and numeric_val is None:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ if numeric_val is not None:
+ try:
+ float(numeric_val)
+ except (ValueError, TypeError):
+ attribute_errors[
+ AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED
+ ].append(self.attribute_identifier)
+
+ if isinstance(numeric_val, bool):
+ attribute_errors[AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ numeric_val = self.values_input.numeric
+ if numeric_val is None:
+ return []
+ defaults = {
+ "name": numeric_val,
+ }
+ return self._update_or_create_value(instance, defaults)
+
+
+class DateTimeAttributeHandler(AttributeTypeHandler):
+ """Handler for Date and DateTime attribute types."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ is_date = self.attribute.input_type == AttributeInputType.DATE
+ has_value = self.values_input.date if is_date else self.values_input.date_time
+ if self.attribute.value_required and not has_value:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ is_date = self.attribute.input_type == AttributeInputType.DATE
+ value = self.values_input.date if is_date else self.values_input.date_time
+ if not value:
+ return []
+
+ date_time_val = (
+ datetime.datetime.combine(value, datetime.time.min, tzinfo=datetime.UTC)
+ if is_date
+ else value
+ )
+ defaults = {"name": str(value), "date_time": date_time_val}
+ return self._update_or_create_value(instance, defaults)
+
+
+class BooleanAttributeHandler(AttributeTypeHandler):
+ """Handler for Boolean attribute type."""
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ if self.attribute.value_required and self.values_input.boolean is None:
+ attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
+ self.attribute_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ boolean_val = self.values_input.boolean
+ if boolean_val is None:
+ return []
+
+ boolean = bool(boolean_val)
+ value = {
+ "attribute": self.attribute,
+ "slug": slugify(unidecode(f"{self.attribute.id}_{boolean}")),
+ "defaults": {
+ "name": f"{self.attribute.name}: {'Yes' if boolean else 'No'}",
+ "boolean": boolean,
+ },
+ }
+ return [(AttributeValueBulkActionEnum.GET_OR_CREATE, value)]
+
+
+class LegacyValuesHandler(AttributeTypeHandler):
+ """Handler for the deprecated `values: [String!]` field.
+
+ Applicable for Dropdown, Swatch, Multiselect, and Numeric attribute types.
+ """
+
+ def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
+ """Validate a list of raw string values."""
+
+ values = self.values_input.values or []
+
+ # Validation for single-select types
+ if (
+ self.attribute.input_type not in [AttributeInputType.MULTISELECT]
+ and len(values) > 1
+ ):
+ attribute_errors[AttributeInputErrors.MORE_THAN_ONE_VALUE].append(
+ self.attr_identifier
+ )
+
+ # Shared validation
+ if get_duplicated_values(values):
+ attribute_errors[AttributeInputErrors.DUPLICATED_VALUES].append(
+ self.attr_identifier
+ )
+
+ is_numeric = self.attribute.input_type == AttributeInputType.NUMERIC
+ name_field = self.attribute.values.model.name.field
+
+ for value in values:
+ if value is None or (not is_numeric and not str(value).strip()):
+ attribute_errors[AttributeInputErrors.BLANK_VALUE].append(
+ self.attr_identifier
+ )
+ continue
+
+ if is_numeric:
+ try:
+ float(value)
+ except (ValueError, TypeError):
+ attribute_errors[AttributeInputErrors.INVALID_INPUT].append(
+ self.attr_identifier
+ )
+ elif name_field.max_length and len(value) > name_field.max_length:
+ attribute_errors[AttributeInputErrors.MAX_LENGTH_EXCEEDED].append(
+ self.attr_identifier
+ )
+
+ def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
+ if not self.values_input.values:
+ return []
+
+ if self.attribute.input_type == AttributeInputType.NUMERIC:
+ value = self.values_input.values[0]
+ defaults = {
+ "name": value,
+ }
+ return self._update_or_create_value(instance, defaults)
+
+ return self.prepare_attribute_values(self.attribute, self.values_input.values)
diff --git a/saleor/graphql/page/mutations/page_create.py b/saleor/graphql/page/mutations/page_create.py
index 7e028a3825..6dadc8c213 100644
--- a/saleor/graphql/page/mutations/page_create.py
+++ b/saleor/graphql/page/mutations/page_create.py
@@ -8,7 +8,7 @@ from ....page import models
from ....page.error_codes import PageErrorCode
from ....permission.enums import PagePermissions
from ...attribute.types import AttributeValueInput
-from ...attribute.utils import PageAttributeAssignmentMixin
+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
from ...core import ResolveInfo
from ...core.context import ChannelContext
from ...core.descriptions import DEPRECATED_IN_3X_INPUT, RICH_CONTENT
@@ -67,9 +67,9 @@ class PageCreate(DeprecatedModelMutation):
error_type_field = "page_errors"
@classmethod
- def clean_attributes(cls, attributes: dict, page_type: models.PageType):
+ def clean_attributes(cls, attributes: list[dict], page_type: models.PageType):
attributes_qs = page_type.page_attributes.prefetch_related("values")
- cleaned_attributes = PageAttributeAssignmentMixin.clean_input(
+ cleaned_attributes = AttributeAssignmentMixin.clean_input(
attributes, attributes_qs, is_page_attributes=True
)
return cleaned_attributes
@@ -128,7 +128,7 @@ class PageCreate(DeprecatedModelMutation):
attributes = cleaned_data.get("attributes")
if attributes:
- PageAttributeAssignmentMixin.save(instance, attributes)
+ AttributeAssignmentMixin.save(instance, attributes)
@classmethod
def save(cls, info: ResolveInfo, instance, cleaned_input):
diff --git a/saleor/graphql/page/mutations/page_update.py b/saleor/graphql/page/mutations/page_update.py
index 50b1eb5df4..24f56e8d2e 100644
--- a/saleor/graphql/page/mutations/page_update.py
+++ b/saleor/graphql/page/mutations/page_update.py
@@ -2,7 +2,7 @@ import graphene
from ....page import models
from ....permission.enums import PagePermissions
-from ...attribute.utils import PageAttributeAssignmentMixin
+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
from ...core import ResolveInfo
from ...core.context import ChannelContext
from ...core.types import PageError
@@ -27,9 +27,9 @@ class PageUpdate(PageCreate):
error_type_field = "page_errors"
@classmethod
- def clean_attributes(cls, attributes: dict, page_type: models.PageType):
+ def clean_attributes(cls, attributes: list[dict], page_type: models.PageType):
attributes_qs = page_type.page_attributes.prefetch_related("values")
- cleaned_attributes = PageAttributeAssignmentMixin.clean_input(
+ cleaned_attributes = AttributeAssignmentMixin.clean_input(
attributes, attributes_qs, creation=False, is_page_attributes=True
)
return cleaned_attributes
diff --git a/saleor/graphql/page/tests/mutations/test_page_bulk_delete.py b/saleor/graphql/page/tests/mutations/test_page_bulk_delete.py
index 96cca2a39e..89ad9d2aac 100644
--- a/saleor/graphql/page/tests/mutations/test_page_bulk_delete.py
+++ b/saleor/graphql/page/tests/mutations/test_page_bulk_delete.py
@@ -2,8 +2,8 @@ import graphene
import pytest
from .....attribute.models import AttributeValue
+from .....attribute.utils import associate_attribute_values_to_instance
from .....page.models import Page
-from ....attribute.utils import associate_attribute_values_to_instance
from ....tests.utils import get_graphql_content
PAGE_BULK_DELETE_MUTATION = """
diff --git a/saleor/graphql/page/tests/mutations/test_page_types_bulk_delete.py b/saleor/graphql/page/tests/mutations/test_page_types_bulk_delete.py
index 5ca11eaaee..5af58a2ac1 100644
--- a/saleor/graphql/page/tests/mutations/test_page_types_bulk_delete.py
+++ b/saleor/graphql/page/tests/mutations/test_page_types_bulk_delete.py
@@ -3,8 +3,8 @@ from unittest import mock
import graphene
import pytest
+from .....attribute.utils import associate_attribute_values_to_instance
from .....page.models import Page
-from ....attribute.utils import associate_attribute_values_to_instance
from ....tests.utils import assert_no_permission, get_graphql_content
PAGE_TYPE_BULK_DELETE_MUTATION = """
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index f92170f0fe..ea5eebd7cc 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -24,7 +24,7 @@ from ....warehouse.models import Warehouse
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...attribute.types import AttributeValueInput
-from ...attribute.utils import ProductAttributeAssignmentMixin
+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
from ...core.context import ChannelContext
from ...core.descriptions import RICH_CONTENT
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
@@ -289,7 +289,7 @@ class ProductBulkCreate(BaseMutation):
if attributes := cleaned_input.get("attributes"):
try:
attributes_qs = cleaned_input["product_type"].product_attributes.all()
- attributes = ProductAttributeAssignmentMixin.clean_input(
+ attributes = AttributeAssignmentMixin.clean_input(
attributes, attributes_qs
)
cleaned_input["attributes"] = attributes
@@ -796,7 +796,7 @@ class ProductBulkCreate(BaseMutation):
models.ProductChannelListing.objects.bulk_create(listings_to_create)
for product, attributes in attributes_to_save:
- ProductAttributeAssignmentMixin.save(product, attributes)
+ AttributeAssignmentMixin.save(product, attributes)
if variants_input_data:
variants = cls.save_variants(info, variants_input_data)
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
index e49a307e79..4cb416d8ff 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
@@ -20,7 +20,7 @@ from ...attribute.types import (
AttributeValueDescriptions,
AttributeValueSelectableTypeInput,
)
-from ...attribute.utils import AttributeAssignmentMixin
+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
from ...core.context import ChannelContext
from ...core.descriptions import DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
index 80bb67f8aa..02a67f41a7 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
@@ -16,7 +16,7 @@ from ....warehouse import models as warehouse_models
from ....warehouse.management import delete_stocks, stock_bulk_update
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
-from ...attribute.utils import AttributeAssignmentMixin
+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.enums import ErrorPolicyEnum
from ...core.mutations import BaseMutation, DeprecatedModelMutation
diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.py
index 878bf27a7e..5ce4016c95 100644
--- a/saleor/graphql/product/mutations/product/product_create.py
+++ b/saleor/graphql/product/mutations/product/product_create.py
@@ -6,7 +6,8 @@ from .....core.tracing import traced_atomic_transaction
from .....permission.enums import ProductPermissions
from .....product import models
from ....attribute.types import AttributeValueInput
-from ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixin
+from ....attribute.utils.attribute_assignment import AttributeAssignmentMixin
+from ....attribute.utils.shared import AttrValuesInput
from ....core import ResolveInfo
from ....core.context import ChannelContext
from ....core.descriptions import (
@@ -159,10 +160,8 @@ class ProductCreate(DeprecatedModelMutation):
if attributes and product_type:
try:
attributes_qs = product_type.product_attributes.all()
- cleaned_input["attributes"] = (
- ProductAttributeAssignmentMixin.clean_input(
- attributes, attributes_qs
- )
+ cleaned_input["attributes"] = AttributeAssignmentMixin.clean_input(
+ attributes, attributes_qs
)
except ValidationError as e:
raise ValidationError({"attributes": e}) from e
@@ -174,7 +173,7 @@ class ProductCreate(DeprecatedModelMutation):
instance.save()
attributes = cleaned_input.get("attributes")
if attributes:
- ProductAttributeAssignmentMixin.save(instance, attributes)
+ AttributeAssignmentMixin.save(instance, attributes)
@classmethod
def _save_m2m(cls, _info: ResolveInfo, instance, cleaned_data):
diff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.py
index b173e235ea..61ff201b6d 100644
--- a/saleor/graphql/product/mutations/product/product_update.py
+++ b/saleor/graphql/product/mutations/product/product_update.py
@@ -6,7 +6,8 @@ from .....core.tracing import traced_atomic_transaction
from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
-from ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixin
+from ....attribute.utils.attribute_assignment import AttributeAssignmentMixin
+from ....attribute.utils.shared import AttrValuesInput
from ....core import ResolveInfo
from ....core.context import ChannelContext
from ....core.mutations import ModelWithExtRefMutation
@@ -50,7 +51,7 @@ class ProductUpdate(ModelWithExtRefMutation):
# prefetch them.
object_id = cls.get_object_id(**data)
if object_id and data.get("attributes"):
- # Prefetches needed by ProductAttributeAssignmentMixin and
+ # Prefetches needed by AttributeAssignmentMixin and
# associate_attribute_values_to_instance
qs = cls.Meta.model.objects.prefetch_related(
"product_type__product_attributes__values",
@@ -84,10 +85,8 @@ class ProductUpdate(ModelWithExtRefMutation):
if attributes and product_type:
try:
attributes_qs = product_type.product_attributes.all()
- cleaned_input["attributes"] = (
- ProductAttributeAssignmentMixin.clean_input(
- attributes, attributes_qs, creation=False
- )
+ cleaned_input["attributes"] = AttributeAssignmentMixin.clean_input(
+ attributes, attributes_qs, creation=False
)
except ValidationError as e:
raise ValidationError({"attributes": e}) from e
@@ -115,7 +114,7 @@ class ProductUpdate(ModelWithExtRefMutation):
instance.save()
attributes = cleaned_input.get("attributes")
if attributes:
- ProductAttributeAssignmentMixin.save(instance, attributes)
+ AttributeAssignmentMixin.save(instance, attributes)
@classmethod
def _save_m2m(cls, _info: ResolveInfo, instance, cleaned_data):
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py b/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py
index 9d3627762f..4816f2ec18 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_cleaner.py
@@ -4,7 +4,7 @@ from django.core.exceptions import ValidationError
from .....attribute import models as attribute_models
from .....product.error_codes import ProductErrorCode
-from ....attribute.utils import (
+from ....attribute.utils.shared import (
AttrValuesInput,
get_values_from_attribute_values_input,
)
@@ -58,7 +58,8 @@ def validate_duplicated_attribute_values(
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)
- attribute_values[attr_data.global_id].extend(values)
+ if attr_data.global_id:
+ attribute_values[attr_data.global_id].extend(values)
if attribute_values in used_attribute_values:
raise ValidationError(
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index 43e505f866..c08acad74e 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -9,10 +9,10 @@ from .....product import models
from .....product.error_codes import ProductErrorCode
from .....product.utils.variants import generate_and_set_variant_name
from ....attribute.types import AttributeValueInput
-from ....attribute.utils import (
+from ....attribute.utils.attribute_assignment import (
AttributeAssignmentMixin,
- AttrValuesInput,
)
+from ....attribute.utils.shared import AttrValuesInput
from ....core import ResolveInfo
from ....core.context import ChannelContext
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
@@ -145,7 +145,7 @@ class ProductVariantCreate(DeprecatedModelMutation):
cleaner.clean_quantity_limit(cleaned_input)
if stocks := cleaned_input.get("stocks"):
cls.check_for_duplicates_in_stocks(stocks)
- cls.clean_attributes(cleaned_input)
+ 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)
@@ -153,7 +153,7 @@ class ProductVariantCreate(DeprecatedModelMutation):
return cleaned_input
@classmethod
- def clean_attributes(cls, cleaned_input: dict):
+ 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)
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
index c784665946..d9900a498d 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
@@ -11,8 +11,10 @@ from .....permission.enums import ProductPermissions
from .....product import models
from .....product.error_codes import ProductErrorCode
from .....product.utils.variants import generate_and_set_variant_name
-from ....attribute.utils import (
+from ....attribute.utils.attribute_assignment import (
AttributeAssignmentMixin,
+)
+from ....attribute.utils.shared import (
AttrValuesInput,
has_input_modified_attribute_values,
)
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index 0944f723d5..34bb4b65c6 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -26,7 +26,7 @@ from .....graphql.tests.utils import get_graphql_content
from .....plugins.manager import PluginsManager
from .....product.error_codes import ProductErrorCode
from .....product.models import Product
-from ....attribute.utils import AttributeInputErrors
+from ....attribute.utils.type_handlers import AttributeInputErrors
MUTATION_UPDATE_PRODUCT = """
mutation updateProduct($productId: ID!, $input: ProductInput!) {
@@ -2809,15 +2809,15 @@ def test_update_product_with_selectable_attribute_by_both_id_and_value(
assert not data["product"]
assert len(errors) == 1
- assert errors[0]["message"] == AttributeInputErrors.ERROR_ID_AND_VALUE[0]
+ assert errors[0]["message"] == AttributeInputErrors.ID_AND_VALUE_PROVIDED[0]
@pytest.mark.parametrize(
("value", "expected_result"),
[
- ("", AttributeInputErrors.ERROR_NO_VALUE_GIVEN),
- (" ", AttributeInputErrors.ERROR_BLANK_VALUE),
- (None, AttributeInputErrors.ERROR_NO_VALUE_GIVEN),
+ ("", AttributeInputErrors.VALUE_REQUIRED),
+ (" ", AttributeInputErrors.BLANK_VALUE),
+ (None, AttributeInputErrors.VALUE_REQUIRED),
],
)
def test_update_product_with_selectable_attribute_value_required(
@@ -2910,7 +2910,7 @@ def test_update_product_with_selectable_attribute_exceed_max_length(
assert not data["product"]
assert len(errors) == 1
- assert errors[0]["message"] == AttributeInputErrors.ERROR_MAX_LENGTH[0]
+ assert errors[0]["message"] == AttributeInputErrors.MAX_LENGTH_EXCEEDED[0]
def test_update_product_with_multiselect_attribute_by_both_id_and_value(
@@ -2953,7 +2953,7 @@ def test_update_product_with_multiselect_attribute_by_both_id_and_value(
assert not data["product"]
assert len(errors) == 1
- assert errors[0]["message"] == AttributeInputErrors.ERROR_ID_AND_VALUE[0]
+ assert errors[0]["message"] == AttributeInputErrors.ID_AND_VALUE_PROVIDED[0]
def test_update_product_with_multiselect_attribute_by_id_duplicated(
@@ -2995,7 +2995,7 @@ def test_update_product_with_multiselect_attribute_by_id_duplicated(
assert not data["product"]
assert len(errors) == 1
- assert errors[0]["message"] == AttributeInputErrors.ERROR_DUPLICATED_VALUES[0]
+ assert errors[0]["message"] == AttributeInputErrors.DUPLICATED_VALUES[0]
def test_update_product_with_multiselect_attribute_by_name_duplicated(
@@ -3039,7 +3039,7 @@ def test_update_product_with_multiselect_attribute_by_name_duplicated(
assert not data["product"]
assert len(errors) == 1
- assert errors[0]["message"] == AttributeInputErrors.ERROR_DUPLICATED_VALUES[0]
+ assert errors[0]["message"] == AttributeInputErrors.DUPLICATED_VALUES[0]
MUTATION_UPDATE_PRODUCT_BY_EXTERNAL_REFERENCE = """
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index 9294ad1474..50ca9b4090 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -2117,7 +2117,11 @@ def test_update_product_variant_change_attribute_values_ordering(
@pytest.mark.parametrize(
("values", "message", "code"),
[
- (["one", "two"], "Attribute must take only one value.", "INVALID"),
+ (
+ ["one", "two"],
+ "Attribute must take only one value.",
+ "INVALID",
+ ),
([" "], "Attribute values cannot be blank.", "REQUIRED"),
],
)