Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Enhance scalar types: add NonNegativeInt and enforce non-negative time units (#18762)
Lukasz Ostrowski2075f4d4e067
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 238c98ee72..edec9c2db7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,10 +18,13 @@ All notable, unreleased changes to this project will be documented in this file.After: `[_Any!]!`Make sure to adapt your GraphQL queries if you use the `_entities` query.+- Mutations `channelCreate` and `channelUpdate` now raise GraphQL errors instead `INVALID` when negative `MINUTE`/`HOUR`/`DAY` values are passed.### GraphQL API- Gift cards support as payment method within Transaction API (read more in the [docs](https://docs.saleor.io/developer/gift-cards#using-gift-cards-in-checkout)).- `Attribute` fields `name`, `slug` and `type` are now non-nullable in schema.+- Added new scalar `NonNegativeInt` which allows integer values greater than or equal to zero.+- Scalars `Minute`, `Hour` and `Day` now inherit from `NonNegativeInt`, which mean GraphQL disallows negative values for time units.### Webhooksdiff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex 01f9822751..ee7340448d 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -41,15 +41,6 @@ DELETE_EXPIRED_ORDERS_MAX_DAYS = 120def clean_expire_orders_after(expire_orders_after: int) -> int | None:if expire_orders_after is None or expire_orders_after == 0:return None- if expire_orders_after < 0:- raise ValidationError(- {- "expire_orders_after": ValidationError(- "Expiration time for orders cannot be lower than 0.",- code=ChannelErrorCode.INVALID.value,- )- }- )return expire_orders_after@@ -217,15 +208,6 @@ def clean_automatic_completion_delay(settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED.total_seconds() // 60)if delay is not None:- if delay < 0:- raise ValidationError(- {- "delay": ValidationError(- "The automatic completion delay must be greater than or equal to 0.",- code=ChannelErrorCode.INVALID.value,- )- }- )if delay >= oldest_allowed_checkout:raise ValidationError({diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.pyindex 7c09a9bbe6..8b43713171 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py@@ -16,7 +16,11 @@ from .....core.utils.json_serializer import CustomJsonEncoderfrom .....tax.models import TaxConfigurationfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.payloads import generate_meta, generate_requestor-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)from ...enums import (AllocationStrategyEnum,MarkAsPaidStrategyEnum,@@ -272,13 +276,17 @@ def test_channel_create_mutation_negative_expire_orders(CHANNEL_CREATE_MUTATION,variables=variables,permissions=(permission_manage_channels,),+ check_no_permissions=False,)# then- content = get_graphql_content(response)- error = content["data"]["channelCreate"]["errors"][0]- assert error["field"] == "expireOrdersAfter"- assert error["code"] == ChannelErrorCode.INVALID.name+ content = get_graphql_content_from_response(response)+ assert "errors" in content+ expected_msg = (+ 'In field "orderSettings": In field "expireOrdersAfter":'+ ' Expected type "Minute", found -1.'+ )+ assert expected_msg in content["errors"][0]["message"]def test_channel_create_draft_order_line_price_freeze_period_negative_value(@@ -309,13 +317,17 @@ def test_channel_create_draft_order_line_price_freeze_period_negative_value(CHANNEL_CREATE_MUTATION,variables=variables,permissions=(permission_manage_channels,),+ check_no_permissions=False,)# then- content = get_graphql_content(response)- error = content["data"]["channelCreate"]["errors"][0]- assert error["field"] == "draftOrderLinePriceFreezePeriod"- assert error["code"] == ChannelErrorCode.INVALID.name+ content = get_graphql_content_from_response(response)+ assert "errors" in content+ expected_msg_part = (+ 'In field "orderSettings": In field "draftOrderLinePriceFreezePeriod":'+ ' Expected type "Hour", found -1.'+ )+ assert expected_msg_part in content["errors"][0]["message"]@pytest.mark.parametrize("expire_input", [0, None])@@ -862,7 +874,44 @@ def test_channel_create_set_delete_expired_orders_after()[email protected]("delete_expired_after", [-1, 0, 121, 300])+def test_channel_create_mutation_negative_delete_expired_orders_after(+ permission_manage_channels,+ app_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "orderSettings": {"deleteExpiredOrdersAfter": -1},+ }+ }++ # when+ response = app_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content_from_response(response)+ assert "errors" in content+ expected_msg = (+ 'In field "orderSettings": In field "deleteExpiredOrdersAfter":'+ ' Expected type "Day", found -1.'+ )+ assert expected_msg in content["errors"][0]["message"]++[email protected]("delete_expired_after", [0, 121, 300])def test_channel_create_mutation_set_incorrect_delete_expired_orders_after(delete_expired_after, permission_manage_channels, staff_api_client, channel_USD):@@ -1054,13 +1103,17 @@ def test_channel_create_with_automatic_completion_delay_value_below_0(CHANNEL_CREATE_MUTATION,variables=variables,permissions=(permission_manage_channels,),+ check_no_permissions=False,)- content = get_graphql_content(response)+ content = get_graphql_content_from_response(response)# then- error = content["data"]["channelCreate"]["errors"][0]- assert error["field"] == "delay"- assert error["code"] == ChannelErrorCode.INVALID.name+ assert "errors" in content+ expected_msg = (+ 'In field "checkoutSettings": In field "automaticCompletion":'+ ' In field "delay": Expected type "Minute", found -1.'+ )+ assert expected_msg in content["errors"][0]["message"]def test_channel_create_with_delay_exceeding_threshold(diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex 1a0a7b8f7c..eebeb231fa 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -16,7 +16,11 @@ from .....discount.models import VoucherCodefrom .....order.models import Orderfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.payloads import generate_meta, generate_requestor-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)from ...enums import (AllocationStrategyEnum,MarkAsPaidStrategyEnum,@@ -877,13 +881,17 @@ def test_channel_update_mutation_negative_expire_orders(CHANNEL_UPDATE_MUTATION,variables=variables,permissions=(permission_manage_channels,),+ check_no_permissions=False,)# then- content = get_graphql_content(response)- error = content["data"]["channelUpdate"]["errors"][0]- assert error["field"] == "expireOrdersAfter"- assert error["code"] == ChannelErrorCode.INVALID.name+ content = get_graphql_content_from_response(response)+ assert "errors" in content+ expected_msg = (+ 'In field "orderSettings": In field "expireOrdersAfter":'+ ' Expected type "Minute", found -1.'+ )+ assert expected_msg in content["errors"][0]["message"]@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")@@ -1151,7 +1159,40 @@ def test_channel_update_delete_expired_orders_after()[email protected]("delete_expired_after", [-1, 0, 121, 300])+def test_channel_update_mutation_negative_delete_expired_orders_after(+ permission_manage_channels,+ app_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ variables = {+ "id": channel_id,+ "input": {+ "orderSettings": {"deleteExpiredOrdersAfter": -1},+ },+ }++ # when+ response = app_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content_from_response(response)+ assert "errors" in content+ expected_msg = (+ 'In field "orderSettings": In field "deleteExpiredOrdersAfter":'+ ' Expected type "Day", found -1.'+ )+ assert expected_msg in content["errors"][0]["message"]++[email protected]("delete_expired_after", [0, 121, 300])def test_channel_update_set_incorrect_delete_expired_orders_after(delete_expired_after,permission_manage_orders,@@ -1348,13 +1389,17 @@ def test_channel_update_draft_order_line_price_freeze_period_negative_value(CHANNEL_UPDATE_MUTATION,variables=variables,permissions=(permission_manage_orders,),+ check_no_permissions=False,)- content = get_graphql_content(response)+ content = get_graphql_content_from_response(response)# then- error = content["data"]["channelUpdate"]["errors"][0]- assert error["field"] == "draftOrderLinePriceFreezePeriod"- assert error["code"] == ChannelErrorCode.INVALID.name+ assert "errors" in content+ expected_msg = (+ 'In field "orderSettings": In field "draftOrderLinePriceFreezePeriod":'+ ' Expected type "Hour", found -5.'+ )+ assert expected_msg in content["errors"][0]["message"]CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """@@ -1614,13 +1659,17 @@ def test_channel_update_with_automatic_completion_delay_below_0(CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,variables=variables,permissions=(permission_manage_channels,),+ check_no_permissions=False,)- content = get_graphql_content(response)+ content = get_graphql_content_from_response(response)# then- error = content["data"]["channelUpdate"]["errors"][0]- assert error["field"] == "delay"- assert error["code"] == ChannelErrorCode.INVALID.name+ assert "errors" in content+ expected_msg = (+ 'In field "checkoutSettings": In field "automaticCompletion":'+ ' In field "delay": Expected type "Minute", found -1.'+ )+ assert expected_msg in content["errors"][0]["message"]def test_channel_update_with_delay_exceeding_threshold(diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.pyindex df029207f3..be1caa6046 100644--- a/saleor/graphql/core/scalars.py+++ b/saleor/graphql/core/scalars.py@@ -199,15 +199,40 @@ class Date(graphene.Date):return graphene.Date.parse_value(value)-class Minute(graphene.Int):+class NonNegativeInt(graphene.Int):+ """Non-negative Integer scalar implementation.++ Should be used in places where value must be non-negative (0 or greater).+ """++ @staticmethod+ def parse_value(value) -> int | None:+ parsed_value = graphene.Int.parse_value(value)++ if (parsed_value is not None) and parsed_value >= 0:+ return parsed_value++ return None++ @staticmethod+ def parse_literal(node) -> int | None:+ parsed_value = graphene.Int.parse_literal(node)++ if (parsed_value is not None) and parsed_value >= 0:+ return parsed_value++ return None+++class Minute(NonNegativeInt):"""The `Minute` scalar type represents number of minutes by integer value."""-class Hour(graphene.Int):+class Hour(NonNegativeInt):"""The `Hour` scalar type represents number of hours by integer value."""-class Day(graphene.Int):+class Day(NonNegativeInt):"""The `Day` scalar type represents number of days by integer value."""