Skip to content

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

Change type of price input fields to MoneyScalar

IKarbowiakb272c40fd816
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index 1971be5d2c..ddf006e079 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -10,7 +10,11 @@ from graphene import InputField
from ....product.models import Category, Product
from ...product import types as product_types
-from ...tests.utils import _get_graphql_content_from_response, get_graphql_content
+from ...tests.utils import (
+ _get_graphql_content_from_response,
+ assert_too_many_decimal_places_in_amount,
+ get_graphql_content,
+)
from ...utils import get_database_id, requestor_is_superuser
from ...utils.filters import filter_range_field, reporting_period_to_date
from ..enums import ReportingPeriod
@@ -77,38 +81,6 @@ def test_snake_to_camel_case():
assert snake_to_camel_case(123) == 123
-def test_mutation_returns_error_field_in_camel_case(
- staff_api_client, variant, permission_manage_products
-):
- # costPrice is snake case variable (cost_price) in the backend
- query = """
- mutation testCamel($id: ID!, $price: Decimal, $cost: Decimal) {
- productVariantUpdate(id: $id,
- input: {costPrice: $cost, price: $price, trackInventory: false}) {
- errors {
- field
- message
- }
- productVariant {
- id
- }
- }
- }
- """
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant.id),
- "price": 15,
- "cost": 12.1234,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- errors = content["data"]["productVariantUpdate"]["errors"]
- assert len(errors) == 1
- assert errors[0]["field"] == "costPriceAmount"
-
-
def test_reporting_period_to_date():
now = timezone.now()
start_date = reporting_period_to_date(ReportingPeriod.TODAY)
@@ -161,11 +133,11 @@ def test_total_count_query(api_client, product):
assert content["data"]["products"]["totalCount"] == Product.objects.count()
-def test_mutation_decimal_input(
+def test_mutation_money_scalar_input(
staff_api_client, variant, stock, permission_manage_products
):
query = """
- mutation decimalInput($id: ID!, $cost: Decimal, $price: Decimal) {
+ mutation moneyScalarInput($id: ID!, $cost: MoneyScalar, $price: MoneyScalar) {
productVariantUpdate(id: $id, input: {costPrice: $cost, price: $price}) {
errors {
field
@@ -193,11 +165,13 @@ def test_mutation_decimal_input(
assert data["errors"] == []
-def test_mutation_decimal_input_without_arguments(
+def test_mutation_money_scalar_input_without_arguments(
staff_api_client, variant, permission_manage_products
):
query = """
- mutation ProductVariantUpdate($id: ID!, $price: Decimal, $costPrice: Decimal) {
+ mutation ProductVariantUpdate(
+ $id: ID!, $price: MoneyScalar, $costPrice: MoneyScalar
+ ) {
productVariantUpdate(id: $id, input: {costPrice: $costPrice, price: $price}) {
errors {
field
@@ -224,6 +198,72 @@ def test_mutation_decimal_input_without_arguments(
assert data["errors"] == []
+def test_mutation_money_scalar_to_many_decimal_places(
+ staff_api_client, variant, permission_manage_products
+):
+ # given
+ query = """
+ mutation testMoneyScalar($id: ID!, $price: MoneyScalar, $costPrice: MoneyScalar) {
+ productVariantUpdate(id: $id,
+ input: {costPrice: $costPrice, price: $price}) {
+ errors {
+ field
+ message
+ }
+ productVariant {
+ id
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "price": 15,
+ "costPrice": 12.1234,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_too_many_decimal_places_in_amount(response)
+
+
+def test_mutation_money_scalar_with_to_many_0_decimal_places(
+ staff_api_client, variant, permission_manage_products
+):
+ # given
+ query = """
+ mutation testMoneyScalar($id: ID!, $price: MoneyScalar, $costPrice: MoneyScalar) {
+ productVariantUpdate(id: $id,
+ input: {costPrice: $costPrice, price: $price}) {
+ errors {
+ field
+ message
+ }
+ productVariant {
+ id
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "price": 15,
+ "costPrice": 12.1200,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantUpdate"]
+ assert not data["errors"]
+
+
def test_filter_input():
class CreatedEnum(graphene.Enum):
WEEK = "week"
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index 8fc8dd3a02..90f1558733 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -10,7 +10,7 @@ from ...product.tasks import (
update_products_minimal_variant_prices_of_discount_task,
)
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ..core.scalars import Decimal
+from ..core.scalars import Decimal, MoneyScalar
from ..core.types.common import DiscountError
from ..product.types import Category, Collection, Product
from .enums import DiscountValueTypeEnum, VoucherTypeEnum
@@ -109,7 +109,7 @@ class VoucherInput(graphene.InputObjectType):
description="Categories discounted by the voucher.",
name="categories",
)
- min_amount_spent = Decimal(
+ min_amount_spent = MoneyScalar(
description="Min purchase amount required to apply the voucher."
)
min_checkout_items_quantity = graphene.Int(
diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.py
index 90d2b7fbb4..81fd99e536 100644
--- a/saleor/graphql/discount/tests/test_discount.py
+++ b/saleor/graphql/discount/tests/test_discount.py
@@ -143,7 +143,8 @@ CREATE_VOUCHER_MUTATION = """
mutation voucherCreate(
$type: VoucherTypeEnum, $name: String, $code: String,
$discountValueType: DiscountValueTypeEnum, $usageLimit: Int,
- $discountValue: Decimal, $minAmountSpent: Decimal, $minCheckoutItemsQuantity: Int,
+ $discountValue: Decimal,
+ $minAmountSpent: MoneyScalar, $minCheckoutItemsQuantity: Int,
$startDate: DateTime, $endDate: DateTime, $applyOncePerOrder: Boolean,
$applyOncePerCustomer: Boolean) {
voucherCreate(input: {
diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.py
index 789d1a1a81..7674750098 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -12,7 +12,7 @@ from ...giftcard import models
from ...giftcard.error_codes import GiftCardErrorCode
from ...giftcard.utils import activate_gift_card, deactivate_gift_card
from ..core.mutations import BaseMutation, ModelMutation
-from ..core.scalars import Decimal
+from ..core.scalars import MoneyScalar
from ..core.types.common import GiftCardError
from .types import GiftCard
@@ -24,7 +24,7 @@ class GiftCardUpdateInput(graphene.InputObjectType):
end_date = graphene.types.datetime.Date(
description="End date of the gift card in ISO 8601 format."
)
- balance = Decimal(description="Value of the gift card.")
+ balance = MoneyScalar(description="Value of the gift card.")
user_email = graphene.String(
required=False, description="The customer's email of the gift card buyer."
)
diff --git a/saleor/graphql/giftcard/tests/test_gift_card.py b/saleor/graphql/giftcard/tests/test_gift_card.py
index 2fe67b7eff..5a4f5974bb 100644
--- a/saleor/graphql/giftcard/tests/test_gift_card.py
+++ b/saleor/graphql/giftcard/tests/test_gift_card.py
@@ -234,7 +234,7 @@ def test_query_gift_card_by_app_without_premissions(
CREATE_GIFT_CARD_MUTATION = """
mutation giftCardCreate(
$code: String, $startDate: Date, $endDate: Date,
- $balance: Decimal!, $userEmail: String) {
+ $balance: MoneyScalar!, $userEmail: String) {
giftCardCreate(input: {
code: $code, startDate: $startDate,
endDate: $endDate,
@@ -476,7 +476,7 @@ def test_create_gift_card_without_premissions(staff_api_client):
UPDATE_GIFT_CARD_MUTATION = """
mutation giftCardUpdate(
$id: ID!, $startDate: Date, $endDate: Date,
- $balance: Decimal, $userEmail: String!) {
+ $balance: MoneyScalar, $userEmail: String!) {
giftCardUpdate(id: $id, input: {startDate: $startDate,
endDate: $endDate,
balance: $balance, userEmail: $userEmail}) {
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 31b038597f..f06eda8acb 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -21,7 +21,7 @@ from ....warehouse.management import allocate_stock
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ...core.scalars import Decimal
+from ...core.scalars import MoneyScalar
from ...core.types.common import OrderError
from ...product.types import ProductVariant
from ..types import Order, OrderLine
@@ -46,7 +46,7 @@ class DraftOrderInput(InputObjectType):
descripton="Customer associated with the draft order.", name="user"
)
user_email = graphene.String(description="Email address of the customer.")
- discount = Decimal(description="Discount amount for the order.")
+ discount = MoneyScalar(description="Discount amount for the order.")
shipping_address = AddressInput(description="Shipping address of the customer.")
shipping_method = graphene.ID(
description="ID of a selected shipping method.", name="shippingMethod"
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 46da0496a7..5d03f931dd 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -19,7 +19,7 @@ from ....order.utils import get_valid_shipping_methods_for_order
from ....payment import CustomPaymentChoices, PaymentError, TransactionKind, gateway
from ...account.types import AddressInput
from ...core.mutations import BaseMutation
-from ...core.scalars import UUID, Decimal
+from ...core.scalars import UUID, MoneyScalar
from ...core.types.common import OrderError
from ...core.utils import validate_required_string_field
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
@@ -362,7 +362,7 @@ class OrderCapture(BaseMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of the order to capture.")
- amount = Decimal(required=True, description="Amount of money to capture.")
+ amount = MoneyScalar(required=True, description="Amount of money to capture.")
class Meta:
description = "Capture an order."
@@ -429,7 +429,7 @@ class OrderRefund(BaseMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of the order to refund.")
- amount = Decimal(required=True, description="Amount of money to refund.")
+ amount = MoneyScalar(required=True, description="Amount of money to refund.")
class Meta:
description = "Refund an order."
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 909394852a..e0b375418b 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -572,7 +572,7 @@ def test_draft_order_create(
variant_0 = variant
query = """
mutation draftCreate(
- $user: ID, $discount: Decimal, $lines: [OrderLineCreateInput],
+ $user: ID, $discount: MoneyScalar, $lines: [OrderLineCreateInput],
$shippingAddress: AddressInput, $shippingMethod: ID, $voucher: ID,
$customerNote: String) {
draftOrderCreate(
@@ -1574,7 +1574,7 @@ def test_order_capture(
):
order = payment_txn_preauth.order
query = """
- mutation captureOrder($id: ID!, $amount: Decimal!) {
+ mutation captureOrder($id: ID!, $amount: MoneyScalar!) {
orderCapture(id: $id, amount: $amount) {
order {
paymentStatus
@@ -1781,7 +1781,7 @@ def test_order_void_payment_error(
def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_captured):
order = payment_txn_captured.order
query = """
- mutation refundOrder($id: ID!, $amount: Decimal!) {
+ mutation refundOrder($id: ID!, $amount: MoneyScalar!) {
orderRefund(id: $id, amount: $amount) {
order {
paymentStatus
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 9f5bc2451d..55f3c9f14b 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -15,7 +15,7 @@ from ..account.i18n import I18nMixin
from ..account.types import AddressInput
from ..checkout.types import Checkout
from ..core.mutations import BaseMutation
-from ..core.scalars import Decimal
+from ..core.scalars import MoneyScalar
from ..core.types import common as common_types
from ..core.utils import from_global_id_strict_type
from .types import Payment
@@ -34,7 +34,7 @@ class PaymentInput(graphene.InputObjectType):
"billing data in a secure manner."
),
)
- amount = Decimal(
+ amount = MoneyScalar(
required=False,
description=(
"Total amount of the transaction, including "
@@ -190,7 +190,7 @@ class PaymentCapture(BaseMutation):
class Arguments:
payment_id = graphene.ID(required=True, description="Payment ID.")
- amount = Decimal(description="Transaction amount.")
+ amount = MoneyScalar(description="Transaction amount.")
class Meta:
description = "Captures the authorized payment amount."
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index f7122a1ed7..b39b5e66d2 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -398,7 +398,7 @@ def test_create_payment_for_checkout_with_active_payments(
CAPTURE_QUERY = """
- mutation PaymentCapture($paymentId: ID!, $amount: Decimal!) {
+ mutation PaymentCapture($paymentId: ID!, $amount: MoneyScalar!) {
paymentCapture(paymentId: $paymentId, amount: $amount) {
payment {
id,
@@ -547,7 +547,7 @@ def test_payment_capture_gateway_dummy_credit_card_error(
REFUND_QUERY = """
- mutation PaymentRefund($paymentId: ID!, $amount: Decimal!) {
+ mutation PaymentRefund($paymentId: ID!, $amount: MoneyScalar!) {
paymentRefund(paymentId: $paymentId, amount: $amount) {
payment {
id,
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index 14117de7ca..58d53e86f6 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -168,22 +168,10 @@ class ProductVariantBulkCreate(BaseMutation):
cost_price_amount = cleaned_input.pop("cost_price", None)
if cost_price_amount is not None:
- if cost_price_amount < 0:
- errors["costPrice"] = ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- params={"index": variant_index},
- )
cleaned_input["cost_price_amount"] = cost_price_amount
price_amount = cleaned_input.pop("price", None)
if price_amount is not None:
- if price_amount < 0:
- errors["price"] = ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- params={"index": variant_index},
- )
cleaned_input["price_amount"] = price_amount
attributes = cleaned_input.get("attributes")
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 6496765557..a2207b3bc5 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -29,7 +29,7 @@ from ....product.utils.attributes import (
generate_name_for_variant,
)
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ...core.scalars import Decimal, WeightScalar
+from ...core.scalars import MoneyScalar, WeightScalar
from ...core.types import SeoInput, Upload
from ...core.types.common import ProductError
from ...core.utils import (
@@ -534,7 +534,7 @@ class ProductInput(graphene.InputObjectType):
"is only used if a product doesn't use variants."
)
)
- base_price = Decimal(
+ base_price = MoneyScalar(
description=(
"Default price for product variant. "
"Note: this field is only used if a product doesn't use variants."
@@ -823,17 +823,6 @@ class ProductCreate(ModelMutation):
}
)
- base_price = cleaned_input.get("base_price")
- if base_price is not None and base_price < 0:
- raise ValidationError(
- {
- "base_price": ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- )
- }
- )
-
# 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
@@ -1108,8 +1097,8 @@ class ProductVariantInput(graphene.InputObjectType):
required=False,
description="List of attributes specific to this variant.",
)
- cost_price = Decimal(description="Cost price of the variant.")
- price = Decimal(description="Price of the particular variant.")
+ cost_price = MoneyScalar(description="Cost price of the variant.")
+ price = MoneyScalar(description="Price of the particular variant.")
sku = graphene.String(description="Stock keeping unit.")
track_inventory = graphene.Boolean(
description=(
@@ -1194,17 +1183,7 @@ class ProductVariantCreate(ModelMutation):
)
if "cost_price" in cleaned_input:
- cost_price = cleaned_input.pop("cost_price")
- if cost_price and cost_price < 0:
- raise ValidationError(
- {
- "costPrice": ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- )
- }
- )
- cleaned_input["cost_price_amount"] = cost_price
+ cleaned_input["cost_price_amount"] = cleaned_input.pop("cost_price")
price = cleaned_input.get("price")
if price is None and instance.price is None:
@@ -1218,17 +1197,7 @@ class ProductVariantCreate(ModelMutation):
)
if "price" in cleaned_input:
- price = cleaned_input.pop("price")
- if price is not None and price < 0:
- raise ValidationError(
- {
- "price": ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- )
- }
- )
- cleaned_input["price_amount"] = price
+ cleaned_input["price_amount"] = cleaned_input.pop("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 41397b1521..387312a284 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -33,6 +33,7 @@ from ....product.utils.attributes import associate_attribute_values_to_instance
from ....warehouse.models import Allocation, Stock, Warehouse
from ...core.enums import ReportingPeriod
from ...tests.utils import (
+ assert_negative_price_amount,
assert_no_permission,
get_graphql_content,
get_multipart_request_body,
@@ -1365,6 +1366,7 @@ def test_create_product_with_negative_base_price(
):
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)
@@ -1380,14 +1382,9 @@ def test_create_product_with_negative_base_price(
}
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productCreate"]
- error = data["productErrors"][0]
- assert error["field"] == "basePrice"
- assert error["code"] == ProductErrorCode.INVALID.name
+ response = staff_api_client.post_graphql(query, variables)
+
+ assert_negative_price_amount(response)
def test_create_product_with_unicode_in_slug_and_name(
@@ -1431,7 +1428,7 @@ QUERY_CREATE_PRODUCT_WITHOUT_VARIANTS = """
$productTypeId: ID!,
$categoryId: ID!
$name: String!,
- $basePrice: Decimal!,
+ $basePrice: MoneyScalar!,
$sku: String,
$trackInventory: Boolean)
{
@@ -1725,7 +1722,7 @@ def test_update_product(
$isPublished: Boolean!,
$chargeTaxes: Boolean!,
$taxCode: String!,
- $basePrice: Decimal!,
+ $basePrice: MoneyScalar!,
$attributes: [AttributeValueInput!]) {
productUpdate(
id: $productId,
@@ -2287,7 +2284,7 @@ def test_update_product_with_negative_base_price(
query = """
mutation updateProduct(
$productId: ID!,
- $basePrice: Decimal)
+ $basePrice: MoneyScalar)
{
productUpdate(
id: $productId,
@@ -2306,19 +2303,15 @@ def test_update_product_with_negative_base_price(
}
}
"""
+ 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}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- error = data["productErrors"][0]
- assert error["field"] == "basePrice"
- assert error["code"] == ProductErrorCode.INVALID.name
+ response = staff_api_client.post_graphql(query, variables)
+
+ assert_negative_price_amount(response)
def test_update_product_without_category_and_true_is_published_value(
@@ -4220,7 +4213,7 @@ mutation createProduct(
$name: String!,
$sku: String,
$stocks: [StockInput!],
- $basePrice: Decimal!
+ $basePrice: MoneyScalar!
$trackInventory: Boolean)
{
productCreate(
@@ -4410,7 +4403,7 @@ mutation createProduct(
$category: ID!
$name: String!,
$sku: String,
- $basePrice: Decimal!,
+ $basePrice: MoneyScalar!,
$weight: WeightScalar)
{
productCreate(
@@ -4515,7 +4508,7 @@ def test_create_product_with_weight_input(
$category: ID!,
$name: String!,
$sku: String,
- $basePrice: Decimal!)
+ $basePrice: MoneyScalar!)
{{
productCreate(
input: {{
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 23ffb96e83..0b44241bb3 100644
--- a/saleor/graphql/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/graphql/product/tests/test_product_minimal_variant_price.py
@@ -4,9 +4,8 @@ import graphene
from freezegun import freeze_time
from graphql_relay import from_global_id, to_global_id
-from ....product.error_codes import ProductErrorCode
from ...discount.enums import DiscountValueTypeEnum
-from ...tests.utils import get_graphql_content
+from ...tests.utils import assert_negative_price_amount, get_graphql_content
@patch(
@@ -23,7 +22,7 @@ def test_product_variant_create_updates_minimal_variant_price(
mutation ProductVariantCreate(
$productId: ID!,
$sku: String!,
- $price: Decimal,
+ $price: MoneyScalar,
$attributes: [AttributeValueInput]!,
) {
productVariantCreate(
@@ -84,7 +83,7 @@ def test_product_variant_update_updates_minimal_variant_price(
query = """
mutation ProductVariantUpdate(
$id: ID!,
- $price: Decimal,
+ $price: MoneyScalar,
) {
productVariantUpdate(
id: $id,
@@ -133,7 +132,7 @@ def test_product_variant_update_updates_invalid_variant_price(
query = """
mutation ProductVariantUpdate(
$id: ID!,
- $price: Decimal,
+ $price: MoneyScalar,
) {
productVariantUpdate(
id: $id,
@@ -152,19 +151,15 @@ def test_product_variant_update_updates_invalid_variant_price(
}
}
"""
+ staff_api_client.user.user_permissions.add(permission_manage_products)
variant = product.variants.first()
variant_id = to_global_id("ProductVariant", variant.pk)
price = "-1.99"
variables = {"id": variant_id, "price": price}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- assert response.status_code == 200
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
- assert data["productErrors"][0]["field"] == "price"
- assert data["productErrors"][0]["code"] == ProductErrorCode.INVALID.name
+ response = staff_api_client.post_graphql(query, variables)
+
+ assert_negative_price_amount(response)
@patch(
@@ -180,7 +175,7 @@ def test_product_variant_update_updates_invalid_cost_price(
query = """
mutation ProductVariantUpdate(
$id: ID!,
- $costPrice: Decimal,
+ $costPrice: MoneyScalar,
) {
productVariantUpdate(
id: $id,
@@ -199,19 +194,15 @@ def test_product_variant_update_updates_invalid_cost_price(
}
}
"""
+ staff_api_client.user.user_permissions.add(permission_manage_products)
variant = product.variants.first()
variant_id = to_global_id("ProductVariant", variant.pk)
cost_price = "-1.99"
variables = {"id": variant_id, "costPrice": cost_price}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- assert response.status_code == 200
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
- assert data["productErrors"][0]["field"] == "costPrice"
- assert data["productErrors"][0]["code"] == ProductErrorCode.INVALID.name
+ response = staff_api_client.post_graphql(query, variables)
+
+ assert_negative_price_amount(response)
@patch(
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 0b367a32fa..650a97e392 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -12,7 +12,7 @@ from ....product.utils.attributes import associate_attribute_values_to_instance
from ....warehouse.error_codes import StockErrorCode
from ....warehouse.models import Stock, Warehouse
from ...core.enums import WeightUnitsEnum
-from ...tests.utils import get_graphql_content
+from ...tests.utils import assert_negative_price_amount, get_graphql_content
def test_fetch_variant(
@@ -96,8 +96,8 @@ def test_create_variant(
$productId: ID!,
$sku: String!,
$stocks: [StockInput!],
- $price: Decimal,
- $costPrice: Decimal,
+ $price: MoneyScalar,
+ $costPrice: MoneyScalar,
$attributes: [AttributeValueInput]!,
$weight: WeightScalar,
$trackInventory: Boolean!) {
@@ -284,7 +284,7 @@ def test_create_product_variant_not_all_attributes(
query = """
mutation createVariant (
$productId: ID!,
- $price: Decimal,
+ $price: MoneyScalar,
$sku: String!,
$attributes: [AttributeValueInput]!) {
productVariantCreate(
@@ -340,7 +340,7 @@ def test_create_product_variant_duplicated_attributes(
query = """
mutation createVariant (
$productId: ID!,
- $price: Decimal,
+ $price: MoneyScalar,
$sku: String!,
$attributes: [AttributeValueInput]!
) {
@@ -393,8 +393,8 @@ def test_create_product_variant_update_with_new_attributes(
mutation VariantUpdate(
$id: ID!
$attributes: [AttributeValueInput]
- $costPrice: Decimal
- $price: Decimal
+ $costPrice: MoneyScalar
+ $price: MoneyScalar
$sku: String
$trackInventory: Boolean!
) {
@@ -466,8 +466,8 @@ def test_update_product_variant(staff_api_client, product, permission_manage_pro
mutation updateVariant (
$id: ID!,
$sku: String!,
- $price: Decimal,
- $costPrice: Decimal,
+ $price: MoneyScalar,
+ $costPrice: MoneyScalar,
$trackInventory: Boolean!) {
productVariantUpdate(
id: $id,
@@ -525,7 +525,7 @@ def test_update_product_variant_with_negative_weight(
query = """
mutation updateVariant (
$id: ID!,
- $price: Decimal,
+ $price: MoneyScalar,
$weight: WeightScalar
) {
productVariantUpdate(
@@ -570,8 +570,8 @@ def test_update_product_variant_unset_cost_price(
mutation updateVariant (
$id: ID!,
$sku: String!,
- $price: Decimal,
- $costPrice: Decimal) {
+ $price: MoneyScalar,
+ $costPrice: MoneyScalar) {
productVariantUpdate(
id: $id,
input: {
@@ -615,7 +615,7 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """
mutation updateVariant (
$id: ID!,
$sku: String,
- $price: Decimal,
+ $price: MoneyScalar,
$attributes: [AttributeValueInput]!) {
productVariantUpdate(
id: $id,
@@ -1092,6 +1092,7 @@ def test_product_variant_bulk_create_by_attribute_id(
def test_product_variant_bulk_create_by_attribute_id_with_invalid_price(
staff_api_client, product, size_attribute, permission_manage_products, price_field
):
+ # given
product_id = graphene.Node.to_global_id("Product", product.pk)
attribut_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
attribute_value = size_attribute.values.last()
@@ -1107,13 +1108,14 @@ def test_product_variant_bulk_create_by_attribute_id_with_invalid_price(
variables = {"productId": product_id, "variants": [variant]}
staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
response = staff_api_client.post_graphql(
PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
)
- content = get_graphql_content(response)
- data = content["data"]["productVariantBulkCreate"]
- assert data["bulkProductErrors"][0]["field"] == price_field
- assert data["bulkProductErrors"][0]["code"] == ProductErrorCode.INVALID.name
+
+ # then
+ assert_negative_price_amount(response)
def test_product_variant_bulk_create_empty_attribute(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 67bec9e023..7bdd272b7a 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1776,7 +1776,7 @@ input DraftOrderCreateInput {
billingAddress: AddressInput
user: ID
userEmail: String
- discount: Decimal
+ discount: MoneyScalar
shippingAddress: AddressInput
shippingMethod: ID
voucher: ID
@@ -1794,7 +1794,7 @@ input DraftOrderInput {
billingAddress: AddressInput
user: ID
userEmail: String
- discount: Decimal
+ discount: MoneyScalar
shippingAddress: AddressInput
shippingMethod: ID
voucher: ID
@@ -2062,7 +2062,7 @@ type GiftCardCreate {
input GiftCardCreateInput {
startDate: Date
endDate: Date
- balance: Decimal
+ balance: MoneyScalar
userEmail: String
code: String
}
@@ -2097,7 +2097,7 @@ type GiftCardUpdate {
input GiftCardUpdateInput {
startDate: Date
endDate: Date
- balance: Decimal
+ balance: MoneyScalar
userEmail: String
}
@@ -2555,6 +2555,8 @@ type MoneyRange {
stop: Money
}
+scalar MoneyScalar
+
input MoveProductInput {
productId: ID!
sortOrder: Int
@@ -2671,8 +2673,8 @@ type Mutation {
productVariantClearPrivateMetadata(id: ID!, input: MetaPath!): ProductVariantClearPrivateMeta @deprecated(reason: "Use the `deletePrivateMetadata` mutation instead. This field will be removed after 2020-07-31.")
variantImageAssign(imageId: ID!, variantId: ID!): VariantImageAssign
variantImageUnassign(imageId: ID!, variantId: ID!): VariantImageUnassign
- paymentCapture(amount: Decimal, paymentId: ID!): PaymentCapture
- paymentRefund(amount: Decimal, paymentId: ID!): PaymentRefund
+ paymentCapture(amount: MoneyScalar, paymentId: ID!): PaymentCapture
+ paymentRefund(amount: MoneyScalar, paymentId: ID!): PaymentRefund
paymentVoid(paymentId: ID!): PaymentVoid
pageCreate(input: PageInput!): PageCreate
pageDelete(id: ID!): PageDelete
@@ -2691,7 +2693,7 @@ type Mutation {
draftOrderUpdate(id: ID!, input: DraftOrderInput!): DraftOrderUpdate
orderAddNote(order: ID!, input: OrderAddNoteInput!): OrderAddNote
orderCancel(id: ID!): OrderCancel
- orderCapture(amount: Decimal!, id: ID!): OrderCapture
+ orderCapture(amount: MoneyScalar!, id: ID!): OrderCapture
orderClearPrivateMeta(id: ID!, input: MetaPath!): OrderClearPrivateMeta @deprecated(reason: "Use the `deletePrivateMetadata` mutation instead. This field will be removed after 2020-07-31.")
orderClearMeta(input: MetaPath!, token: UUID!): OrderClearMeta @deprecated(reason: "Use the `deleteMetadata` mutation instead. This field will be removed after 2020-07-31.")
orderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfill
@@ -2702,7 +2704,7 @@ type Mutation {
orderFulfillmentUpdateMeta(id: ID!, input: MetaInput!): FulfillmentUpdateMeta @deprecated(reason: "Use the `updateMetadata` mutation instead. This field will be removed after 2020-07-31.")
orderFulfillmentUpdatePrivateMeta(id: ID!, input: MetaInput!): FulfillmentUpdatePrivateMeta @deprecated(reason: "Use the `updatePrivateMetadata` mutation instead. This field will be removed after 2020-07-31.")
orderMarkAsPaid(id: ID!): OrderMarkAsPaid
- orderRefund(amount: Decimal!, id: ID!): OrderRefund
+ orderRefund(amount: MoneyScalar!, id: ID!): OrderRefund
orderUpdate(id: ID!, input: OrderUpdateInput!): OrderUpdate
orderUpdateMeta(input: MetaInput!, token: UUID!): OrderUpdateMeta @deprecated(reason: "Use the `updateMetadata` mutation instead. This field will be removed after 2020-07-31.")
orderUpdatePrivateMeta(id: ID!, input: MetaInput!): OrderUpdatePrivateMeta @deprecated(reason: "Use the `updatePrivateMetadata` mutation instead. This field will be removed after 2020-07-31.")
@@ -3444,7 +3446,7 @@ type PaymentGateway {
input PaymentInput {
gateway: String!
token: String
- amount: Decimal
+ amount: MoneyScalar
billingAddress: AddressInput
returnUrl: String
}
@@ -3717,7 +3719,7 @@ input ProductCreateInput {
weight: WeightScalar
sku: String
trackInventory: Boolean
- basePrice: Decimal
+ basePrice: MoneyScalar
productType: ID!
stocks: [StockInput!]
}
@@ -3848,7 +3850,7 @@ input ProductInput {
weight: WeightScalar
sku: String
trackInventory: Boolean
- basePrice: Decimal
+ basePrice: MoneyScalar
}
input ProductOrder {
@@ -4088,8 +4090,8 @@ type ProductVariantBulkCreate {
input ProductVariantBulkCreateInput {
attributes: [AttributeValueInput]!
- costPrice: Decimal
- price: Decimal
+ costPrice: MoneyScalar
+ price: MoneyScalar
sku: String!
trackInventory: Boolean
weight: WeightScalar
@@ -4133,8 +4135,8 @@ type ProductVariantCreate {
input ProductVariantCreateInput {
attributes: [AttributeValueInput]!
- costPrice: Decimal
- price: Decimal
+ costPrice: MoneyScalar
+ price: MoneyScalar
sku: String
trackInventory: Boolean
weight: WeightScalar
@@ -4150,8 +4152,8 @@ type ProductVariantDelete {
input ProductVariantInput {
attributes: [AttributeValueInput]
- costPrice: Decimal
- price: Decimal
+ costPrice: MoneyScalar
+ price: MoneyScalar
sku: String
trackInventory: Boolean
weight: WeightScalar
@@ -4624,9 +4626,9 @@ type ShippingPriceDelete {
input ShippingPriceInput {
name: String
- price: Decimal
- minimumOrderPrice: Decimal
- maximumOrderPrice: Decimal
+ price: MoneyScalar
+ minimumOrderPrice: MoneyScalar
+ maximumOrderPrice: MoneyScalar
minimumOrderWeight: WeightScalar
maximumOrderWeight: WeightScalar
type: ShippingMethodTypeEnum
@@ -5340,7 +5342,7 @@ input VoucherInput {
products: [ID]
collections: [ID]
categories: [ID]
- minAmountSpent: Decimal
+ minAmountSpent: MoneyScalar
minCheckoutItemsQuantity: Int
countries: [String]
applyOncePerOrder: Boolean
diff --git a/saleor/graphql/shipping/mutations.py b/saleor/graphql/shipping/mutations.py
index 57c2512c16..3e973c4dfd 100644
--- a/saleor/graphql/shipping/mutations.py
+++ b/saleor/graphql/shipping/mutations.py
@@ -10,7 +10,7 @@ from ...shipping.utils import (
get_countries_without_shipping_zone,
)
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ..core.scalars import Decimal, WeightScalar
+from ..core.scalars import MoneyScalar, WeightScalar
from ..core.types.common import ShippingError
from ..core.utils import get_duplicates_ids
from .enums import ShippingMethodTypeEnum
@@ -19,11 +19,11 @@ from .types import ShippingMethod, ShippingZone
class ShippingPriceInput(graphene.InputObjectType):
name = graphene.String(description="Name of the shipping method.")
- price = Decimal(description="Shipping price of the shipping method.")
- minimum_order_price = Decimal(
+ price = MoneyScalar(description="Shipping price of the shipping method.")
+ minimum_order_price = MoneyScalar(
description="Minimum order price to use this shipping method."
)
- maximum_order_price = Decimal(
+ maximum_order_price = MoneyScalar(
description="Maximum order price to use this shipping method."
)
minimum_order_weight = WeightScalar(
@@ -170,15 +170,6 @@ class ShippingPriceMixin:
# Rename the price field to price_amount (the model's)
price_amount = cleaned_input.pop("price", None)
if price_amount is not None:
- if price_amount < 0:
- raise ValidationError(
- {
- "price": ValidationError(
- ("Shipping rate price cannot be lower than 0."),
- code=ShippingErrorCode.INVALID,
- )
- }
- )
cleaned_input["price_amount"] = price_amount
cleaned_type = cleaned_input.get("type")
diff --git a/saleor/graphql/shipping/tests/test_shipping_method.py b/saleor/graphql/shipping/tests/test_shipping_method.py
index f4e783b842..646747fefa 100644
--- a/saleor/graphql/shipping/tests/test_shipping_method.py
+++ b/saleor/graphql/shipping/tests/test_shipping_method.py
@@ -6,7 +6,7 @@ from ....core.weight import WeightUnits
from ....shipping.error_codes import ShippingErrorCode
from ....shipping.utils import get_countries_without_shipping_zone
from ...core.enums import WeightUnitsEnum
-from ...tests.utils import get_graphql_content
+from ...tests.utils import assert_negative_price_amount, get_graphql_content
from ..types import ShippingMethodTypeEnum
SHIPPING_ZONE_QUERY = """
@@ -523,9 +523,9 @@ def test_delete_shipping_zone(
PRICE_BASED_SHIPPING_QUERY = """
mutation createShippingPrice(
- $type: ShippingMethodTypeEnum, $name: String!, $price: Decimal,
- $shippingZone: ID!, $minimumOrderPrice: Decimal,
- $maximumOrderPrice: Decimal) {
+ $type: ShippingMethodTypeEnum, $name: String!, $price: MoneyScalar,
+ $shippingZone: ID!, $minimumOrderPrice: MoneyScalar,
+ $maximumOrderPrice: MoneyScalar) {
shippingPriceCreate(input: {
name: $name, price: $price, shippingZone: $shippingZone,
minimumOrderPrice: $minimumOrderPrice,
@@ -604,6 +604,7 @@ def test_create_shipping_method_with_invalid_price(
staff_api_client, shipping_zone, permission_manage_shipping,
):
query = PRICE_BASED_SHIPPING_QUERY
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
name = "DHL"
price = -12.34
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
@@ -615,13 +616,10 @@ def test_create_shipping_method_with_invalid_price(
"maximumOrderPrice": 20,
"type": ShippingMethodTypeEnum.PRICE.name,
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_shipping]
- )
- content = get_graphql_content(response)
- data = content["data"]["shippingPriceCreate"]
- assert data["shippingErrors"][0]["field"] == "price"
- assert data["shippingErrors"][0]["code"] == ShippingErrorCode.INVALID.name
+
+ response = staff_api_client.post_graphql(query, variables)
+
+ assert_negative_price_amount(response)
def test_create_price_shipping_method_errors(
@@ -646,7 +644,7 @@ def test_create_price_shipping_method_errors(
WEIGHT_BASED_SHIPPING_QUERY = """
mutation createShippingPrice(
- $type: ShippingMethodTypeEnum, $name: String!, $price: Decimal,
+ $type: ShippingMethodTypeEnum, $name: String!, $price: MoneyScalar,
$shippingZone: ID!, $maximumOrderWeight: WeightScalar,
$minimumOrderWeight: WeightScalar) {
shippingPriceCreate(
@@ -783,8 +781,8 @@ def test_update_shipping_method(
):
query = """
mutation updateShippingPrice(
- $id: ID!, $price: Decimal, $shippingZone: ID!,
- $type: ShippingMethodTypeEnum!, $minimumOrderPrice: Decimal) {
+ $id: ID!, $price: MoneyScalar, $shippingZone: ID!,
+ $type: ShippingMethodTypeEnum!, $minimumOrderPrice: MoneyScalar) {
shippingPriceUpdate(
id: $id, input: {
price: $price, shippingZone: $shippingZone,
diff --git a/saleor/graphql/tests/utils.py b/saleor/graphql/tests/utils.py
index 7bc4aabaac..95b06ab8a5 100644
--- a/saleor/graphql/tests/utils.py
+++ b/saleor/graphql/tests/utils.py
@@ -26,6 +26,22 @@ def assert_no_permission(response):
), content["errors"]
+def assert_negative_price_amount(response):
+ content = _get_graphql_content_from_response(response)
+ assert "errors" in content, content
+ assert content["errors"][0]["message"] == (
+ "Money value cannot be lower than 0."
+ ), content["errors"]
+
+
+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.
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index deebbc174f..4e40973caa 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -81,7 +81,7 @@ def test_product_update_updates_minimal_variant_price(
query = """
mutation ProductUpdate(
$productId: ID!,
- $basePrice: Decimal!,
+ $basePrice: MoneyScalar!,
) {
productUpdate(
id: $productId