Skip to content

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

Add index to errors in bulk product variant create mutation

fowczareke7fa5e82abb9
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 926b5ac681..2b41cc06a7 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -100,7 +100,7 @@ class SetPassword(CreateToken):
def handle_typed_errors(cls, errors: list):
account_errors = [
AccountError(field=e.field, message=e.message, code=code)
- for e, code in errors
+ for e, code, _ in errors
]
return cls(errors=[e[0] for e in errors], account_errors=account_errors)
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index c13291264a..bb5cd9eb22 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -66,13 +66,18 @@ def validation_error_to_error_type(validation_error: ValidationError) -> list:
(
Error(field=field, message=err.messages[0]),
get_error_code_from_error(err),
+ err.params,
)
)
else:
# convert non-field errors
for err in validation_error.error_list:
err_list.append(
- (Error(message=err.messages[0]), get_error_code_from_error(err))
+ (
+ Error(message=err.messages[0]),
+ get_error_code_from_error(err),
+ err.params,
+ )
)
return err_list
@@ -295,7 +300,7 @@ class BaseMutation(graphene.Mutation):
):
typed_errors = [
cls._meta.error_type_class(field=e.field, message=e.message, code=code)
- for e, code in errors
+ for e, code, _ in errors
]
extra.update({cls._meta.error_type_field: typed_errors})
return cls(errors=[e[0] for e in errors], **extra)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index b6cecd8c6d..38084c9afd 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -58,6 +58,10 @@ class ProductError(Error):
code = ProductErrorCode(description="The error code.")
+class BulkProductError(ProductError):
+ index = graphene.Int(description="Input list index with error")
+
+
class ShopError(Error):
code = ShopErrorCode(description="The error code.")
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index b336db65b6..6612fb9cee 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -14,7 +14,7 @@ from ...core.mutations import (
ModelBulkDeleteMutation,
ModelMutation,
)
-from ...core.types.common import ProductError
+from ...core.types.common import BulkProductError, ProductError
from ..mutations.products import (
T_INPUT_MAP,
AttributeAssignmentMixin,
@@ -105,17 +105,22 @@ class ProductVariantBulkCreate(BaseMutation):
description="Returns how many objects were affected.",
)
product_variants = graphene.List(
- ProductVariant, required=True, default_value=[], description=""
+ ProductVariant,
+ required=True,
+ default_value=[],
+ description=(
+ "Represents a version of a products such as different size or color.",
+ ),
)
class Arguments:
variants = graphene.List(
ProductVariantBulkCreateInput,
required=True,
- description="Fields required to create a product variants.",
+ description="Fields required to create product variants.",
)
product_id = graphene.ID(
- description="Product ID of which type is the variant.",
+ description="ID of the product to create the variants for",
name="product",
required=True,
)
@@ -123,8 +128,8 @@ class ProductVariantBulkCreate(BaseMutation):
class Meta:
description = "Creates product variants."
permissions = ("product.manage_products",)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = BulkProductError
+ error_type_field = "bulk_product_errors"
@classmethod
def clean_attributes(
@@ -140,12 +145,16 @@ class ProductVariantBulkCreate(BaseMutation):
def validate_sku_duplication(cls, variants):
errors = []
sku_list = []
- for variant_data in variants:
+ for index, variant_data in enumerate(variants):
if not variant_data.sku:
continue
if variant_data.sku in sku_list:
errors.append(
- ValidationError("Duplicated SKU.", ProductErrorCode.UNIQUE)
+ ValidationError(
+ "Duplicated SKU.",
+ ProductErrorCode.UNIQUE,
+ params={"index": index},
+ )
)
sku_list.append(variant_data.sku)
return errors
@@ -202,7 +211,7 @@ class ProductVariantBulkCreate(BaseMutation):
instances = []
cleaned_inputs = []
errors = defaultdict(list)
- for variant_data in variants:
+ for index, variant_data in enumerate(variants):
try:
instance = models.ProductVariant()
variant_data["product_type"] = product.product_type
@@ -214,6 +223,11 @@ class ProductVariantBulkCreate(BaseMutation):
cleaned_inputs.append(cleaned_input)
except ValidationError as exc:
for key, value in exc.error_dict.items():
+ for e in value:
+ if e.params:
+ e.params["index"] = index
+ else:
+ e.params = {"index": index}
errors[key].extend(value)
return instances, cleaned_inputs, errors
@@ -233,6 +247,20 @@ class ProductVariantBulkCreate(BaseMutation):
count=len(instances), product_variants=instances
)
+ @classmethod
+ def handle_typed_errors(cls, errors: list, **extra):
+ typed_errors = [
+ cls._meta.error_type_class(
+ field=e.field,
+ message=e.message,
+ code=code,
+ index=params.get("index") if params else None,
+ )
+ for e, code, params in errors
+ ]
+ extra.update({cls._meta.error_type_field: typed_errors})
+ return cls(errors=[e[0] for e in errors], **extra)
+
class ProductVariantBulkDelete(ModelBulkDeleteMutation):
class Arguments:
diff --git a/tests/api/test_variant.py b/tests/api/test_variant.py
index 3acb61d86c..fa68cc8f00 100644
--- a/tests/api/test_variant.py
+++ b/tests/api/test_variant.py
@@ -630,10 +630,11 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
$variants: [ProductVariantBulkCreateInput]!, $productId: ID!
) {
productVariantBulkCreate(variants: $variants, product: $productId) {
- productErrors {
+ bulkProductErrors {
field
message
code
+ index
}
count
}
@@ -669,7 +670,7 @@ def test_product_variant_bulk_create_by_attribute_slug(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- assert not data["productErrors"]
+ assert not data["bulkProductErrors"]
assert data["count"] == 1
assert product_varinat_count + 1 == ProductVariant.objects.count()
assert attribut_value_count == size_attribute.values.count()
@@ -702,7 +703,7 @@ def test_product_variant_bulk_create_by_attribute_id(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- assert not data["productErrors"]
+ assert not data["bulkProductErrors"]
assert data["count"] == 1
assert product_varinat_count + 1 == ProductVariant.objects.count()
assert attribut_value_count == size_attribute.values.count()
@@ -735,7 +736,7 @@ def test_product_variant_bulk_create_with_new_attribute_value(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- assert not data["productErrors"]
+ assert not data["bulkProductErrors"]
assert data["count"] == 2
assert product_varinat_count + 2 == ProductVariant.objects.count()
assert attribut_value_count + 1 == size_attribute.values.count()
@@ -766,9 +767,11 @@ def test_product_variant_bulk_create_negative_quantity(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- # TODO Refactor errors
- assert len(data["productErrors"]) == 1
- assert data["productErrors"][0]["code"] == ProductErrorCode.INVALID.name
+ assert len(data["bulkProductErrors"]) == 1
+ error = data["bulkProductErrors"][0]
+ assert error["field"] == "quantity"
+ assert error["code"] == ProductErrorCode.INVALID.name
+ assert error["index"] == 0
assert product_varinat_count == ProductVariant.objects.count()
@@ -792,9 +795,11 @@ def test_product_variant_bulk_create_duplicated_sku(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- # TODO Refactor errors
- assert len(data["productErrors"]) == 1
- assert data["productErrors"][0]["code"] == ProductErrorCode.UNIQUE.name
+ assert len(data["bulkProductErrors"]) == 1
+ error = data["bulkProductErrors"][0]
+ assert error["field"] == "sku"
+ assert error["code"] == ProductErrorCode.UNIQUE.name
+ assert error["index"] == 0
assert product_varinat_count == ProductVariant.objects.count()
@@ -822,9 +827,11 @@ def test_product_variant_bulk_create_duplicated_sku_in_input(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- # TODO Refactor errors
- assert len(data["productErrors"]) == 1
- assert data["productErrors"][0]["code"] == ProductErrorCode.UNIQUE.name
+ assert len(data["bulkProductErrors"]) == 1
+ error = data["bulkProductErrors"][0]
+ assert error["field"] == "sku"
+ assert error["code"] == ProductErrorCode.UNIQUE.name
+ assert error["index"] == 1
assert product_varinat_count == ProductVariant.objects.count()
@@ -855,9 +862,14 @@ def test_product_variant_bulk_create_invalid_attribute_slug(
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
# TODO Refactor errors
- assert len(data["productErrors"]) == 2
- assert data["productErrors"][0]["code"] == ProductErrorCode.NOT_FOUND.name
- assert data["productErrors"][1]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert len(data["bulkProductErrors"]) == 2
+ errors = data["bulkProductErrors"]
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[0]["index"] == 0
+ assert errors[1]["field"] == "attributes"
+ assert errors[1]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[1]["index"] == 1
assert product_varinat_count == ProductVariant.objects.count()
@@ -897,8 +909,15 @@ def test_product_variant_bulk_create_many_errors(
)
content = get_graphql_content(response)
data = content["data"]["productVariantBulkCreate"]
- assert len(data["productErrors"]) == 3
- assert data["productErrors"][0]["code"] == ProductErrorCode.INVALID.name
- assert data["productErrors"][1]["code"] == ProductErrorCode.UNIQUE.name
- assert data["productErrors"][2]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert len(data["bulkProductErrors"]) == 3
+ errors = data["bulkProductErrors"]
+ assert errors[0]["field"] == "quantity"
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["index"] == 0
+ assert errors[1]["field"] == "sku"
+ assert errors[1]["code"] == ProductErrorCode.UNIQUE.name
+ assert errors[1]["index"] == 1
+ assert errors[2]["field"] == "attributes"
+ assert errors[2]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[2]["index"] == 2
assert product_varinat_count == ProductVariant.objects.count()