Skip to content

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

Add attributes validation while creating/updating a product's variant (#6269)

Grzegorz Derdake654bdfd674a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b42f84ee1..d02bbc92d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix attribute filtering by categories and collections - #6214 by @fowczarek
- Fix is_visible when publication_date==today - #6225 by @korycins
- Fix filtering products by multiple attributes - #6215 by @GrzegorzDerdak
+- Add attributes validation while creating/updating a product's variant - #6269 by @GrzegorzDerdak
## 2.10.2
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index 0506d643e8..d825383317 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -130,30 +130,47 @@ def test_total_count_query(api_client, product):
def test_mutation_positive_decimal_input(
- staff_api_client, variant, stock, permission_manage_products
+ staff_api_client, variant, size_attribute, stock, permission_manage_products
):
query = """
mutation PositiveDecimalInput(
- $id: ID!, $cost: PositiveDecimal, $price: PositiveDecimal
+ $id: ID!,
+ $cost: PositiveDecimal,
+ $price: PositiveDecimal,
+ $attributes: [AttributeValueInput],
) {
- productVariantUpdate(id: $id, input: {costPrice: $cost, price: $price}) {
+ productVariantUpdate(
+ id: $id,
+ input: {
+ costPrice: $cost,
+ price: $price,
+ attributes: $attributes
+ }
+ ) {
errors {
field
message
}
productVariant {
- costPrice{
+ costPrice {
amount
}
}
}
}
"""
+
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant.id),
"price": 15,
"cost": 12.12,
"quantity": 17,
+ "attributes": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", size_attribute.pk),
+ "values": ["S"],
+ }
+ ],
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
@@ -164,13 +181,23 @@ def test_mutation_positive_decimal_input(
def test_mutation_positive_decimal_input_without_arguments(
- staff_api_client, variant, permission_manage_products
+ staff_api_client, variant, size_attribute, permission_manage_products
):
query = """
mutation ProductVariantUpdate(
- $id: ID!, $price: PositiveDecimal, $costPrice: PositiveDecimal
+ $id: ID!,
+ $price: PositiveDecimal,
+ $costPrice: PositiveDecimal,
+ $attributes: [AttributeValueInput],
) {
- productVariantUpdate(id: $id, input: {costPrice: $costPrice, price: $price}) {
+ productVariantUpdate(
+ id: $id,
+ input: {
+ costPrice: $costPrice,
+ price: $price,
+ attributes: $attributes,
+ }
+ ) {
errors {
field
message
@@ -187,6 +214,12 @@ def test_mutation_positive_decimal_input_without_arguments(
"id": graphene.Node.to_global_id("ProductVariant", variant.id),
"cost": 12.12,
"price": 15,
+ "attributes": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", size_attribute.pk),
+ "values": ["S"],
+ }
+ ],
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index a132f3453d..1362fbfab5 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1206,6 +1206,11 @@ class ProductVariantCreate(ModelMutation):
def clean_attributes(
cls, attributes: dict, product_type: models.ProductType
) -> T_INPUT_MAP:
+ if not attributes:
+ raise ValidationError(
+ "All attributes must take a value.", ProductErrorCode.REQUIRED.value
+ )
+
attributes_qs = product_type.variant_attributes
attributes = AttributeAssignmentMixin.clean_input(
attributes, attributes_qs, is_variant=True
@@ -1276,36 +1281,32 @@ class ProductVariantCreate(ModelMutation):
if stocks:
cls.check_for_duplicates_in_stocks(stocks)
+ if instance.product_id is not None:
+ # If the variant is getting updated,
+ # simply retrieve the associated product type
+ product_type = instance.product.product_type
+ used_attribute_values = get_used_variants_attribute_values(instance.product)
+ else:
+ # If the variant is getting created, no product type is associated yet,
+ # retrieve it from the required "product" input field
+ product_type = cleaned_input["product"].product_type
+ used_attribute_values = get_used_variants_attribute_values(
+ cleaned_input["product"]
+ )
+
# Attributes are provided as list of `AttributeValueInput` objects.
# We need to transform them into the format they're stored in the
# `Product` model, which is HStore field that maps attribute's PK to
# the value's PK.
- attributes = cleaned_input.get("attributes")
- if attributes:
- if instance.product_id is not None:
- # If the variant is getting updated,
- # simply retrieve the associated product type
- product_type = instance.product.product_type
- used_attribute_values = get_used_variants_attribute_values(
- instance.product
- )
- else:
- # If the variant is getting created, no product type is associated yet,
- # retrieve it from the required "product" input field
- product_type = cleaned_input["product"].product_type
- used_attribute_values = get_used_variants_attribute_values(
- cleaned_input["product"]
- )
+ attributes = cleaned_input.get("attributes", [])
+ try:
+ cls.validate_duplicated_attribute_values(
+ attributes, used_attribute_values, instance
+ )
+ cleaned_input["attributes"] = cls.clean_attributes(attributes, product_type)
+ except ValidationError as exc:
+ raise ValidationError({"attributes": exc})
- try:
- cls.validate_duplicated_attribute_values(
- attributes, used_attribute_values, instance
- )
- cleaned_input["attributes"] = cls.clean_attributes(
- attributes, product_type
- )
- except ValidationError as exc:
- raise ValidationError({"attributes": exc})
return cleaned_input
@classmethod
diff --git a/saleor/graphql/product/tests/test_product_minimal_variant_price.py b/saleor/graphql/product/tests/test_product_minimal_variant_price.py
index 916bb9d5c1..ebe7bf9590 100644
--- a/saleor/graphql/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/graphql/product/tests/test_product_minimal_variant_price.py
@@ -78,17 +78,20 @@ def test_product_variant_update_updates_minimal_variant_price(
mock_update_product_minimal_variant_price_task,
staff_api_client,
product,
+ size_attribute,
permission_manage_products,
):
query = """
mutation ProductVariantUpdate(
$id: ID!,
$price: PositiveDecimal,
+ $attributes: [AttributeValueInput],
) {
productVariantUpdate(
id: $id,
input: {
price: $price,
+ attributes: $attributes
}
) {
productVariant {
@@ -103,8 +106,13 @@ def test_product_variant_update_updates_minimal_variant_price(
"""
variant = product.variants.first()
variant_id = to_global_id("ProductVariant", variant.pk)
+ attribute_id = to_global_id("Attribute", size_attribute.pk)
price = "1.99"
- variables = {"id": variant_id, "price": price}
+ variables = {
+ "id": variant_id,
+ "price": price,
+ "attributes": [{"id": attribute_id, "values": ["S"]}],
+ }
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 98abc8c9f0..601d904067 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -262,6 +262,33 @@ def test_create_product_variant_with_negative_weight(
assert error["code"] == ProductErrorCode.INVALID.name
+def test_create_product_variant_without_attributes(
+ staff_api_client, product, permission_manage_products
+):
+ # given
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "productId": product_id,
+ "sku": "test-sku",
+ "price": 0,
+ "attributes": [],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantCreate"]
+ error = data["productErrors"][0]
+
+ assert error["field"] == "attributes"
+ assert error["code"] == ProductErrorCode.REQUIRED.name
+
+
def test_create_product_variant_not_all_attributes(
staff_api_client, product, product_type, color_attribute, permission_manage_products
):
@@ -514,7 +541,11 @@ def test_create_product_variant_update_with_new_attributes(
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_update_product_variant(
- updated_webhook_mock, staff_api_client, product, permission_manage_products
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ size_attribute,
+ permission_manage_products,
):
query = """
mutation updateVariant (
@@ -522,14 +553,17 @@ def test_update_product_variant(
$sku: String!,
$price: PositiveDecimal,
$costPrice: PositiveDecimal,
- $trackInventory: Boolean!) {
+ $trackInventory: Boolean!,
+ $attributes: [AttributeValueInput],
+ ) {
productVariantUpdate(
id: $id,
input: {
sku: $sku,
price: $price,
costPrice: $costPrice,
- trackInventory: $trackInventory
+ trackInventory: $trackInventory,
+ attributes: $attributes,
}) {
productVariant {
name
@@ -549,6 +583,7 @@ def test_update_product_variant(
"""
variant = product.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
sku = "test sku"
cost_price = 3.3
price = 15
@@ -559,6 +594,7 @@ def test_update_product_variant(
"price": price,
"costPrice": cost_price,
"trackInventory": True,
+ "attributes": [{"id": attribute_id, "values": ["S"]}],
}
response = staff_api_client.post_graphql(
@@ -616,7 +652,7 @@ def test_update_product_variant_with_negative_weight(
def test_update_product_variant_unset_cost_price(
- staff_api_client, product, permission_manage_products
+ staff_api_client, product, size_attribute, permission_manage_products
):
"""Ensure setting nullable amounts to null is properly handled
(setting the amount to none) and doesn't override the currency.
@@ -626,13 +662,16 @@ def test_update_product_variant_unset_cost_price(
$id: ID!,
$sku: String!,
$price: PositiveDecimal,
- $costPrice: PositiveDecimal) {
+ $costPrice: PositiveDecimal,
+ $attributes: [AttributeValueInput],
+ ) {
productVariantUpdate(
id: $id,
input: {
sku: $sku,
price: $price,
costPrice: $costPrice,
+ attributes: $attributes,
}) {
productVariant {
name
@@ -649,9 +688,16 @@ def test_update_product_variant_unset_cost_price(
"""
variant = product.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
sku = variant.sku
- variables = {"id": variant_id, "sku": sku, "costPrice": None, "price": 15}
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "costPrice": None,
+ "price": 15,
+ "attributes": [{"id": attribute_id, "values": ["S"]}],
+ }
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
@@ -667,18 +713,24 @@ def test_update_product_variant_unset_cost_price(
def test_update_product_variant_invalid_price(
- staff_api_client, product, permission_manage_products
+ staff_api_client, product, size_attribute, permission_manage_products
):
query = """
mutation updateVariant(
$id: ID!
$sku: String!
$price: PositiveDecimal
- $costPrice: PositiveDecimal
+ $costPrice: PositiveDecimal,
+ $attributes: [AttributeValueInput],
) {
productVariantUpdate(
id: $id
- input: { sku: $sku, price: $price, costPrice: $costPrice }
+ input: {
+ sku: $sku,
+ price: $price,
+ costPrice: $costPrice,
+ attributes: $attributes,
+ }
) {
productErrors {
field
@@ -690,12 +742,14 @@ def test_update_product_variant_invalid_price(
"""
variant = product.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
variables = {
"id": variant_id,
"sku": variant.sku,
"costPrice": 15,
"price": 1234567891234,
+ "attributes": [{"id": attribute_id, "values": ["S"]}],
}
response = staff_api_client.post_graphql(
@@ -1002,11 +1056,15 @@ def test_update_product_variant_requires_values(
def test_update_product_variant_with_price_does_not_raise_price_validation_error(
- staff_api_client, variant, permission_manage_products
+ staff_api_client, variant, size_attribute, permission_manage_products
):
mutation = """
- mutation updateVariant ($id: ID!) {
- productVariantUpdate(id: $id, input: {}) {
+ mutation updateVariant ($id: ID!, $attributes: [AttributeValueInput]) {
+ productVariantUpdate(
+ id: $id,
+ input: {
+ attributes: $attributes,
+ }) {
productVariant {
id
price {
@@ -1020,11 +1078,15 @@ def test_update_product_variant_with_price_does_not_raise_price_validation_error
}
}
"""
- # given a product variant
+ # given a product variant and an attribute
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
# when running the updateVariant mutation without price input field
- variables = {"id": variant_id}
+ variables = {
+ "id": variant_id,
+ "attributes": [{"id": attribute_id, "values": ["S"]}],
+ }
response = staff_api_client.post_graphql(
mutation, variables, permissions=[permission_manage_products]
)