Skip to content

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

Add attributes to ProductError

IKarbowiakab6c29ba265d
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 693aef481f..8c346eb41c 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -155,6 +155,11 @@ class PermissionGroupError(Error):
class ProductError(Error):
code = ProductErrorCode(description="The error code.", required=True)
+ attributes = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of attributes IDs which causes the error.",
+ required=False,
+ )
class ProductAttributeError(ProductError):
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index f540852754..e617ff0a6c 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -57,8 +57,8 @@ from ..utils import (
create_stocks,
get_used_attribute_values_for_variant,
get_used_variants_attribute_values,
- validate_attribute_input_for_product,
- validate_attribute_input_for_variant,
+ validate_attributes_input_for_product,
+ validate_attributes_input_for_variant,
)
from .common import ReorderInput
@@ -684,21 +684,29 @@ class AttributeAssignmentMixin:
- ensure all required attributes are passed
- ensure the values are correct for a product
"""
- supplied_attribute_pk = []
- for attribute, values in cleaned_input:
- validate_attribute_input_for_product(attribute, values)
- supplied_attribute_pk.append(attribute.pk)
+ errors = validate_attributes_input_for_product(cleaned_input,)
+
+ supplied_attribute_pk = [attribute.pk for attribute, _ in cleaned_input]
# Asserts all required attributes are supplied
- missing_required_filter = Q(value_required=True) & ~Q(
- pk__in=supplied_attribute_pk
+ missing_required_attributes = qs.filter(
+ Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)
)
- if qs.filter(missing_required_filter).exists():
- raise ValidationError(
+ 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=ProductErrorCode.REQUIRED.value,
+ params={"attributes": ids},
)
+ errors.append(error)
+
+ if errors:
+ raise ValidationError(errors)
@classmethod
def _check_input_for_variant(cls, cleaned_input: T_INPUT_MAP, qs: QuerySet):
@@ -714,8 +722,9 @@ class AttributeAssignmentMixin:
"All attributes must take a value", code=ProductErrorCode.REQUIRED.value
)
- for attribute, values in cleaned_input:
- validate_attribute_input_for_variant(attribute, values)
+ errors = validate_attributes_input_for_variant(cleaned_input)
+ if errors:
+ raise ValidationError(errors)
@classmethod
def _validate_input(
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 5261c6dec2..dee8faf42e 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -1308,10 +1308,7 @@ CREATE_PRODUCT_MUTATION = """
field
code
message
- }
- errors {
- message
- field
+ attributes
}
}
}
@@ -1384,7 +1381,7 @@ def test_create_product(
)
content = get_graphql_content(response)
data = content["data"]["productCreate"]
- assert data["errors"] == []
+ assert data["productErrors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == product_slug
assert data["product"]["descriptionJson"] == description_json
@@ -1621,7 +1618,7 @@ def test_create_product_no_slug_in_input(
)
content = get_graphql_content(response)
data = content["data"]["productCreate"]
- assert data["errors"] == []
+ assert data["productErrors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == "test-name"
assert data["product"]["isPublished"] == product_is_published
@@ -1671,7 +1668,7 @@ def test_create_product_no_category_id(
)
content = get_graphql_content(response)
data = content["data"]["productCreate"]
- assert data["errors"] == []
+ assert data["productErrors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == input_slug
assert data["product"]["isPublished"] == product_is_published
@@ -1820,6 +1817,104 @@ def test_create_product_with_unicode_in_slug_and_name(
assert data["product"]["slug"] == slug
+def test_create_product_invalid_product_attributes(
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ weight_attribute,
+ description_json,
+ permission_manage_products,
+ settings,
+ monkeypatch,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ description_json = json.dumps(description_json)
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+ product_is_published = True
+ product_charge_taxes = True
+ visible_in_listings = True
+ product_tax_rate = "STANDARD"
+ product_price = "22.33"
+
+ # Mock tax interface with fake response from tax gateway
+ monkeypatch.setattr(
+ PluginsManager,
+ "get_tax_code_from_object_meta",
+ lambda self, x: TaxType(description="", code=product_tax_rate),
+ )
+
+ # Default attribute defined in product_type fixture
+ color_attr = product_type.product_attributes.get(name="Color")
+ color_value_slug = color_attr.values.first().slug
+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attr.id)
+
+ # Add second attribute
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ # Add third attribute
+ product_type.product_attributes.add(weight_attribute)
+ weight_attr_id = graphene.Node.to_global_id("Attribute", weight_attribute.id)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "descriptionJson": description_json,
+ "isPublished": product_is_published,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "basePrice": product_price,
+ "attributes": [
+ {"id": color_attr_id, "values": [" "]},
+ {"id": weight_attr_id, "values": [None]},
+ {
+ "id": size_attr_id,
+ "values": [non_existent_attr_value, color_value_slug],
+ },
+ ],
+ "visibleInListings": visible_in_listings,
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ errors = data["productErrors"]
+
+ assert not data["product"]
+ assert len(errors) == 2
+
+ expected_errors = [
+ {
+ "attributes": [color_attr_id, weight_attr_id],
+ "code": ProductErrorCode.REQUIRED.name,
+ "field": "attributes",
+ "message": ANY,
+ },
+ {
+ "attributes": [size_attr_id],
+ "code": ProductErrorCode.INVALID.name,
+ "field": "attributes",
+ "message": ANY,
+ },
+ ]
+ for error in expected_errors:
+ assert error in errors
+
+
QUERY_CREATE_PRODUCT_WITHOUT_VARIANTS = """
mutation createProduct(
$productTypeId: ID!,
@@ -2484,6 +2579,7 @@ SET_ATTRIBUTES_TO_PRODUCT_QUERY = """
message
field
code
+ attributes
}
}
}
@@ -2516,7 +2612,12 @@ def test_update_product_can_only_assign_multiple_values_to_valid_input_types(
staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
)["data"]["productUpdate"]
assert data["productErrors"] == [
- {"field": "attributes", "code": ProductErrorCode.INVALID.name, "message": ANY}
+ {
+ "field": "attributes",
+ "code": ProductErrorCode.INVALID.name,
+ "message": ANY,
+ "attributes": [color_attribute_id],
+ }
]
# Try to assign multiple values from a valid attribute
@@ -2571,6 +2672,9 @@ def test_update_product_without_supplying_required_product_attribute(
name="Required One", slug="required-one", value_required=True
)
product_type.product_attributes.add(required_attribute)
+ required_attribute_id = graphene.Node.to_global_id(
+ "Attribute", required_attribute.id
+ )
# Try to assign multiple values from an attribute that does not support such things
variables = {
@@ -2582,7 +2686,12 @@ def test_update_product_without_supplying_required_product_attribute(
staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
)["data"]["productUpdate"]
assert data["productErrors"] == [
- {"field": "attributes", "code": ProductErrorCode.REQUIRED.name, "message": ANY}
+ {
+ "field": "attributes",
+ "code": ProductErrorCode.REQUIRED.name,
+ "message": ANY,
+ "attributes": [required_attribute_id],
+ }
]
@@ -2609,7 +2718,12 @@ def test_update_product_with_non_existing_attribute(
staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
)["data"]["productUpdate"]
assert data["productErrors"] == [
- {"field": "attributes", "code": ProductErrorCode.NOT_FOUND.name, "message": ANY}
+ {
+ "field": "attributes",
+ "code": ProductErrorCode.NOT_FOUND.name,
+ "message": ANY,
+ "attributes": None,
+ }
]
@@ -2630,7 +2744,12 @@ def test_update_product_with_no_attribute_slug_or_id(
staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
)["data"]["productUpdate"]
assert data["productErrors"] == [
- {"field": "attributes", "code": ProductErrorCode.REQUIRED.name, "message": ANY}
+ {
+ "field": "attributes",
+ "code": ProductErrorCode.REQUIRED.name,
+ "message": ANY,
+ "attributes": None,
+ }
]
diff --git a/saleor/graphql/product/tests/test_utils.py b/saleor/graphql/product/tests/test_utils.py
new file mode 100644
index 0000000000..f8ed3220c9
--- /dev/null
+++ b/saleor/graphql/product/tests/test_utils.py
@@ -0,0 +1,251 @@
+import graphene
+
+from ....product import AttributeInputType
+from ....product.error_codes import ProductErrorCode
+from ..utils import (
+ validate_attributes_input_for_product,
+ validate_attributes_input_for_variant,
+)
+
+
+def test_validate_attributes_input_for_product(weight_attribute, color_attribute):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]
+
+ # when
+ errors = validate_attributes_input_for_product(input_data)
+
+ # then
+ assert not errors
+
+
+def test_validate_attributes_input_for_product_no_values_given(
+ weight_attribute, color_attribute
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, []), (color_attribute, [])]
+
+ # when
+ errors = validate_attributes_input_for_product(input_data)
+
+ # then
+ assert len(errors) == 1
+ error = errors[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_product_too_many_values_given(
+ weight_attribute, color_attribute
+):
+ # 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"])
+
+ input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]
+
+ # when
+ errors = validate_attributes_input_for_product(input_data)
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert error.params["attributes"] == [
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ ]
+
+
+def test_validate_attributes_input_for_product_empty_values_given(
+ weight_attribute, color_attribute
+):
+ # 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"])
+
+ input_data = [(weight_attribute, ["a", None]), (color_attribute, [" "])]
+
+ # when
+ errors = validate_attributes_input_for_product(input_data)
+
+ # then
+ assert len(errors) == 1
+ error = errors[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_product_multiply_errors(
+ weight_attribute, color_attribute
+):
+ # 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"])
+
+ input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]
+
+ # when
+ errors = validate_attributes_input_for_product(input_data)
+
+ # then
+ assert len(errors) == 2
+ assert {error.code for error in errors} == {
+ ProductErrorCode.INVALID.value,
+ ProductErrorCode.REQUIRED.value,
+ }
+ assert {attr for error in errors for attr in error.params["attributes"]} == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [weight_attribute, color_attribute]
+ }
+
+
+def test_validate_attributes_input_for_variant(weight_attribute, color_attribute):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]
+
+ # when
+ errors = validate_attributes_input_for_variant(input_data)
+
+ # then
+ assert not errors
+
+
+def test_validate_attributes_input_for_variant_no_values_given(
+ weight_attribute, color_attribute
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, []), (color_attribute, [])]
+
+ # when
+ errors = validate_attributes_input_for_variant(input_data)
+
+ # then
+ assert len(errors) == 1
+ error = errors[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_variant_too_many_values_given(
+ weight_attribute, color_attribute
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]
+
+ # when
+ errors = validate_attributes_input_for_variant(input_data)
+
+ # then
+ assert len(errors) == 1
+ error = errors[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]
+ }
+
+
+def test_validate_attributes_input_for_variant_empty_values_given(
+ weight_attribute, color_attribute
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required", "input_type"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ input_data = [(weight_attribute, [None]), (color_attribute, [" "])]
+
+ # when
+ errors = validate_attributes_input_for_variant(input_data)
+
+ # then
+ assert len(errors) == 1
+ error = errors[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_variant_multiply_errors(
+ weight_attribute, color_attribute
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required", "input_type"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]
+
+ # when
+ errors = validate_attributes_input_for_variant(input_data)
+
+ # then
+ assert len(errors) == 2
+ assert {error.code for error in errors} == {
+ ProductErrorCode.INVALID.value,
+ ProductErrorCode.REQUIRED.value,
+ }
+ assert {attr for error in errors for attr in error.params["attributes"]} == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [weight_attribute, color_attribute]
+ }
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index a8b088e69a..0ec24e773f 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -91,25 +91,16 @@ def test_fetch_variant(
assert data["weight"]["unit"] == WeightUnitsEnum.G.name
-@patch("saleor.plugins.manager.PluginsManager.product_updated")
-def test_create_variant(
- updated_webhook_mock,
- staff_api_client,
- product,
- product_type,
- permission_manage_products,
- warehouse,
-):
- query = """
- mutation createVariant (
+CREATE_VARIANT_MUTATION = """
+ mutation createVariant (
$productId: ID!,
- $sku: String!,
+ $sku: String,
$stocks: [StockInput!],
$price: PositiveDecimal,
$costPrice: PositiveDecimal,
$attributes: [AttributeValueInput]!,
$weight: WeightScalar,
- $trackInventory: Boolean!) {
+ $trackInventory: Boolean) {
productVariantCreate(
input: {
product: $productId,
@@ -124,6 +115,8 @@ def test_create_variant(
productErrors {
field
message
+ attributes
+ code
}
productVariant {
name
@@ -160,7 +153,19 @@ def test_create_variant(
}
}
- """
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_create_variant(
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+ warehouse,
+):
+ query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
price = 1.32
@@ -211,20 +216,7 @@ def test_create_variant(
def test_create_product_variant_without_price(
staff_api_client, product, product_type, permission_manage_products
):
- query = """
- mutation createVariant ($productId: ID!, $attributes: [AttributeValueInput]!) {
- productVariantCreate(
- input: {
- product: $productId,
- attributes: $attributes
- }) {
- productErrors {
- field
- code
- }
- }
- }
- """
+ query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
attr_id = graphene.Node.to_global_id(
"Attribute", product_type.variant_attributes.first().pk
@@ -247,25 +239,7 @@ def test_create_product_variant_without_price(
def test_create_product_variant_with_negative_weight(
staff_api_client, product, product_type, permission_manage_products
):
- query = """
- mutation createVariant (
- $productId: ID!,
- $attributes: [AttributeValueInput]!,
- $weight: WeightScalar) {
- productVariantCreate(
- input: {
- product: $productId,
- attributes: $attributes,
- weight: $weight
- }) {
- productErrors {
- field
- code
- message
- }
- }
- }
- """
+ query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
variant_id = graphene.Node.to_global_id(
@@ -291,28 +265,7 @@ def test_create_product_variant_with_negative_weight(
def test_create_product_variant_not_all_attributes(
staff_api_client, product, product_type, color_attribute, permission_manage_products
):
- query = """
- mutation createVariant (
- $productId: ID!,
- $price: PositiveDecimal,
- $sku: String!,
- $attributes: [AttributeValueInput]!) {
- productVariantCreate(
- input: {
- product: $productId,
- price: $price,
- sku: $sku,
- attributes: $attributes
- }) {
- productErrors {
- field
- code
- message
- }
- }
- }
-
- """
+ query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
variant_id = graphene.Node.to_global_id(
@@ -336,6 +289,7 @@ def test_create_product_variant_not_all_attributes(
"field": "attributes",
"code": ProductErrorCode.REQUIRED.name,
"message": ANY,
+ "attributes": None,
}
assert not product.variants.filter(sku=sku).exists()
@@ -343,27 +297,7 @@ def test_create_product_variant_not_all_attributes(
def test_create_product_variant_too_many_places_in_cost_price(
staff_api_client, product, product_type, permission_manage_products
):
- query = """
- mutation createVariant (
- $productId: ID!,
- $attributes: [AttributeValueInput]!,
- $weight: WeightScalar,
- $costPrice: PositiveDecimal) {
- productVariantCreate(
- input: {
- product: $productId,
- attributes: $attributes,
- weight: $weight,
- costPrice: $costPrice,
- }) {
- productErrors {
- field
- code
- message
- }
- }
- }
- """
+ query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
variant_id = graphene.Node.to_global_id(
@@ -394,28 +328,7 @@ def test_create_product_variant_duplicated_attributes(
size_attribute,
permission_manage_products,
):
- query = """
- mutation createVariant (
- $productId: ID!,
- $price: PositiveDecimal,
- $sku: String!,
- $attributes: [AttributeValueInput]!
- ) {
- productVariantCreate(
- input: {
- product: $productId,
- price: $price,
- sku: $sku,
- attributes: $attributes
- }) {
- productErrors {
- field
- code
- message
- }
- }
- }
- """
+ query = CREATE_VARIANT_MUTATION
product = product_with_variant_with_two_attributes
product_id = graphene.Node.to_global_id("Product", product.pk)
color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
@@ -439,10 +352,91 @@ def test_create_product_variant_duplicated_attributes(
"field": "attributes",
"code": ProductErrorCode.DUPLICATED_INPUT_ITEM.name,
"message": ANY,
+ "attributes": None,
}
assert not product.variants.filter(sku=sku).exists()
+def test_create_variant_invalid_variant_attributes(
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+ warehouse,
+ color_attribute,
+ weight_attribute,
+):
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+ price = 1.32
+ cost_price = 3.22
+ weight = 10.22
+
+ # Default attribute defined in product_type fixture
+ size_attribute = product_type.variant_attributes.get(name="Size")
+ size_value_slug = size_attribute.values.first().slug
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+
+ # Add second attribute
+ product_type.variant_attributes.add(color_attribute)
+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ # Add third attribute
+ product_type.variant_attributes.add(weight_attribute)
+ weight_attr_id = graphene.Node.to_global_id("Attribute", weight_attribute.id)
+
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "productId": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "costPrice": cost_price,
+ "price": price,
+ "weight": weight,
+ "attributes": [
+ {"id": color_attr_id, "values": [" "]},
+ {"id": weight_attr_id, "values": [None]},
+ {"id": size_attr_id, "values": [non_existent_attr_value, size_value_slug]},
+ ],
+ "trackInventory": True,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+
+ data = content["data"]["productVariantCreate"]
+ errors = data["productErrors"]
+
+ assert not data["productVariant"]
+ assert len(errors) == 2
+
+ expected_errors = [
+ {
+ "attributes": [color_attr_id, weight_attr_id],
+ "code": ProductErrorCode.REQUIRED.name,
+ "field": "attributes",
+ "message": ANY,
+ },
+ {
+ "attributes": [size_attr_id],
+ "code": ProductErrorCode.INVALID.name,
+ "field": "attributes",
+ "message": ANY,
+ },
+ ]
+ for error in expected_errors:
+ assert error in errors
+
+
def test_create_product_variant_update_with_new_attributes(
staff_api_client, permission_manage_products, product, size_attribute
):
@@ -918,7 +912,7 @@ def test_update_product_variant_with_duplicated_attribute(
@pytest.mark.parametrize(
"values, message",
(
- ([], "size expects a value but none were given"),
+ ([], "Attribute expects a value but none were given"),
(["one", "two"], "A variant attribute cannot take more than one value"),
([" "], "Attribute values cannot be blank"),
([None], "Attribute values cannot be blank"),
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 992c23fe4e..b2366d7f2c 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import TYPE_CHECKING, Dict, List
+from typing import TYPE_CHECKING, Dict, List, Tuple
import graphene
from django.core.exceptions import ValidationError
@@ -15,45 +15,84 @@ if TYPE_CHECKING:
from ...product.models import Attribute, ProductVariant
-def validate_attribute_input_for_product(instance: "Attribute", values: List[str]):
- if not values:
- if not instance.value_required:
- return
- raise ValidationError(
- f"{instance.slug} expects a value but none were given",
- code=ProductErrorCode.REQUIRED.value,
- )
-
- if instance.input_type != AttributeInputType.MULTISELECT and len(values) != 1:
- raise ValidationError(
- f"A {instance.input_type} attribute must take only one value",
- code=ProductErrorCode.INVALID.value,
- )
+def validate_attributes_input_for_product(
+ input_data: List[Tuple["Attribute", List[str]]],
+):
+ error_no_value_given = ValidationError(
+ "Attribute expects a value but none were given",
+ code=ProductErrorCode.REQUIRED.value,
+ )
+ error_dropdown_get_more_than_one_value = ValidationError(
+ "Attribute attribute must take only one value",
+ code=ProductErrorCode.INVALID.value,
+ )
+ error_blank_value = ValidationError(
+ "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value,
+ )
- for value in values:
- if not value.strip():
- raise ValidationError(
- "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value
+ attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)
+ for attribute, values in input_data:
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ if not values:
+ if attribute.value_required:
+ attribute_errors[error_no_value_given].append(attribute_id)
+ continue
+
+ if attribute.input_type != AttributeInputType.MULTISELECT and len(values) != 1:
+ attribute_errors[error_dropdown_get_more_than_one_value].append(
+ attribute_id
)
+ continue
+ for value in values:
+ if value is None or not value.strip():
+ attribute_errors[error_blank_value].append(attribute_id)
+ continue
-def validate_attribute_input_for_variant(instance: "Attribute", values: List[str]):
- if not values:
- raise ValidationError(
- f"{instance.slug} expects a value but none were given",
- code=ProductErrorCode.REQUIRED.value,
- )
+ return prepare_error_list_from_error_attribute_mapping(attribute_errors)
- if len(values) != 1:
- raise ValidationError(
- "A variant attribute cannot take more than one value",
- code=ProductErrorCode.INVALID.value,
- )
- if values[0] is None or not values[0].strip():
- raise ValidationError(
- "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value
- )
+def validate_attributes_input_for_variant(
+ input_data: List[Tuple["Attribute", List[str]]]
+):
+ error_no_value_given = ValidationError(
+ "Attribute expects a value but none were given",
+ code=ProductErrorCode.REQUIRED.value,
+ )
+ error_more_than_one_value_given = ValidationError(
+ "A variant attribute cannot take more than one value",
+ code=ProductErrorCode.INVALID.value,
+ )
+ error_blank_value = ValidationError(
+ "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value,
+ )
+
+ attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)
+ for attribute, values in input_data:
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ if not values:
+ attribute_errors[error_no_value_given].append(attribute_id)
+ continue
+
+ if len(values) != 1:
+ attribute_errors[error_more_than_one_value_given].append(attribute_id)
+ continue
+
+ if values[0] is None or not values[0].strip():
+ attribute_errors[error_blank_value].append(attribute_id)
+
+ return prepare_error_list_from_error_attribute_mapping(attribute_errors)
+
+
+def prepare_error_list_from_error_attribute_mapping(
+ attribute_errors: Dict[ValidationError, List[str]]
+):
+ errors = []
+ for error, attributes in attribute_errors.items():
+ error.params = {"attributes": attributes}
+ errors.append(error)
+
+ return errors
def get_used_attribute_values_for_variant(variant):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 31cd137821..ba7d271f60 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -688,6 +688,7 @@ type BulkProductError {
field: String
message: String
code: ProductErrorCode!
+ attributes: [ID!]
index: Int
warehouses: [ID!]
}
@@ -696,6 +697,7 @@ type BulkStockError {
field: String
message: String
code: ProductErrorCode!
+ attributes: [ID!]
index: Int
}
@@ -3745,6 +3747,7 @@ type ProductError {
field: String
message: String
code: ProductErrorCode!
+ attributes: [ID!]
}
enum ProductErrorCode {