Skip to content

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

Add validate_price_amount validators

IKarbowiak5e7cd15adcac
diff --git a/saleor/graphql/core/tests/test_validators.py b/saleor/graphql/core/tests/test_validators.py
new file mode 100644
index 0000000000..23c9567b79
--- /dev/null
+++ b/saleor/graphql/core/tests/test_validators.py
@@ -0,0 +1,40 @@
+from decimal import Decimal
+
+import pytest
+from django.core.exceptions import ValidationError
+
+from ..validators import validate_price_amount
+
+
+ "value, currency",
+ [
+ (Decimal("1.1200"), "USD"),
+ (Decimal("1.12"), "USD"),
+ (Decimal("1"), "USD"),
+ (Decimal("1"), "ISK"),
+ (Decimal("1.00"), "ISK"),
+ (Decimal("5.12"), None),
+ ],
+)
+def test_validate_price_amount(value, currency):
+ # when
+ result = validate_price_amount(value, currency)
+
+ # then
+ assert result is None
+
+
+ "value, currency",
+ [
+ (Decimal("1.1212"), "USD"),
+ (Decimal("1.128"), "USD"),
+ (Decimal("1.1"), "ISK"),
+ (Decimal("1.11"), "ISK"),
+ (Decimal("5.123"), None),
+ ],
+)
+def test_validate_price_amount_raise_error(value, currency):
+ with pytest.raises(ValidationError):
+ validate_price_amount(value, currency)
diff --git a/saleor/graphql/core/validators.py b/saleor/graphql/core/validators.py
index 44436fcddf..4b24c69639 100644
--- a/saleor/graphql/core/validators.py
+++ b/saleor/graphql/core/validators.py
@@ -1,5 +1,13 @@
+from typing import TYPE_CHECKING
+
+from django.conf import settings
+from django.core.exceptions import ValidationError
+from django_prices.utils.formatting import get_currency_fraction
from graphql.error import GraphQLError
+if TYPE_CHECKING:
+ from decimal import Decimal
+
def validate_one_of_args_is_in_query(arg1_name, arg1, arg2_name, arg2):
if arg1 and arg2:
@@ -10,3 +18,18 @@ def validate_one_of_args_is_in_query(arg1_name, arg1, arg2_name, arg2):
raise GraphQLError(
f"Either '{arg1_name}' or '{arg2_name}' argument is required"
)
+
+
+def validate_price_amount(value: "Decimal", currency: str = None):
+ """Validate if price amount has appropriate number of decimal places."""
+ if not value:
+ return
+ if currency:
+ currency_fraction = get_currency_fraction(currency)
+ else:
+ currency_fraction = get_currency_fraction(settings.DEFAULT_CURRENCY)
+ value = value.normalize()
+ if abs(value.as_tuple().exponent) > currency_fraction:
+ raise ValidationError(
+ f"Value cannot have more than {currency_fraction} decimal places."
+ )