Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Validate percentage discounted value for sale
Damian W5e343679a0ca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80ba5ef180..5218a8eee8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,7 +25,7 @@ All notable, unreleased changes to this project will be documented in this file.- Raise an error when the user is trying to sort products by rank without search - #7013 by @IKarbowiak- Fix available shipping methods - return also weight methods without weight limits - #7021 by @IKarbowiak- Remove redundant Opentracing spans - #6994 by @fowczarek-- Validate discount value for percentage vouchers - #7033 by @d-wysocki+- Validate discount value for percentage vouchers and sales - #7033 by @d-wysocki### Breaking- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysockidiff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.pyindex 42f7f759c2..381a884d45 100644--- a/saleor/graphql/discount/mutations.py+++ b/saleor/graphql/discount/mutations.py@@ -318,13 +318,7 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):error_type_field = "discount_errors"@classmethod- def clean_discount_values_per_channel(cls, cleaned_input, voucher, error_lists):- (- channels_without_value,- channels_with_invalid_value_precision,- channels_with_invalid_percentage_value,- channels_with_invalid_min_amount_spent_precision,- ) = error_lists+ def clean_discount_values_per_channel(cls, cleaned_input, voucher, error_dict):channel_slugs_assigned_to_voucher = voucher.channel_listings.values_list("channel__slug", flat=True)@@ -340,49 +334,46 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):should_create = channel.slug not in channel_slugs_assigned_to_vouchermissing_required_value = not discount_value and should_createif missing_required_value or discount_value is None:- channels_without_value.append(cleaned_channel["channel_id"])+ error_dict["channels_without_value"].append(+ cleaned_channel["channel_id"]+ )# Validate value precision if it is fixed amount voucherif voucher.discount_value_type == DiscountValueType.FIXED:try:validate_price_precision(discount_value, channel.currency_code)except ValidationError:- channels_with_invalid_value_precision.append(+ error_dict["channels_with_invalid_value_precision"].append(cleaned_channel["channel_id"])- if voucher.discount_value_type == DiscountValueType.PERCENTAGE:+ elif voucher.discount_value_type == DiscountValueType.PERCENTAGE:if discount_value > 100:- channels_with_invalid_percentage_value.append(+ error_dict["channels_with_invalid_percentage_value"].append(cleaned_channel["channel_id"])- cleaned_channel["discount_value"] = discount_valuemin_amount_spent = cleaned_channel.get("min_amount_spent", None)if min_amount_spent:try:validate_price_precision(min_amount_spent, channel.currency_code)except ValidationError:- channels_with_invalid_min_amount_spent_precision.append(- cleaned_channel["channel_id"]- )+ error_dict[+ "channels_with_invalid_min_amount_spent_precision"+ ].append(cleaned_channel["channel_id"])@classmethoddef clean_discount_values(cls, cleaned_input, voucher, errors):- channels_without_value = []- channels_with_invalid_value_precision = []- channels_with_invalid_percentage_value = []- channels_with_invalid_min_amount_spent_precision = []- error_lists = (- channels_without_value,- channels_with_invalid_value_precision,- channels_with_invalid_percentage_value,- channels_with_invalid_min_amount_spent_precision,- )+ error_dict = {+ "channels_without_value": [],+ "channels_with_invalid_value_precision": [],+ "channels_with_invalid_percentage_value": [],+ "channels_with_invalid_min_amount_spent_precision": [],+ }cls.clean_discount_values_per_channel(cleaned_input,voucher,- error_lists,+ error_dict,)-+ channels_without_value = error_dict["channels_without_value"]if channels_without_value:errors["discount_value"].append(ValidationError(@@ -392,6 +383,9 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):))+ channels_with_invalid_value_precision = error_dict[+ "channels_with_invalid_value_precision"+ ]if channels_with_invalid_value_precision:errors["discount_value"].append(ValidationError(@@ -400,6 +394,10 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):params={"channels": channels_with_invalid_value_precision},))++ channels_with_invalid_percentage_value = error_dict[+ "channels_with_invalid_percentage_value"+ ]if channels_with_invalid_percentage_value:errors["discount_value"].append(ValidationError(@@ -408,6 +406,10 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):params={"channels": channels_with_invalid_percentage_value},))++ channels_with_invalid_min_amount_spent_precision = error_dict[+ "channels_with_invalid_min_amount_spent_precision"+ ]if channels_with_invalid_min_amount_spent_precision:errors["min_amount_spent"].append(ValidationError(@@ -639,28 +641,42 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):)@classmethod- def clean_prices(cls, cleaned_channels, sale_type, errors, error_code):- if sale_type != DiscountValueType.FIXED:- return cleaned_channels-- invalid_channels_ids = []- error_message = None+ def clean_discount_values(cls, cleaned_channels, sale_type, errors, error_code):+ channels_with_invalid_value_precision = []+ channels_with_invalid_percentage_value = []for cleaned_channel in cleaned_channels.get("add_channels", []):channel = cleaned_channel["channel"]currency_code = channel.currency_codediscount_value = cleaned_channel.get("discount_value")- if discount_value:+ if not discount_value:+ continue+ if sale_type == DiscountValueType.FIXED:try:validate_price_precision(discount_value, currency_code)- except ValidationError as error:- error_message = error.message- invalid_channels_ids.append(cleaned_channel["channel_id"])- if invalid_channels_ids and error_message:+ except ValidationError:+ channels_with_invalid_value_precision.append(+ cleaned_channel["channel_id"]+ )+ elif sale_type == DiscountValueType.PERCENTAGE:+ if discount_value > 100:+ channels_with_invalid_percentage_value.append(+ cleaned_channel["channel_id"]+ )++ if channels_with_invalid_value_precision:errors["input"].append(ValidationError(- error_message,+ "Invalid amount precision.",code=error_code,- params={"channels": invalid_channels_ids},+ params={"channels": channels_with_invalid_value_precision},+ )+ )+ if channels_with_invalid_percentage_value:+ errors["input"].append(+ ValidationError(+ "Invalid percentage value.",+ code=error_code,+ params={"channels": channels_with_invalid_percentage_value},))return cleaned_channels@@ -683,7 +699,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):cleaned_channels = cls.clean_channels(info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value)- cleaned_input = cls.clean_prices(+ cleaned_input = cls.clean_discount_values(cleaned_channels, sale.type, errors, DiscountErrorCode.INVALID.value)diff --git a/saleor/graphql/discount/tests/test_sale_channel_listing.py b/saleor/graphql/discount/tests/test_sale_channel_listing.pyindex 3d9605f1d2..8f05a17a7c 100644--- a/saleor/graphql/discount/tests/test_sale_channel_listing.py+++ b/saleor/graphql/discount/tests/test_sale_channel_listing.py@@ -2,6 +2,7 @@ from unittest.mock import patchimport graphene+from ....discount import DiscountValueTypefrom ....discount.error_codes import DiscountErrorCodefrom ....discount.models import SaleChannelListingfrom ...tests.utils import assert_negative_positive_decimal_value, get_graphql_content@@ -280,3 +281,36 @@ def test_sale_channel_listing_update_with_invalid_decimal_places(assert errors[0]["code"] == DiscountErrorCode.INVALID.nameassert errors[0]["field"] == "input"assert errors[0]["channels"] == [channel_id]+++def test_sale_channel_listing_update_with_invalid_percentage_value(+ staff_api_client, sale, permission_manage_discounts, channel_USD+):+ # given+ sale = sale+ sale.type = DiscountValueType.PERCENTAGE+ sale.save()+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ discounted = 101+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": sale_id,+ "input": {+ "addChannels": [{"channelId": channel_id, "discountValue": discounted}],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_discounts,),+ )+ content = get_graphql_content(response)+ # then+ errors = content["data"]["saleChannelListingUpdate"]["discountErrors"]++ assert len(errors) == 1+ assert errors[0]["code"] == DiscountErrorCode.INVALID.name+ assert errors[0]["field"] == "input"+ assert errors[0]["channels"] == [channel_id]