Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add validation for duplicated attribute valuse in single mutation
fowczarekd0b63970f33c
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex bf194af8cf..147ed1efd7 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -193,24 +193,6 @@ class ProductVariantBulkCreate(BaseMutation):cls.add_indexes_to_errors(index, exc, errors)return instances- @classmethod- def validate_duplicated_attribute_values(- cls, variant_data, index, used_attribute_values, errors- ):- attribute_values = defaultdict(list)- for attribute in variant_data.attributes:- attribute_values[attribute.id].extend(attribute.values)- if attribute_values in used_attribute_values:- errors["attributes"].append(- ValidationError(- "Duplicated attribute values for product variant.",- ProductErrorCode.UNIQUE,- params={"index": index},- )- )- else:- used_attribute_values.append(attribute_values)-@classmethoddef validate_duplicated_sku(cls, sku, index, sku_list, errors):if sku in sku_list:@@ -227,9 +209,14 @@ class ProductVariantBulkCreate(BaseMutation):sku_list = []used_attribute_values = get_used_attribute_values(product)for index, variant_data in enumerate(variants):- cls.validate_duplicated_attribute_values(- variant_data, index, used_attribute_values, errors- )+ try:+ ProductVariantCreate.validate_duplicated_attribute_values(+ variant_data.attributes, used_attribute_values+ )+ except ValidationError as exc:+ errors["attributes"].append(+ ValidationError(exc.message, exc.code, params={"index": index})+ )cleaned_input = Nonetry:diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 110e1bb500..0606f405bc 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom typing import Iterable, List, Tuple, Unionimport graphene@@ -49,6 +50,7 @@ from ..types import (ProductVariant,)from ..utils import (+ get_used_attribute_values,validate_attribute_input_for_product,validate_attribute_input_for_variant,)@@ -1040,6 +1042,19 @@ class ProductVariantCreate(ModelMutation):)return attributes+ @classmethod+ def validate_duplicated_attribute_values(cls, attributes, used_attribute_values):+ attribute_values = defaultdict(list)+ for attribute in attributes:+ attribute_values[attribute.id].extend(attribute.values)+ if attribute_values in used_attribute_values:+ raise ValidationError(+ "Duplicated attribute values for product variant.",+ ProductErrorCode.UNIQUE,+ )+ else:+ used_attribute_values.append(attribute_values)+@classmethoddef clean_input(cls, info, instance: models.ProductVariant, data: dict):cleaned_input = super().clean_input(info, instance, data)@@ -1060,12 +1075,19 @@ class ProductVariantCreate(ModelMutation):# If the variant is getting updated,# simply retrieve the associated product typeproduct_type = instance.product.product_type+ used_attribute_values = get_used_attribute_values(instance.product)else:# If the variant is getting created, no product type is associated yet,# retrieve it from the required "product" input fieldproduct_type = cleaned_input["product"].product_type+ used_attribute_values = get_used_attribute_values(+ cleaned_input["product"]+ )try:+ cls.validate_duplicated_attribute_values(+ attributes, used_attribute_values+ )cleaned_input["attributes"] = cls.clean_attributes(attributes, product_type)diff --git a/tests/api/test_variant.py b/tests/api/test_variant.pyindex 468bebb75a..9155fef081 100644--- a/tests/api/test_variant.py+++ b/tests/api/test_variant.py@@ -208,6 +208,60 @@ def test_create_product_variant_not_all_attributes(assert not product.variants.filter(sku=sku).exists()+def test_create_product_variant_duplicated_attributes(+ staff_api_client, product_with_two_variants, permission_manage_products+):+ query = """+ mutation createVariant (+ $productId: ID!,+ $sku: String!,+ $attributes: [AttributeValueInput]!+ ) {+ productVariantCreate(+ input: {+ product: $productId,+ sku: $sku,+ attributes: $attributes+ }) {+ productErrors {+ field+ code+ message+ }+ }+ }+ """+ product = product_with_two_variants+ product_variant = product.variants.first()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ first_attribute = product_variant.attributes.first().attribute+ first_attribute_id = graphene.Node.to_global_id("Attribute", first_attribute.id)+ first_attribute_value = product_variant.attributes.first().values.first()+ second_attribute = product_variant.attributes.last().attribute+ second_attribute_id = graphene.Node.to_global_id("Attribute", second_attribute.id)+ second_attribute_value = product_variant.attributes.last().values.first()+ sku = str(uuid4())[:12]+ variables = {+ "productId": product_id,+ "sku": sku,+ "attributes": [+ {"id": first_attribute_id, "values": [first_attribute_value.slug]},+ {"id": second_attribute_id, "values": [second_attribute_value.slug]},+ ],+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ assert content["data"]["productVariantCreate"]["productErrors"]+ assert content["data"]["productVariantCreate"]["productErrors"][0] == {+ "field": "attributes",+ "code": ProductErrorCode.UNIQUE.name,+ "message": ANY,+ }+ assert not product.variants.filter(sku=sku).exists()++def test_create_product_variant_update_with_new_attributes(staff_api_client, permission_manage_products, product, size_attribute):