Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add validation for tax data (#16720)
Piotr Zabieglikadeb61dc8469
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa9e3aced1..edb7127674 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,3 +27,4 @@ All notable, unreleased changes to this project will be documented in this file.- Add slugs to product/category/collection/page translations. Allow to query by translated slug - #16449 by @delemeator- Fixed a crash when the Decimal scalar is passed a non-normal value - #16520 by @patrys- Fixed a bug when saving webhook payload to Azure Storage - #16585 by @delemeator+- Added validation for tax data received from tax app - #16720 by @zedziordiff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 692d1fc391..2bab750555 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -10,7 +10,13 @@ from prices import Money, TaxedMoneyfrom ..checkout import base_calculationsfrom ..core.db.connection import allow_writerfrom ..core.prices import quantize_price-from ..core.taxes import TaxData, TaxEmptyData, zero_money, zero_taxed_money+from ..core.taxes import (+ TaxData,+ TaxDataError,+ TaxDataErrorMessage,+ zero_money,+ zero_taxed_money,+)from ..discount.utils.checkout import (create_or_update_discount_objects_from_promotion_for_checkout,)@@ -23,6 +29,7 @@ from ..tax.utils import (get_tax_app_identifier_for_checkout,get_tax_calculation_strategy_for_checkout,normalize_tax_rate_for_db,+ validate_tax_data,)from .fetch import find_checkout_line_infofrom .models import Checkout@@ -264,6 +271,8 @@ def _fetch_checkout_prices_if_expired(Prices can be updated only if force_update == True, or if time elapsed from thelast price update is greater than settings.CHECKOUT_PRICES_TTL."""+ from .utils import checkout_info_for_logs+if pregenerated_subscription_payloads is None:pregenerated_subscription_payloads = {}@@ -307,7 +316,11 @@ def _fetch_checkout_prices_if_expired(database_connection_name=database_connection_name,pregenerated_subscription_payloads=pregenerated_subscription_payloads,)- except TaxEmptyData as e:+ except TaxDataError as e:+ if str(e) != TaxDataErrorMessage.EMPTY:+ logger.warning(+ str(e), extra=checkout_info_for_logs(checkout_info, lines)+ )_set_checkout_base_prices(checkout, checkout_info, lines)checkout.tax_error = str(e)@@ -334,7 +347,11 @@ def _fetch_checkout_prices_if_expired(database_connection_name=database_connection_name,pregenerated_subscription_payloads=pregenerated_subscription_payloads,)- except TaxEmptyData as e:+ except TaxDataError as e:+ if str(e) != TaxDataErrorMessage.EMPTY:+ logger.warning(+ str(e), extra=checkout_info_for_logs(checkout_info, lines)+ )_set_checkout_base_prices(checkout, checkout_info, lines)checkout.tax_error = str(e)else:@@ -411,6 +428,7 @@ def _calculate_and_add_tax()if not tax_data:log_address_if_validation_skipped_for_checkout(checkout_info, logger)+ validate_tax_data(tax_data, lines, allow_empty_tax_data=True)_apply_tax_data(checkout, lines, tax_data)else:_call_plugin_or_tax_app(@@ -456,7 +474,7 @@ def _call_plugin_or_tax_app(plugin_ids=plugin_ids,)if not plugins:- raise TaxEmptyData("Empty tax data.")+ raise TaxDataError(TaxDataErrorMessage.EMPTY)_apply_tax_data_from_plugins(checkout,manager,@@ -466,7 +484,7 @@ def _call_plugin_or_tax_app(plugin_ids=plugin_ids,)if checkout.tax_error:- raise TaxEmptyData("Empty tax data.")+ raise TaxDataError(checkout.tax_error)else:tax_data = manager.get_taxes_for_checkout(checkout_info,@@ -476,7 +494,7 @@ def _call_plugin_or_tax_app()if tax_data is None:log_address_if_validation_skipped_for_checkout(checkout_info, logger)- raise TaxEmptyData("Empty tax data.")+ validate_tax_data(tax_data, lines)_apply_tax_data(checkout, lines, tax_data)diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.pyindex 34607390eb..d4ebd1bfec 100644--- a/saleor/checkout/tests/test_calculations.py+++ b/saleor/checkout/tests/test_calculations.py@@ -11,8 +11,16 @@ from prices import Money, TaxedMoneyfrom ...checkout.utils import add_promo_code_to_checkout, set_external_shipping_idfrom ...core.prices import quantize_price-from ...core.taxes import TaxData, TaxLineData, zero_taxed_money+from ...core.taxes import (+ TaxData,+ TaxDataErrorMessage,+ TaxLineData,+ zero_taxed_money,+)+from ...graphql.core.utils import to_global_id_or_nonefrom ...plugins import PLUGIN_IDENTIFIER_PREFIX+from ...plugins.avatax.plugin import AvataxPlugin+from ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401from ...plugins.manager import get_plugins_managerfrom ...plugins.tests.sample_plugins import PluginSamplefrom ...tax import TaxCalculationStrategy@@ -568,6 +576,7 @@ def test_fetch_checkout_data_calls_plugin(@freeze_time()+@patch("saleor.checkout.calculations.validate_tax_data")@patch("saleor.plugins.manager.PluginsManager.calculate_checkout_total")@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_checkout")@patch("saleor.checkout.calculations._apply_tax_data")@@ -576,10 +585,13 @@ def test_fetch_checkout_data_calls_tax_app(mock_apply_tax_data,mock_get_taxes,mock_calculate_checkout_total,+ mock_validate_tax_data,fetch_kwargs,checkout_with_items,):# given+ mock_validate_tax_data.return_value = False+checkout = checkout_with_itemscheckout.price_expiration = timezone.now()checkout.save()@@ -752,3 +764,370 @@ def test_calculate_and_add_tax_empty_tax_data_logging_address(f"Fetching tax data for checkout with address validation skipped. "f"Address ID: {address.pk}" in caplog.text)+++ ("prices_entered_with_tax", "tax_app_id"),+ [(True, None), (True, "test.app"), (False, None), (False, "test.app")],+)+@patch("saleor.checkout.calculations._set_checkout_base_prices")+def test_fetch_checkout_data_tax_data_with_negative_values(+ mock_set_base_prices,+ prices_entered_with_tax,+ tax_app_id,+ checkout_with_single_item,+ caplog,+):+ # given+ checkout = checkout_with_single_item++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = tax_app_id+ channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.save()++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("-3"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ zero_money = zero_taxed_money(checkout.currency)+ manager_methods = {+ "calculate_checkout_total": Mock(return_value=zero_money),+ "calculate_checkout_subtotal": Mock(return_value=zero_money),+ "calculate_checkout_line_total": Mock(return_value=zero_money),+ "calculate_checkout_shipping": Mock(return_value=zero_money),+ "get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_taxes_for_checkout": Mock(return_value=tax_data),+ }+ manager = Mock(**manager_methods)++ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout_info.checkout.tax_error == TaxDataErrorMessage.NEGATIVE_VALUE+ assert TaxDataErrorMessage.NEGATIVE_VALUE in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++ ("prices_entered_with_tax", "tax_app_id"),+ [(True, None), (True, "test.app"), (False, None), (False, "test.app")],+)+@patch("saleor.checkout.calculations._set_checkout_base_prices")+def test_fetch_checkout_data_tax_data_with_wrong_number_of_lines(+ mock_set_base_prices,+ prices_entered_with_tax,+ tax_app_id,+ checkout_with_single_item,+ caplog,+):+ # given+ checkout = checkout_with_single_item++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = tax_app_id+ channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.save()++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ TaxLineData(+ total_net_amount=Decimal("4"),+ total_gross_amount=Decimal("6"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ zero_money = zero_taxed_money(checkout.currency)+ manager_methods = {+ "calculate_checkout_total": Mock(return_value=zero_money),+ "calculate_checkout_subtotal": Mock(return_value=zero_money),+ "calculate_checkout_line_total": Mock(return_value=zero_money),+ "calculate_checkout_shipping": Mock(return_value=zero_money),+ "get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_taxes_for_checkout": Mock(return_value=tax_data),+ }+ manager = Mock(**manager_methods)++ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout_info.checkout.tax_error == TaxDataErrorMessage.LINE_NUMBER+ assert TaxDataErrorMessage.LINE_NUMBER in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++ ("prices_entered_with_tax", "tax_app_id"),+ [(True, None), (True, "test.app"), (False, None), (False, "test.app")],+)+@patch("saleor.checkout.calculations._set_checkout_base_prices")+def test_fetch_checkout_data_tax_data_with_price_overflow(+ mock_set_base_prices,+ prices_entered_with_tax,+ tax_app_id,+ checkout_with_single_item,+ caplog,+):+ # given+ checkout = checkout_with_single_item++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = tax_app_id+ channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.save()++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("120"),+ ),+ ],+ )++ zero_money = zero_taxed_money(checkout.currency)+ manager_methods = {+ "calculate_checkout_total": Mock(return_value=zero_money),+ "calculate_checkout_subtotal": Mock(return_value=zero_money),+ "calculate_checkout_line_total": Mock(return_value=zero_money),+ "calculate_checkout_shipping": Mock(return_value=zero_money),+ "get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_taxes_for_checkout": Mock(return_value=tax_data),+ }+ manager = Mock(**manager_methods)++ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout_info.checkout.tax_error == TaxDataErrorMessage.OVERFLOW+ assert TaxDataErrorMessage.OVERFLOW in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++@patch("saleor.plugins.avatax.plugin.get_checkout_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_with_negative_values(+ mock_get_tax_data,+ checkout_with_item_and_shipping,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ checkout = checkout_with_item_and_shipping++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": -8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)+ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout.tax_error == TaxDataErrorMessage.NEGATIVE_VALUE+ assert TaxDataErrorMessage.NEGATIVE_VALUE in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++@patch("saleor.plugins.avatax.plugin.get_checkout_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_with_wrong_number_of_lines(+ mock_get_tax_data,+ checkout_with_item_and_shipping,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ checkout = checkout_with_item_and_shipping++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 40.0000,+ "quantity": 2.0,+ "itemCode": "SKU_B",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)+ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout.tax_error == TaxDataErrorMessage.LINE_NUMBER+ assert TaxDataErrorMessage.LINE_NUMBER in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++@patch("saleor.plugins.avatax.plugin.get_checkout_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_with_wrong_number_of_lines_no_shipping(+ mock_get_tax_data,+ checkout_with_item_and_shipping,+ caplog,+ plugin_configuration, # noqa: F811+ product_type,+):+ # given+ checkout = checkout_with_item_and_shipping+ product_type.is_shipping_required = False+ product_type.save(update_fields=["is_shipping_required"])++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)+ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ for line in checkout_lines_info:+ line.product_type++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout.tax_error == TaxDataErrorMessage.LINE_NUMBER+ assert TaxDataErrorMessage.LINE_NUMBER in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++@patch("saleor.plugins.avatax.plugin.get_checkout_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_price_overflow(+ mock_get_tax_data,+ checkout_with_item_and_shipping,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ checkout = checkout_with_item_and_shipping++ channel = checkout.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 3892370265647658029.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)+ checkout_lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)++ # when+ fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)++ # then+ assert checkout.tax_error == TaxDataErrorMessage.OVERFLOW+ assert TaxDataErrorMessage.OVERFLOW in caplog.text+ assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)diff --git a/saleor/checkout/tests/test_utils.py b/saleor/checkout/tests/test_utils.pyindex 673431b6ab..543b20b75e 100644--- a/saleor/checkout/tests/test_utils.py+++ b/saleor/checkout/tests/test_utils.py@@ -1,9 +1,12 @@from decimal import Decimal+import grapheneimport pytestfrom prices import Money, TaxedMoney+from ...discount import DiscountType, DiscountValueTypefrom ...tax.calculations import get_taxed_undiscounted_price+from ..utils import checkout_info_for_logsBASE = Money("35.00", "USD")@@ -50,3 +53,39 @@ def test_get_taxed_undiscounted_price(price, tax_rate, prices_entered_with_tax,)assert result_price == result+++def test_checkout_info_for_logs(checkout_info, voucher, order_promotion_with_rule):+ # given+ checkout = checkout_info.checkout+ voucher_code = voucher.codes.first().code+ checkout.voucher_code = voucher_code++ checkout_discount = checkout.discounts.create(+ type=DiscountType.ORDER_PROMOTION,+ value_type=DiscountValueType.FIXED,+ value=Decimal(5),+ amount_value=Decimal(5),+ promotion_rule=order_promotion_with_rule.rules.first(),+ currency=checkout.currency,+ )+ checkout_info.discounts = [checkout_discount]++ lines_info = checkout_info.lines+ line_discount = lines_info[0].line.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=Decimal(5),+ currency=checkout.currency,+ amount_value=Decimal(5),+ voucher=voucher,+ )+ lines_info[0].discounts = [line_discount]++ # when+ extra = checkout_info_for_logs(checkout_info, lines_info)++ # then+ assert extra["checkout_id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ assert extra["discounts"]+ assert extra["lines"][0]["discounts"]diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex fe12776921..4d42016df4 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -39,6 +39,7 @@ from ..discount.utils.checkout import (from ..discount.utils.promotion import (delete_gift_line,)+from ..discount.utils.shared import discount_info_for_logsfrom ..discount.utils.voucher import (get_discounted_lines,get_products_voucher_discount,@@ -1070,3 +1071,63 @@ def get_address_for_checkout_taxes() -> Optional["Address"]:shipping_address = checkout_info.delivery_method_info.shipping_addressreturn shipping_address or checkout_info.billing_address+++def checkout_info_for_logs(+ checkout_info: "CheckoutInfo",+ checkout_lines_info: Iterable["CheckoutLineInfo"],+):+ checkout = checkout_info.checkout+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ tax_configuration = checkout_info.tax_configuration+ channel = checkout.channel++ return {+ "checkout_id": checkout_id,+ "checkoutId": checkout_id,+ "checkout": {+ "currency": checkout.currency,+ "total_net_amount": checkout.total_net_amount,+ "total_gross_amount": checkout.total_gross_amount,+ "base_total_amount": checkout.base_total_amount,+ "subtotal_net_amount": checkout.subtotal_net_amount,+ "subtotal_gross_amount": checkout.subtotal_gross_amount,+ "base_subtotal_amount": checkout.base_subtotal_amount,+ "shipping_price_net_amount": checkout.shipping_price_net_amount,+ "shipping_price_gross_amount": checkout.shipping_price_gross_amount,+ "discount_amount": checkout.discount_amount,+ "has_voucher_code": bool(checkout.voucher_code),+ "tax_exemption": checkout.tax_exemption,+ "tax_error": checkout.tax_error,+ },+ "tax_configuration": {+ "charge_taxes": tax_configuration.charge_taxes,+ "tax_calculation_strategy": tax_configuration.tax_calculation_strategy,+ "prices_entered_with_tax": tax_configuration.prices_entered_with_tax,+ "tax_app_id": tax_configuration.tax_app_id,+ },+ "discounts": discount_info_for_logs(checkout_info.discounts),+ "lines": [+ {+ "id": graphene.Node.to_global_id("CheckoutLine", line_info.line.pk),+ "variant_id": graphene.Node.to_global_id(+ "ProductVariant", line_info.line.variant_id+ ),+ "quantity": line_info.line.quantity,+ "is_gift": line_info.line.is_gift,+ "price_override": line_info.line.price_override,+ "total_price_net_amount": line_info.line.total_price_net_amount,+ "total_price_gross_amount": line_info.line.total_price_gross_amount,+ "variant_listing_price": line_info.channel_listing.price_amount,+ "variant_listing_discounted_price": line_info.channel_listing.discounted_price_amount,+ "product_listing_discounted_price": line_info.product.channel_listings.get(+ channel=channel+ ).discounted_price_amount,+ "product_discounted_price_dirty": line_info.product.channel_listings.get(+ channel=channel+ ).discounted_price_dirty,+ "discounts": discount_info_for_logs(line_info.discounts),+ }+ for line_info in checkout_lines_info+ ],+ }diff --git a/saleor/core/prices.py b/saleor/core/prices.pyindex b8be0d03d5..0271152ecc 100644--- a/saleor/core/prices.py+++ b/saleor/core/prices.py@@ -5,11 +5,18 @@ from typing import TYPE_CHECKING, TypeVarfrom babel.numbers import get_currency_precisionfrom prices import Money, TaxedMoney, TaxedMoneyRange+from saleor import settings+if TYPE_CHECKING:from django.db.models import ModelPriceType = TypeVar("PriceType", TaxedMoney, Money, Decimal, TaxedMoneyRange)+# The maximum price value we can save in the database+MAXIMUM_PRICE = (+ 10 ** (settings.DEFAULT_MAX_DIGITS - settings.DEFAULT_DECIMAL_PLACES) - 1+)+def quantize_price(price: PriceType, currency: str) -> PriceType:precision = get_currency_precision(currency)diff --git a/saleor/core/taxes.py b/saleor/core/taxes.pyindex ba802c158c..1fd5593a1f 100644--- a/saleor/core/taxes.py+++ b/saleor/core/taxes.py@@ -8,8 +8,8 @@ class TaxError(Exception):"""Default tax error."""-class TaxEmptyData(Exception):- """Empty tax data received from Tax App error."""+class TaxDataError(Exception):+ """Error in tax data received from tax app or plugin."""def zero_money(currency: str) -> Money:@@ -46,3 +46,12 @@ class TaxData:shipping_price_net_amount: Decimalshipping_tax_rate: Decimallines: list[TaxLineData]+++class TaxDataErrorMessage:+ EMPTY = "Empty tax data."+ NEGATIVE_VALUE = "Tax data contains negative values."+ LINE_NUMBER = (+ "Number of lines from tax data doesn't match the line number from order."+ )+ OVERFLOW = "Tax data contains prices exceeding a billion or tax rate over 100%."diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.pyindex eb29f12968..3ea7466cc5 100644--- a/saleor/discount/tests/test_discounts.py+++ b/saleor/discount/tests/test_discounts.py@@ -8,7 +8,8 @@ from prices import Money, TaxedMoneyfrom ...checkout.fetch import CheckoutLineInfofrom ...discount.interface import VariantPromotionRuleInfo-from .. import DiscountValueType, RewardValueType, VoucherType+from ...order import OrderStatus+from .. import DiscountType, DiscountValueType, RewardValueType, VoucherTypefrom ..models import (NotApplicable,Voucher,@@ -21,6 +22,7 @@ from ..utils.promotion import (get_discount_name,get_discount_translated_name,)+from ..utils.shared import discount_info_for_logsfrom ..utils.voucher import (_get_the_cheapest_line,activate_voucher_code,@@ -725,3 +727,54 @@ def test_split_manual_discount(# thenassert subtotal_discount == Money(subtotal_portion, "USD")assert shipping_discount == Money(shipping_portion, "USD")+++def test_discount_info_for_logs(order_with_lines, voucher, order_promotion_with_rule):+ # given+ order = order_with_lines+ promotion = order_promotion_with_rule+ rule = promotion.rules.first()+ voucher_code = voucher.codes.first().code+ order.voucher_code = voucher_code+ order.voucher = voucher+ order.status = OrderStatus.DRAFT+ order.save(update_fields=["voucher_code", "voucher_id", "status"])++ order_discount = order.discounts.create(+ type=DiscountType.ORDER_PROMOTION,+ value_type=DiscountValueType.FIXED,+ value=Decimal(5),+ amount_value=Decimal(5),+ promotion_rule=order_promotion_with_rule.rules.first(),+ currency=order.currency,+ )++ lines = order.lines.all()+ line_discount = lines[0].discounts.create(+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=Decimal(5),+ currency=order.currency,+ amount_value=Decimal(5),+ voucher=voucher,+ )++ # when+ extra = discount_info_for_logs([order_discount, line_discount])++ # then+ assert extra[0]["id"] == graphene.Node.to_global_id(+ "OrderDiscount", order_discount.pk+ )+ assert extra[0]["promotion_rule"]["id"] == graphene.Node.to_global_id(+ "PromotionRule", rule.pk+ )+ assert extra[0]["promotion_rule"]["promotion_id"] == graphene.Node.to_global_id(+ "Promotion", promotion.pk+ )+ assert extra[1]["id"] == graphene.Node.to_global_id(+ "OrderLineDiscount", line_discount.pk+ )+ assert extra[1]["voucher"]["id"] == graphene.Node.to_global_id(+ "Voucher", voucher.pk+ )diff --git a/saleor/discount/utils/shared.py b/saleor/discount/utils/shared.pyindex bbd6504a62..4c26d5a017 100644--- a/saleor/discount/utils/shared.py+++ b/saleor/discount/utils/shared.py@@ -2,6 +2,9 @@ from collections import defaultdictfrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional, Union+import graphene++from ...graphql.core.utils import to_global_id_or_nonefrom .. import DiscountTypefrom ..models import (CheckoutDiscount,@@ -92,3 +95,39 @@ def is_order_level_discount(discount: OrderDiscount) -> bool:DiscountType.MANUAL,DiscountType.ORDER_PROMOTION,] or is_order_level_voucher(discount.voucher)+++def discount_info_for_logs(discounts):+ return [+ {+ "id": to_global_id_or_none(discount),+ "type": discount.type,+ "value_type": discount.value_type,+ "value": discount.value,+ "amount_value": discount.amount_value,+ "reason": discount.reason,+ "promotion_rule": {+ "id": to_global_id_or_none(discount.promotion_rule),+ "promotion_id": graphene.Node.to_global_id(+ "Promotion", discount.promotion_rule.promotion_id+ ),+ "catalogue_predicate": discount.promotion_rule.catalogue_predicate,+ "order_predicate": discount.promotion_rule.order_predicate,+ "reward_value_type": discount.promotion_rule.reward_value_type,+ "reward_value": discount.promotion_rule.reward_value,+ "reward_type": discount.promotion_rule.reward_type,+ "variants_dirty": discount.promotion_rule.variants_dirty,+ }+ if discount.promotion_rule+ else None,+ "voucher": {+ "id": to_global_id_or_none(discount.voucher),+ "type": discount.voucher.type,+ "discount_value_type": discount.voucher.discount_value_type,+ "apply_once_per_order": discount.voucher.apply_once_per_order,+ }+ if discount.voucher+ else None,+ }+ for discount in discounts+ ]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 9c3f95f38f..17a7835100 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -438,9 +438,11 @@ def test_checkout_complete_fails_with_invalid_tax_app(@freeze_time()@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.checkout.calculations.validate_tax_data")@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")def test_checkout_complete_calls_correct_tax_app(mock_request,+ mock_validate_tax_data,user_api_client,checkout_without_shipping_required,channel_USD,@@ -451,7 +453,7 @@ def test_checkout_complete_calls_correct_tax_app():# givenmock_request.return_value = tax_data_response-+ mock_validate_tax_data.return_value = Falsecheckout = checkout_without_shipping_requiredcheckout.billing_address = addresscheckout.price_expiration = timezone.now()@@ -501,9 +503,11 @@ def test_checkout_complete_calls_failing_plugin(settings,):# given+ tax_error_message = "Test error"+def side_effect(checkout_info, *args, **kwargs):price = Money("10.0", checkout_info.checkout.currency)- checkout_info.checkout.tax_error = "Test error"+ checkout_info.checkout.tax_error = tax_error_messagereturn TaxedMoney(price, price)mock_calculate_checkout_line_total.side_effect = side_effect@@ -540,14 +544,16 @@ def test_checkout_complete_calls_failing_plugin(checkout.refresh_from_db()assert checkout.price_expiration == timezone.now() + settings.CHECKOUT_PRICES_TTL- assert checkout.tax_error == "Empty tax data."+ assert checkout.tax_error == tax_error_message@freeze_time()@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.checkout.calculations.validate_tax_data")@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")def test_checkout_complete_calls_correct_force_tax_calculation_when_tax_error_was_saved(mock_request,+ mock_validate_tax_data,user_api_client,checkout_without_shipping_required,channel_USD,@@ -558,6 +564,7 @@ def test_checkout_complete_calls_correct_force_tax_calculation_when_tax_error_wa):# givenmock_request.return_value = tax_data_response+ mock_validate_tax_data.return_value = Falsecheckout = checkout_without_shipping_requiredcheckout.billing_address = addressdiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 8886288d5b..9808026c32 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -1113,9 +1113,11 @@ def test_draft_order_complete_fails_with_invalid_tax_app(@freeze_time()@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+@patch("saleor.order.calculations.validate_tax_data")@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")def test_draft_order_complete_force_tax_calculation_when_tax_error_was_saved(mock_request,+ mock_validate_tax_data,staff_api_client,permission_group_manage_orders,draft_order,@@ -1125,6 +1127,7 @@ def test_draft_order_complete_force_tax_calculation_when_tax_error_was_saved():# givenmock_request.return_value = tax_data_response+ mock_validate_tax_data.return_value = Falsepermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_order@@ -1158,9 +1161,11 @@ def test_draft_order_complete_force_tax_calculation_when_tax_error_was_saved(@freeze_time()@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+@patch("saleor.order.calculations.validate_tax_data")@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")def test_draft_order_complete_calls_correct_tax_app(mock_request,+ mock_validate_tax_data,staff_api_client,permission_group_manage_orders,draft_order,@@ -1170,6 +1175,7 @@ def test_draft_order_complete_calls_correct_tax_app():# givenmock_request.return_value = tax_data_response+ mock_validate_tax_data.return_value = Falsepermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_order@@ -1211,9 +1217,11 @@ def test_draft_order_complete_calls_failing_plugin(channel_USD,):# given+ tax_error_message = "Test error"+def side_effect(order, *args, **kwargs):price = Money("10.0", order.currency)- order.tax_error = "Test error"+ order.tax_error = tax_error_messagereturn OrderTaxedPricesData(price_with_discounts=TaxedMoney(price, price),undiscounted_price=TaxedMoney(price, price),@@ -1247,7 +1255,7 @@ def test_draft_order_complete_calls_failing_plugin(order.refresh_from_db()assert not order.should_refresh_prices- assert order.tax_error == "Empty tax data."+ assert order.tax_error == tax_error_messageDRAFT_ORDER_COMPLETE_WITH_DISCOUNTS_MUTATION = """diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 67f1872c9b..318f8bb9cb 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -10,7 +10,13 @@ from prices import Money, TaxedMoneyfrom ..core.db.connection import allow_writerfrom ..core.prices import quantize_price-from ..core.taxes import TaxData, TaxEmptyData, TaxError, zero_taxed_money+from ..core.taxes import (+ TaxData,+ TaxDataError,+ TaxDataErrorMessage,+ TaxError,+ zero_taxed_money,+)from ..discount.utils.order import create_or_update_discount_objects_for_orderfrom ..payment.model_helpers import get_subtotalfrom ..plugins import PLUGIN_IDENTIFIER_PREFIX@@ -23,13 +29,14 @@ from ..tax.utils import (get_tax_app_identifier_for_order,get_tax_calculation_strategy_for_order,normalize_tax_rate_for_db,+ validate_tax_data,)from . import ORDER_EDITABLE_STATUSfrom .base_calculations import apply_order_discounts, base_order_line_totalfrom .fetch import EditableOrderLineInfo, fetch_draft_order_lines_infofrom .interface import OrderTaxedPricesDatafrom .models import Order, OrderLine-from .utils import log_address_if_validation_skipped_for_order+from .utils import log_address_if_validation_skipped_for_order, order_info_for_logslogger = logging.getLogger(__name__)@@ -161,7 +168,9 @@ def _recalculate_prices(prices_entered_with_tax,database_connection_name=database_connection_name,)- except TaxEmptyData as e:+ except TaxDataError as e:+ if str(e) != TaxDataErrorMessage.EMPTY:+ logger.warning(str(e), extra=order_info_for_logs(order, lines))order.tax_error = str(e)if not should_charge_tax:@@ -184,7 +193,9 @@ def _recalculate_prices(prices_entered_with_tax,database_connection_name=database_connection_name,)- except TaxEmptyData as e:+ except TaxDataError as e:+ if str(e) != TaxDataErrorMessage.EMPTY:+ logger.warning(str(e), extra=order_info_for_logs(order, lines))order.tax_error = str(e)else:_remove_tax(order, lines)@@ -210,6 +221,7 @@ def _calculate_and_add_tax(tax_data = manager.get_taxes_for_order(order, tax_app_identifier)if not tax_data:log_address_if_validation_skipped_for_order(order, logger)+ validate_tax_data(tax_data, lines, allow_empty_tax_data=True)_apply_tax_data(order, lines, tax_data, prices_entered_with_tax)else:_call_plugin_or_tax_app(@@ -242,7 +254,7 @@ def _call_plugin_or_tax_app(order.channel.slug, active_only=True, plugin_ids=plugin_ids)if not plugins:- raise TaxEmptyData("Empty tax data.")+ raise TaxDataError(TaxDataErrorMessage.EMPTY)_recalculate_with_plugins(manager,order,@@ -251,12 +263,12 @@ def _call_plugin_or_tax_app(plugin_ids=plugin_ids,)if order.tax_error:- raise TaxEmptyData("Empty tax data.")+ raise TaxDataError(order.tax_error)else:tax_data = manager.get_taxes_for_order(order, tax_app_identifier)if tax_data is None:log_address_if_validation_skipped_for_order(order, logger)- raise TaxEmptyData("Empty tax data.")+ validate_tax_data(tax_data, lines)_apply_tax_data(order, lines, tax_data, prices_entered_with_tax)diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex 8185453788..f3531f9f02 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -7,15 +7,25 @@ from django.test import override_settingsfrom prices import Money, TaxedMoneyfrom ...core.prices import quantize_price-from ...core.taxes import TaxData, TaxError, TaxLineData, zero_taxed_money+from ...core.taxes import (+ TaxData,+ TaxDataErrorMessage,+ TaxError,+ TaxLineData,+ zero_taxed_money,+)from ...discount import DiscountValueType+from ...graphql.core.utils import to_global_id_or_nonefrom ...plugins import PLUGIN_IDENTIFIER_PREFIX+from ...plugins.avatax.plugin import AvataxPlugin+from ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401from ...plugins.manager import get_plugins_managerfrom ...plugins.tests.sample_plugins import PluginSamplefrom ...tax import TaxCalculationStrategyfrom ...tax.calculations.order import update_order_prices_with_flat_ratesfrom .. import OrderStatus, calculationsfrom ..interface import OrderTaxedPricesData+from ..models import OrderLine@pytest.fixture@@ -1181,6 +1191,7 @@ def test_fetch_order_data_calls_plugin(mock_get_taxes.assert_not_called()+@patch("saleor.order.calculations.validate_tax_data")@patch("saleor.plugins.manager.PluginsManager.calculate_order_total")@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_order")@patch("saleor.order.calculations._apply_tax_data")@@ -1189,10 +1200,13 @@ def test_fetch_order_data_calls_tax_app(mock_apply_tax_data,mock_get_taxes,mock_calculate_order_total,+ mock_validate_tax_data,order_with_lines,order_lines,):# given+ mock_validate_tax_data.return_value = False+order = order_with_linesorder.channel.tax_configuration.tax_app_id = "test.app"order.channel.tax_configuration.save()@@ -1277,3 +1291,370 @@ def test_recalculate_prices_empty_tax_data_logging_address(f"Fetching tax data for order with address validation skipped. "f"Address ID: {address.pk}" in caplog.text)+++ ("prices_entered_with_tax", "tax_app_id"),+ [(True, None), (True, "test.app"), (False, None), (False, "test.app")],+)+def test_fetch_order_data_tax_data_with_negative_values(+ prices_entered_with_tax,+ tax_app_id,+ order_with_lines,+ caplog,+):+ # given+ order = order_with_lines++ channel = order.channel+ channel.tax_configuration.tax_app_id = tax_app_id+ channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.save()++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("-1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ TaxLineData(+ total_net_amount=Decimal("4"),+ total_gross_amount=Decimal("6"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ zero_money = zero_taxed_money(order.currency)+ zero_prices = OrderTaxedPricesData(+ undiscounted_price=zero_money,+ price_with_discounts=zero_money,+ )+ manager_methods = {+ "calculate_order_line_unit": Mock(return_value=zero_prices),+ "calculate_order_line_total": Mock(return_value=zero_prices),+ "calculate_order_total": Mock(return_value=zero_money),+ "calculate_order_shipping": Mock(return_value=zero_money),+ "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_taxes_for_order": Mock(return_value=tax_data),+ }+ manager = Mock(**manager_methods)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.NEGATIVE_VALUE+ assert TaxDataErrorMessage.NEGATIVE_VALUE in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)+++ ("prices_entered_with_tax", "tax_app_id"),+ [(True, None), (True, "test.app"), (False, None), (False, "test.app")],+)+def test_fetch_order_data_tax_data_with_wrong_number_of_lines(+ prices_entered_with_tax,+ tax_app_id,+ order_with_lines,+ caplog,+):+ # given+ order = order_with_lines+ channel = order.channel+ channel.tax_configuration.tax_app_id = tax_app_id+ channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.save()++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ zero_money = zero_taxed_money(order.currency)+ zero_prices = OrderTaxedPricesData(+ undiscounted_price=zero_money,+ price_with_discounts=zero_money,+ )+ manager_methods = {+ "calculate_order_line_unit": Mock(return_value=zero_prices),+ "calculate_order_line_total": Mock(return_value=zero_prices),+ "calculate_order_total": Mock(return_value=zero_money),+ "calculate_order_shipping": Mock(return_value=zero_money),+ "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_taxes_for_order": Mock(return_value=tax_data),+ }+ manager = Mock(**manager_methods)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.LINE_NUMBER+ assert TaxDataErrorMessage.LINE_NUMBER in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)+++ ("prices_entered_with_tax", "tax_app_id"),+ [(True, None), (True, "test.app"), (False, None), (False, "test.app")],+)+def test_fetch_order_data_tax_data_with_price_overflow(+ prices_entered_with_tax,+ tax_app_id,+ order_with_lines,+ caplog,+):+ # given+ order = order_with_lines+ channel = order.channel+ channel.tax_configuration.tax_app_id = tax_app_id+ channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.save()++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("99999999999"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ TaxLineData(+ total_net_amount=Decimal("4"),+ total_gross_amount=Decimal("6"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ zero_money = zero_taxed_money(order.currency)+ zero_prices = OrderTaxedPricesData(+ undiscounted_price=zero_money,+ price_with_discounts=zero_money,+ )+ manager_methods = {+ "calculate_order_line_unit": Mock(return_value=zero_prices),+ "calculate_order_line_total": Mock(return_value=zero_prices),+ "calculate_order_total": Mock(return_value=zero_money),+ "calculate_order_shipping": Mock(return_value=zero_money),+ "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),+ "get_taxes_for_order": Mock(return_value=tax_data),+ }+ manager = Mock(**manager_methods)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.OVERFLOW+ assert TaxDataErrorMessage.OVERFLOW in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)+++@patch("saleor.plugins.avatax.plugin.get_order_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_with_negative_values(+ mock_get_tax_data,+ order_with_lines,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ order = order_with_lines++ channel = order.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": -30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 40.0000,+ "quantity": 2.0,+ "itemCode": "SKU_B",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.NEGATIVE_VALUE+ assert TaxDataErrorMessage.NEGATIVE_VALUE in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)+++@patch("saleor.plugins.avatax.plugin.get_order_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_with_wrong_number_of_lines(+ mock_get_tax_data,+ order_with_lines,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ order = order_with_lines++ channel = order.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.LINE_NUMBER+ assert TaxDataErrorMessage.LINE_NUMBER in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)+++@patch("saleor.plugins.avatax.plugin.get_order_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_with_wrong_number_of_lines_no_shipping(+ mock_get_tax_data,+ order_with_lines,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ order = order_with_lines+ lines = [line for line in order.lines.all()]+ for line in lines:+ line.is_shipping_required = False+ OrderLine.objects.bulk_update(lines, ["is_shipping_required"])++ channel = order.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 40.0000,+ "quantity": 2.0,+ "itemCode": "SKU_B",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.LINE_NUMBER+ assert TaxDataErrorMessage.LINE_NUMBER in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)+++@patch("saleor.plugins.avatax.plugin.get_order_tax_data")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_fetch_order_data_plugin_tax_data_price_overflow(+ mock_get_tax_data,+ order_with_lines,+ caplog,+ plugin_configuration, # noqa: F811+):+ # given+ order = order_with_lines++ channel = order.channel+ channel.tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER+ channel.tax_configuration.save(update_fields=["tax_app_id"])++ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 40.0000,+ "quantity": 2.0,+ "itemCode": "SKU_B",+ },+ {+ "lineAmount": 8368725697628976.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }+ mock_get_tax_data.return_value = tax_data++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)++ # when+ calculations.fetch_order_prices_if_expired(order, manager, None, True)++ # then+ assert order.tax_error == TaxDataErrorMessage.OVERFLOW+ assert TaxDataErrorMessage.OVERFLOW in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex bbd384d6b4..2953f5f740 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -1,5 +1,6 @@from decimal import Decimal+import grapheneimport pytestfrom prices import Money, TaxedMoney@@ -26,6 +27,7 @@ from ..utils import (get_total_order_discount_excluding_shipping,get_valid_shipping_methods_for_order,match_orders_with_new_user,+ order_info_for_logs,update_order_display_gross_prices,)@@ -705,3 +707,40 @@ def test_calculate_order_granted_refund_status(# thengranted_refund.refresh_from_db()assert granted_refund.status == expected_granted_status+++def test_order_info_for_logs(order_with_lines, voucher, order_promotion_with_rule):+ # given+ order = order_with_lines+ voucher_code = voucher.codes.first().code+ order.voucher_code = voucher_code+ order.voucher = voucher+ order.status = OrderStatus.DRAFT+ order.save(update_fields=["voucher_code", "voucher_id", "status"])++ order.discounts.create(+ type=DiscountType.ORDER_PROMOTION,+ value_type=DiscountValueType.FIXED,+ value=Decimal(5),+ amount_value=Decimal(5),+ promotion_rule=order_promotion_with_rule.rules.first(),+ currency=order.currency,+ )++ lines = order.lines.all()+ lines[0].discounts.create(+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=Decimal(5),+ currency=order.currency,+ amount_value=Decimal(5),+ voucher=voucher,+ )++ # when+ extra = order_info_for_logs(order, lines)++ # then+ assert extra["order_id"] == graphene.Node.to_global_id("Order", order.pk)+ assert extra["discounts"]+ assert extra["lines"][0]["discounts"]diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex fe1bbf4bee..06d630ac1c 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -54,7 +54,7 @@ from . import (OrderStatus,events,)-from .fetch import OrderLineInfo+from .fetch import OrderLineInfo, fetch_draft_order_lines_infofrom .models import Order, OrderGrantedRefund, OrderLineif TYPE_CHECKING:@@ -1210,3 +1210,71 @@ def get_address_for_order_taxes(order: "Order"):else:address = order.shipping_address or order.billing_addressreturn address+++def order_info_for_logs(order: Order, lines: Iterable[OrderLine]):+ from ..discount.utils.shared import discount_info_for_logs++ order_id = graphene.Node.to_global_id("Order", order.id)+ tax_configuration = order.channel.tax_configuration+ lines_info = fetch_draft_order_lines_info(order, lines)++ return {+ "order_id": order_id,+ "orderId": order_id,+ "order": {+ "currency": order.currency,+ "status": order.status,+ "origin": order.origin,+ "checkout_id": order.checkout_token,+ "undiscounted_base_shipping_price_amount": order.undiscounted_base_shipping_price_amount,+ "base_shipping_price_amount": order.base_shipping_price_amount,+ "shipping_price_net_amount": order.shipping_price_net_amount,+ "shipping_price_gross_amount": order.shipping_price_gross_amount,+ "undiscounted_total_net_amount": order.undiscounted_total_net_amount,+ "total_net_amount": order.total_net_amount,+ "undiscounted_total_gross_amount": order.undiscounted_total_gross_amount,+ "total_gross_amount": order.total_gross_amount,+ "subtotal_net_amount": order.subtotal_net_amount,+ "subtotal_gross_amount": order.subtotal_gross_amount,+ "has_voucher_code": bool(order.voucher_code),+ "tax_exemption": order.tax_exemption,+ "tax_error": order.tax_error,+ },+ "tax_configuration": {+ "charge_taxes": tax_configuration.charge_taxes,+ "tax_calculation_strategy": tax_configuration.tax_calculation_strategy,+ "prices_entered_with_tax": tax_configuration.prices_entered_with_tax,+ "tax_app_id": tax_configuration.tax_app_id,+ },+ "discounts": discount_info_for_logs(order.discounts.all()),+ "lines": [+ {+ "id": graphene.Node.to_global_id("OrderLine", line_info.line.pk),+ "variant_id": graphene.Node.to_global_id(+ "ProductVariant", line_info.line.variant_id+ ),+ "quantity": line_info.line.quantity,+ "is_gift_card": line_info.line.is_gift_card,+ "is_price_overridden": line_info.line.is_price_overridden,+ "undiscounted_base_unit_price_amount": line_info.line.undiscounted_base_unit_price_amount,+ "base_unit_price_amount": line_info.line.base_unit_price_amount,+ "undiscounted_unit_price_net_amount": line_info.line.undiscounted_unit_price_net_amount,+ "undiscounted_unit_price_gross_amount": line_info.line.undiscounted_unit_price_gross_amount,+ "unit_price_net_amount": line_info.line.unit_price_net_amount,+ "unit_price_gross_amount": line_info.line.unit_price_gross_amount,+ "undiscounted_total_price_net_amount": line_info.line.undiscounted_total_price_net_amount,+ "undiscounted_total_price_gross_amount": line_info.line.undiscounted_total_price_gross_amount,+ "total_price_net_amount": line_info.line.total_price_net_amount,+ "total_price_gross_amount": line_info.line.total_price_gross_amount,+ "has_voucher_code": bool(line_info.line.voucher_code),+ "variant_listing_price": line_info.channel_listing.price_amount,+ "variant_listing_discounted_price": line_info.channel_listing.discounted_price_amount,+ "unit_discount_amount": line_info.line.unit_discount_amount,+ "unit_discount_type": line_info.line.unit_discount_type,+ "unit_discount_reason": line_info.line.unit_discount_reason,+ "discounts": discount_info_for_logs(line_info.discounts),+ }+ for line_info in lines_info+ ],+ }diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.pyindex 1f2ffc0ae1..27a9da5ea8 100644--- a/saleor/plugins/avatax/plugin.py+++ b/saleor/plugins/avatax/plugin.py@@ -15,10 +15,22 @@ from prices import Money, TaxedMoney, TaxedMoneyRangefrom ...checkout import base_calculationsfrom ...checkout.fetch import fetch_checkout_lines-from ...checkout.utils import log_address_if_validation_skipped_for_checkout-from ...core.taxes import TaxError, TaxType, zero_taxed_money+from ...checkout.utils import (+ is_shipping_required as is_shipping_required_for_checkout,+)+from ...checkout.utils import (+ log_address_if_validation_skipped_for_checkout,+)+from ...core.prices import MAXIMUM_PRICE+from ...core.taxes import (+ TaxDataErrorMessage,+ TaxError,+ TaxType,+ zero_taxed_money,+)from ...order import base_calculations as order_base_calculationfrom ...order.interface import OrderTaxedPricesData+from ...order.utils import is_shipping_required as is_shipping_required_for_orderfrom ...product.models import ProductTypefrom ...tax import TaxCalculationStrategyfrom ...tax.utils import (@@ -736,18 +748,31 @@ class AvataxPlugin(BasePlugin):base_value: Union[TaxedMoney, Decimal],):if self._skip_plugin(base_value):- self._set_checkout_tax_error(checkout_info, lines_info)+ self._set_checkout_tax_error(+ checkout_info, lines_info, TaxDataErrorMessage.EMPTY+ )return Nonevalid = _validate_checkout(checkout_info, lines_info)if not valid:- self._set_checkout_tax_error(checkout_info, lines_info)+ self._set_checkout_tax_error(+ checkout_info, lines_info, TaxDataErrorMessage.EMPTY+ )return Noneresponse = get_checkout_tax_data(checkout_info, lines_info, self.config)if not response or "error" in response:- self._set_checkout_tax_error(checkout_info, lines_info)+ self._set_checkout_tax_error(+ checkout_info, lines_info, TaxDataErrorMessage.EMPTY+ )+ return None++ is_shipping_required = is_shipping_required_for_checkout(lines_info)+ if tax_error := self.validate_tax_data(+ response, lines_info, is_shipping_required+ ):+ self._set_checkout_tax_error(checkout_info, lines_info, tax_error)return Nonereturn response@@ -756,34 +781,41 @@ class AvataxPlugin(BasePlugin):self,checkout_info: "CheckoutInfo",lines_info: Iterable["CheckoutLineInfo"],+ tax_error_message: str,) -> None:app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines_info)if app_identifier == self.PLUGIN_IDENTIFIER:- checkout_info.checkout.tax_error = "Empty tax data."+ checkout_info.checkout.tax_error = tax_error_messagedef _get_order_tax_data(self, order: "Order", base_value: Union[Decimal, OrderTaxedPricesData]):if self._skip_plugin(base_value):- self._set_order_tax_error(order)+ self._set_order_tax_error(order, TaxDataErrorMessage.EMPTY)return Nonevalid = _validate_order(order)if not valid:- self._set_order_tax_error(order)+ self._set_order_tax_error(order, TaxDataErrorMessage.EMPTY)return Noneresponse = get_order_tax_data(order, self.config, False)if not response or "error" in response:- self._set_order_tax_error(order)+ self._set_order_tax_error(order, TaxDataErrorMessage.EMPTY)+ return None++ lines = order.lines.all()+ is_shipping_required = is_shipping_required_for_order(lines)+ if tax_error := self.validate_tax_data(response, lines, is_shipping_required):+ self._set_order_tax_error(order, tax_error)return Nonereturn response- def _set_order_tax_error(self, order: "Order") -> None:+ def _set_order_tax_error(self, order: "Order", tax_error: str) -> None:app_identifier = get_tax_app_identifier_for_order(order)if app_identifier == self.PLUGIN_IDENTIFIER:- order.tax_error = "Empty tax data."+ order.tax_error = tax_error@staticmethoddef _get_unit_tax_rate(@@ -910,3 +942,63 @@ class AvataxPlugin(BasePlugin):)cls.validate_authentication(plugin_configuration)++ @classmethod+ def validate_tax_data(+ cls, tax_data: dict[str, Any], lines: Iterable, is_shipping_required: bool+ ) -> str:+ if not tax_data:+ return TaxDataErrorMessage.EMPTY++ if cls.check_negative_values_in_plugin_tax_data(tax_data):+ return TaxDataErrorMessage.NEGATIVE_VALUE++ if cls.check_line_number_in_plugin_tax_data(+ tax_data, lines, is_shipping_required+ ):+ return TaxDataErrorMessage.LINE_NUMBER++ if cls.check_overflows_in_plugin_tax_data(tax_data):+ return TaxDataErrorMessage.OVERFLOW++ return ""++ @classmethod+ def check_negative_values_in_plugin_tax_data(cls, tax_data: dict[str, Any]) -> bool:+ """Check if tax data contains negative values."""+ if not tax_data:+ return False++ for line in tax_data.get("lines", []):+ if line.get("lineAmount", 0) < 0:+ return True++ return False++ @classmethod+ def check_line_number_in_plugin_tax_data(+ cls, tax_data: dict[str, Any], lines: Iterable, is_shipping_required: bool+ ) -> bool:+ """Check if tax data contains same line number as input data."""+ if not tax_data:+ return False++ tax_lines = tax_data.get("lines", [])+ # shipping data is represented as additional order line+ expected_lines_length = len(list(lines)) + (1 if is_shipping_required else 0)+ if len(tax_lines) != expected_lines_length:+ return True++ return False++ @classmethod+ def check_overflows_in_plugin_tax_data(cls, tax_data: dict[str, Any]) -> bool:+ """Check if line prices are lower than a billion."""+ if not tax_data:+ return False++ for line in tax_data.get("lines", []):+ if line.get("lineAmount", 0) > MAXIMUM_PRICE:+ return True++ return Falsediff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex d09105d06b..df46604520 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -19,7 +19,13 @@ from ....checkout.fetch import ()from ....checkout.utils import add_variant_to_checkoutfrom ....core.prices import quantize_price-from ....core.taxes import TaxError, TaxType, zero_money, zero_taxed_money+from ....core.taxes import (+ TaxDataErrorMessage,+ TaxError,+ TaxType,+ zero_money,+ zero_taxed_money,+)from ....discount import DiscountType, DiscountValueType, RewardValueType, VoucherTypefrom ....discount.models import CheckoutLineDiscount, Promotion, PromotionRulefrom ....discount.utils.checkout import (@@ -6364,3 +6370,96 @@ def test_get_checkout_tax_data_set_tax_error(# thenassert checkout_with_item.tax_error == "Empty tax data."+++def test_validate_plugin_tax_data_no_data(order_with_lines, lines_info):+ # given+ tax_data = {}++ # when+ error_message = AvataxPlugin.validate_tax_data(tax_data, lines_info, True)++ # then+ assert error_message == TaxDataErrorMessage.EMPTY+++def test_validate_plugin_tax_data_with_negative_values(lines_info, caplog):+ # given+ tax_data = {+ "lines": [+ {+ "lineAmount": -30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 40.0000,+ "quantity": 2.0,+ "itemCode": "SKU_B",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }++ # when+ error_message = AvataxPlugin.validate_tax_data(tax_data, lines_info, True)++ # then+ assert error_message == TaxDataErrorMessage.NEGATIVE_VALUE+++def test_validate_plugin_tax_data_line_number(lines_info, caplog):+ # given+ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }++ # when+ error_message = AvataxPlugin.validate_tax_data(tax_data, lines_info, True)++ # then+ assert error_message == TaxDataErrorMessage.LINE_NUMBER+++def test_validate_plugin_tax_data_price_overflow(lines_info, caplog):+ # given+ tax_data = {+ "lines": [+ {+ "lineAmount": 30.0000,+ "quantity": 3.0,+ "itemCode": "SKU_A",+ },+ {+ "lineAmount": 99999999999.0000,+ "quantity": 2.0,+ "itemCode": "SKU_B",+ },+ {+ "lineAmount": 8.1300,+ "quantity": 1.0,+ "itemCode": "Shipping",+ },+ ]+ }++ # when+ error_message = AvataxPlugin.validate_tax_data(tax_data, lines_info, True)++ # then+ assert error_message == TaxDataErrorMessage.OVERFLOWdiff --git a/saleor/plugins/avatax/tests/test_avatax_caching.py b/saleor/plugins/avatax/tests/test_avatax_caching.pyindex 0dc874ab84..77d269dea0 100644--- a/saleor/plugins/avatax/tests/test_avatax_caching.py+++ b/saleor/plugins/avatax/tests/test_avatax_caching.py@@ -11,9 +11,11 @@ from ..plugin import AvataxPlugin@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_calculate_checkout_total_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -42,6 +44,7 @@ def test_calculate_checkout_total_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_total(@@ -57,7 +60,9 @@ def test_calculate_checkout_total_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_calculate_checkout_total_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -80,6 +85,7 @@ def test_calculate_checkout_total_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_total(@@ -100,9 +106,11 @@ def test_calculate_checkout_total_save_avatax_response_in_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_calculate_checkout_subtotal_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -131,6 +139,7 @@ def test_calculate_checkout_subtotal_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_subtotal(@@ -146,7 +155,9 @@ def test_calculate_checkout_subtotal_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_calculate_checkout_subtotal_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -169,6 +180,7 @@ def test_calculate_checkout_subtotal_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_subtotal(@@ -189,9 +201,11 @@ def test_calculate_checkout_subtotal_save_avatax_response_in_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_calculate_checkout_shipping_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -220,6 +234,7 @@ def test_calculate_checkout_shipping_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_shipping(@@ -235,7 +250,9 @@ def test_calculate_checkout_shipping_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_calculate_checkout_shipping_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -258,6 +275,7 @@ def test_calculate_checkout_shipping_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_shipping(@@ -278,9 +296,11 @@ def test_calculate_checkout_shipping_save_avatax_response_in_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_calculate_checkout_line_total_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -310,6 +330,7 @@ def test_calculate_checkout_line_total_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_line_total(@@ -328,7 +349,9 @@ def test_calculate_checkout_line_total_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_calculate_checkout_line_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -352,6 +375,7 @@ def test_calculate_checkout_line_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_line_total(@@ -372,9 +396,11 @@ def test_calculate_checkout_line_save_avatax_response_in_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_calculate_checkout_line_unit_price_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -404,6 +430,7 @@ def test_calculate_checkout_line_unit_price_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_line_unit_price(@@ -422,7 +449,9 @@ def test_calculate_checkout_line_unit_price_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_calculate_checkout_line_unit_price_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -446,6 +475,7 @@ def test_calculate_checkout_line_unit_price_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""# thenresult = manager.calculate_checkout_line_unit_price(@@ -472,9 +502,11 @@ def test_calculate_checkout_line_unit_price_save_avatax_response_in_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_get_checkout_line_tax_rate_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -504,6 +536,7 @@ def test_get_checkout_line_tax_rate_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""fake_unit_price = TaxedMoney(net=Money("2", "USD"), gross=Money("10", "USD"))# then@@ -524,7 +557,9 @@ def test_get_checkout_line_tax_rate_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_get_checkout_line_tax_rate_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -548,6 +583,7 @@ def test_get_checkout_line_tax_rate_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""fake_unit_price = TaxedMoney(net=Money("2", "USD"), gross=Money("10", "USD"))# then@@ -577,9 +613,11 @@ def test_get_checkout_line_tax_rate_save_avatax_response_in_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")@patch("saleor.plugins.avatax.cache.set")def test_get_checkout_shipping_tax_rate_use_cache(mock_cache_set,+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -608,6 +646,7 @@ def test_get_checkout_shipping_tax_rate_use_cache())monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)+ mock_validate_tax_data.return_value = ""fake_shipping_price = TaxedMoney(net=Money("2", "USD"), gross=Money("10", "USD"))# then@@ -624,7 +663,9 @@ def test_get_checkout_shipping_tax_rate_use_cache(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+@patch("saleor.plugins.avatax.plugin.AvataxPlugin.validate_tax_data")def test_get_checkout_shipping_tax_rate_save_avatax_response_in_cache(+ mock_validate_tax_data,checkout_with_items_and_shipping,checkout_with_items_and_shipping_info,address,@@ -647,6 +688,7 @@ def test_get_checkout_shipping_tax_rate_save_avatax_response_in_cache(return_value=avalara_response_for_checkout_with_items_and_shipping)monkeypatch.setattr("saleor.plugins.avatax.api_post_request", mocked_avalara)+ mock_validate_tax_data.return_value = ""fake_shipping_price = TaxedMoney(net=Money("2", "USD"), gross=Money("10", "USD"))# thendiff --git a/saleor/tax/tests/test_utils.py b/saleor/tax/tests/test_utils.pyindex 3c9330d934..c956db1a37 100644--- a/saleor/tax/tests/test_utils.py+++ b/saleor/tax/tests/test_utils.py@@ -1,7 +1,15 @@+from decimal import Decimal+import pytest+from ...core.taxes import TaxData, TaxDataError, TaxLineDatafrom ...core.utils.country import get_active_country-from ..utils import get_charge_taxes, get_display_gross_prices, get_tax_app_id+from ..utils import (+ get_charge_taxes,+ get_display_gross_prices,+ get_tax_app_id,+ validate_tax_data,+)def test_get_display_gross_prices(channel_USD):@@ -107,3 +115,113 @@ def test_get_tax_country_fallbacks_to_channel_country(channel_USD):# thenassert country == channel_USD.default_country.code+++def test_validate_tax_data_no_data(order_with_lines, lines_info):+ # given+ tax_data = None++ # when & then+ with pytest.raises(TaxDataError):+ validate_tax_data(tax_data, lines_info)+++def test_validate_tax_data_with_negative_values(lines_info, caplog):+ # given+ tax_data = TaxData(+ shipping_price_net_amount=Decimal("-1"),+ shipping_price_gross_amount=Decimal("-1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ TaxLineData(+ total_net_amount=Decimal("4"),+ total_gross_amount=Decimal("6"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ # when & then+ with pytest.raises(TaxDataError):+ validate_tax_data(tax_data, lines_info)+++def test_validate_tax_data_line_number(lines_info, caplog):+ # given+ assert len(lines_info) == 2++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ # when & then+ with pytest.raises(TaxDataError):+ validate_tax_data(tax_data, lines_info)+++def test_validate_tax_data_tax_rate_overflow(lines_info, caplog):+ # given+ assert len(lines_info) == 2++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("1"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("120"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ TaxLineData(+ total_net_amount=Decimal("4"),+ total_gross_amount=Decimal("6"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ # when & then+ with pytest.raises(TaxDataError):+ validate_tax_data(tax_data, lines_info)+++def test_validate_tax_data_price_overflow(lines_info, caplog):+ # given+ assert len(lines_info) == 2++ tax_data = TaxData(+ shipping_price_net_amount=Decimal("9999999999999999"),+ shipping_price_gross_amount=Decimal("1.5"),+ shipping_tax_rate=Decimal("50"),+ lines=[+ TaxLineData(+ total_net_amount=Decimal("2"),+ total_gross_amount=Decimal("3"),+ tax_rate=Decimal("50"),+ ),+ TaxLineData(+ total_net_amount=Decimal("4"),+ total_gross_amount=Decimal("6"),+ tax_rate=Decimal("50"),+ ),+ ],+ )++ # when & then+ with pytest.raises(TaxDataError):+ validate_tax_data(tax_data, lines_info)diff --git a/saleor/tax/utils.py b/saleor/tax/utils.pyindex cb6d4a7f00..d7eda9e718 100644--- a/saleor/tax/utils.py+++ b/saleor/tax/utils.py@@ -1,3 +1,4 @@+import loggingfrom collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional@@ -5,6 +6,8 @@ from typing import TYPE_CHECKING, Optionalfrom django.conf import settingsfrom prices import TaxedMoney+from ..core.prices import MAXIMUM_PRICE+from ..core.taxes import TaxData, TaxDataError, TaxDataErrorMessagefrom ..core.utils.country import get_active_countryfrom . import TaxCalculationStrategy@@ -15,6 +18,9 @@ if TYPE_CHECKING:from .models import TaxConfiguration, TaxConfigurationPerCountry+logger = logging.getLogger(__name__)++def get_display_gross_prices(channel_tax_configuration: "TaxConfiguration",country_tax_configuration: Optional["TaxConfigurationPerCountry"],@@ -248,3 +254,78 @@ def get_shipping_tax_class_kwargs_for_order(tax_class: Optional["TaxClass"]):"shipping_tax_class_private_metadata": tax_class.private_metadata,"shipping_tax_class_metadata": tax_class.metadata,}+++def validate_tax_data(+ tax_data: Optional[TaxData],+ lines: Iterable,+ allow_empty_tax_data: bool = False,+):+ if tax_data is None and not allow_empty_tax_data:+ raise TaxDataError(TaxDataErrorMessage.EMPTY)++ if check_negative_values_in_tax_data(tax_data):+ raise TaxDataError(TaxDataErrorMessage.NEGATIVE_VALUE)++ if check_line_number_in_tax_data(tax_data, lines):+ raise TaxDataError(TaxDataErrorMessage.LINE_NUMBER)++ if check_overflows_in_tax_data(tax_data):+ raise TaxDataError(TaxDataErrorMessage.OVERFLOW)+++def check_negative_values_in_tax_data(tax_data: Optional[TaxData]) -> bool:+ """Check if tax data contains negative values."""+ if not tax_data:+ return False++ if (+ tax_data.shipping_price_gross_amount < 0+ or tax_data.shipping_price_net_amount < 0+ or tax_data.shipping_tax_rate < 0+ ):+ return True++ for line in tax_data.lines:+ if (+ line.total_gross_amount < 0+ or line.total_net_amount < 0+ or line.tax_rate < 0+ ):+ return True++ return False+++def check_line_number_in_tax_data(tax_data: Optional[TaxData], lines: Iterable) -> bool:+ """Check if tax data contains same line number as input data."""+ if not tax_data:+ return False++ if len(tax_data.lines) != len(list(lines)):+ return True++ return False+++def check_overflows_in_tax_data(tax_data: Optional[TaxData]) -> bool:+ """Check if tax rates exceed 100% and line prices are lower than a billion."""+ if not tax_data:+ return False++ if (+ tax_data.shipping_price_gross_amount > MAXIMUM_PRICE+ or tax_data.shipping_price_net_amount > MAXIMUM_PRICE+ or tax_data.shipping_tax_rate > 100+ ):+ return True++ for line in tax_data.lines:+ if (+ line.total_gross_amount > MAXIMUM_PRICE+ or line.total_net_amount > MAXIMUM_PRICE+ or line.tax_rate > 100+ ):+ return True++ return Falsediff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex c9cc6c5e35..37716765fa 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -954,6 +954,15 @@ def checkout_with_items_and_shipping(checkout_with_items, address, shipping_methreturn checkout_with_items+def checkout_with_item_and_shipping(checkout_with_item, address, shipping_method):+ checkout_with_item.shipping_address = address+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.billing_address = address+ checkout_with_item.save()+ return checkout_with_item++@pytest.fixturedef checkout_with_voucher(checkout, product, voucher):variant = product.variants.get()