Skip to content

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

Add price amount valdiation to Product and ProductVariant mutations

IKarbowiak5d7892598708
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 45e41e5d31..6decd124cb 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -41,6 +41,7 @@ from ...core.utils import (
validate_slug_and_generate_if_needed,
)
from ...core.utils.reordering import perform_reordering
+from ...core.validators import validate_price_amount
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
from ...warehouse.types import Warehouse
from ..types import Category, Collection, Product, ProductImage, ProductVariant
@@ -825,11 +826,18 @@ class ProductCreate(ModelMutation):
{
"weight": ValidationError(
"Product can't have negative weight.",
- code=ProductErrorCode.INVALID,
+ code=ProductErrorCode.INVALID.value,
)
}
)
+ base_price = cleaned_input.get("base_price")
+ try:
+ validate_price_amount(base_price, instance.currency)
+ except ValidationError as error:
+ error.code = ProductErrorCode.INVALID.value
+ raise ValidationError({"base_price": error})
+
# 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
@@ -1190,7 +1198,13 @@ class ProductVariantCreate(ModelMutation):
)
if "cost_price" in cleaned_input:
- cleaned_input["cost_price_amount"] = cleaned_input.pop("cost_price")
+ cost_price = cleaned_input.pop("cost_price")
+ try:
+ validate_price_amount(cost_price, instance.currency)
+ except ValidationError as error:
+ error.code = ProductErrorCode.INVALID.value
+ raise ValidationError({"cost_price": error})
+ cleaned_input["cost_price_amount"] = cost_price
price = cleaned_input.get("price")
if price is None and instance.price is None:
@@ -1204,7 +1218,12 @@ class ProductVariantCreate(ModelMutation):
)
if "price" in cleaned_input:
- cleaned_input["price_amount"] = cleaned_input.pop("price")
+ try:
+ validate_price_amount(price, instance.currency)
+ except ValidationError as error:
+ error.code = ProductErrorCode.INVALID.value
+ raise ValidationError({"price": error})
+ cleaned_input["price_amount"] = price
stocks = cleaned_input.get("stocks")
if stocks:
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 35c8ce90d7..68aaae7a83 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -1546,6 +1546,7 @@ def test_create_product_with_negative_base_price(
description_json,
permission_manage_products,
):
+ # given
query = CREATE_PRODUCT_MUTATION
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -1564,11 +1565,50 @@ def test_create_product_with_negative_base_price(
}
}
+ # when
response = staff_api_client.post_graphql(query, variables)
+ # then
assert_negative_positive_decimal_value(response)
+def test_create_product_with_too_many_decimal_places_in_price(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ query = CREATE_PRODUCT_MUTATION
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ 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"
+
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "basePrice": 1.1234,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ error = data["productErrors"][0]
+ assert error["field"] == "basePrice"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+
def test_create_product_with_unicode_in_slug_and_name(
staff_api_client,
product_type,
@@ -2502,6 +2542,94 @@ def test_update_product_with_negative_base_price(
assert_negative_positive_decimal_value(response)
+def test_update_product_with_too_many_decimal_places_in_price(
+ staff_api_client, product_with_default_variant, permission_manage_products, product
+):
+ # given
+ query = """
+ mutation updateProduct(
+ $productId: ID!,
+ $basePrice: PositiveDecimal)
+ {
+ productUpdate(
+ id: $productId,
+ input: {
+ basePrice: $basePrice
+ })
+ {
+ product {
+ id
+ }
+ productErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ product = product_with_default_variant
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variables = {"productId": product_id, "basePrice": 1.1001}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ error = data["productErrors"][0]
+ assert error["field"] == "basePrice"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+
+def test_update_product_with_too_many_decimal_places_in_price_different_currency(
+ staff_api_client, product_with_default_variant, permission_manage_products, product
+):
+ # given
+ query = """
+ mutation updateProduct(
+ $productId: ID!,
+ $basePrice: PositiveDecimal)
+ {
+ productUpdate(
+ id: $productId,
+ input: {
+ basePrice: $basePrice
+ })
+ {
+ product {
+ id
+ }
+ productErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+ """
+ product_with_default_variant.currency = "ISK"
+ product_with_default_variant.save(update_fields=["currency"])
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ product = product_with_default_variant
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variables = {"productId": product_id, "basePrice": 1.1}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ error = data["productErrors"][0]
+ assert error["field"] == "basePrice"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+
def test_update_product_without_category_and_true_is_published_value(
staff_api_client, permission_manage_products, product
):
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index d61685ed4f..1f116199a8 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -330,6 +330,53 @@ def test_create_product_variant_not_all_attributes(
assert not product.variants.filter(sku=sku).exists()
+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
+ }
+ }
+ }
+ """
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variant_id = graphene.Node.to_global_id(
+ "Attribute", product_type.variant_attributes.first().pk
+ )
+ variant_value = "test-value"
+
+ variables = {
+ "productId": product_id,
+ "weight": 1,
+ "attributes": [{"id": variant_id, "values": [variant_value]}],
+ "costPrice": 1.40001,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantCreate"]
+ error = data["productErrors"][0]
+ assert error["field"] == "costPrice"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+
def test_create_product_variant_duplicated_attributes(
staff_api_client,
product_with_variant_with_two_attributes,
@@ -637,6 +684,47 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """
"""
+def test_update_product_variant_with_too_many_decimal_values_in_price(
+ staff_api_client, product, permission_manage_products
+):
+ query = """
+ mutation updateVariant (
+ $id: ID!,
+ $price: PositiveDecimal,
+ $weight: WeightScalar
+ ) {
+ productVariantUpdate(
+ id: $id,
+ input: {
+ weight: $weight,
+ price: $price
+ }
+ ){
+ productVariant {
+ name
+ }
+ productErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+ """
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "weight": 1, "price": 15.234}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ variant.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantUpdate"]
+ error = data["productErrors"][0]
+ assert error["field"] == "price"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+
def test_update_product_variant_not_all_attributes(
staff_api_client, product, product_type, color_attribute, permission_manage_products
):
diff --git a/saleor/graphql/tests/utils.py b/saleor/graphql/tests/utils.py
index 429478be41..a6122dfc82 100644
--- a/saleor/graphql/tests/utils.py
+++ b/saleor/graphql/tests/utils.py
@@ -34,14 +34,6 @@ def assert_negative_positive_decimal_value(response):
]
-def assert_too_many_decimal_places_in_amount(response):
- content = _get_graphql_content_from_response(response)
- assert "errors" in content, content
- assert content["errors"][0]["message"] == (
- "Ensure the provided money field value has no more than 2 decimal places."
- ), content["errors"]
-
-
def get_multipart_request_body(query, variables, file, file_name):
"""Create request body for multipart GraphQL requests.