Skip to content

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

Introduce static typing for tax sync webhook responses (#17562)

Iga Karbowiak1337f67b0019
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 4b7760b214..7b9191315d 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -30,7 +30,6 @@ 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_info
from .models import Checkout
@@ -406,9 +405,10 @@ def _fetch_checkout_prices_if_expired(
)
except TaxDataError as e:
if str(e) != TaxDataErrorMessage.EMPTY:
- logger.warning(
- str(e), extra=checkout_info_for_logs(checkout_info, lines)
- )
+ extra = checkout_info_for_logs(checkout_info, lines)
+ if e.errors:
+ extra["errors"] = e.errors
+ logger.warning(str(e), extra=extra)
_set_checkout_base_prices(checkout, checkout_info, lines)
checkout.tax_error = str(e)
@@ -437,9 +437,10 @@ def _fetch_checkout_prices_if_expired(
)
except TaxDataError as e:
if str(e) != TaxDataErrorMessage.EMPTY:
- logger.warning(
- str(e), extra=checkout_info_for_logs(checkout_info, lines)
- )
+ extra = checkout_info_for_logs(checkout_info, lines)
+ if e.errors:
+ extra["errors"] = e.errors
+ logger.warning(str(e), extra=extra)
_set_checkout_base_prices(checkout, checkout_info, lines)
checkout.tax_error = str(e)
else:
@@ -500,8 +501,6 @@ def _calculate_and_add_tax(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
pregenerated_subscription_payloads: dict | None = None,
):
- from .utils import log_address_if_validation_skipped_for_checkout
-
if pregenerated_subscription_payloads is None:
pregenerated_subscription_payloads = {}
if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:
@@ -514,15 +513,16 @@ def _calculate_and_add_tax(
checkout, manager, checkout_info, lines, address
)
# Get the taxes calculated with apps and apply to checkout.
- tax_data = manager.get_taxes_for_checkout(
+ # We should allow empty tax_data in case any tax webhook has not been
+ # configured - handled by `allowed_empty_tax_data`
+ tax_data = _get_taxes_for_checkout(
checkout_info,
lines,
tax_app_identifier,
+ manager,
pregenerated_subscription_payloads,
+ allowed_empty_tax_data=True,
)
- 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(
@@ -555,8 +555,6 @@ def _call_plugin_or_tax_app(
address: Optional["Address"] = None,
pregenerated_subscription_payloads: dict | None = None,
):
- from .utils import log_address_if_validation_skipped_for_checkout
-
if pregenerated_subscription_payloads is None:
pregenerated_subscription_payloads = {}
@@ -580,16 +578,50 @@ def _call_plugin_or_tax_app(
if checkout.tax_error:
raise TaxDataError(checkout.tax_error)
else:
+ tax_data = _get_taxes_for_checkout(
+ checkout_info,
+ lines,
+ tax_app_identifier,
+ manager,
+ pregenerated_subscription_payloads,
+ )
+ _apply_tax_data(checkout, lines, tax_data)
+
+
+def _get_taxes_for_checkout(
+ checkout_info: "CheckoutInfo",
+ lines: list["CheckoutLineInfo"],
+ tax_app_identifier: str | None,
+ manager: "PluginsManager",
+ pregenerated_subscription_payloads: dict | None = None,
+ allowed_empty_tax_data: bool = False,
+):
+ """Get taxes for checkout from tax apps.
+
+ The `allowed_empty_tax_data` flag prevents an error from being raised when tax data
+ is missing due to the absence of a configured tax app.
+ """
+ from .utils import log_address_if_validation_skipped_for_checkout
+
+ tax_data = None
+ try:
tax_data = manager.get_taxes_for_checkout(
checkout_info,
lines,
tax_app_identifier,
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
+ except TaxDataError as e:
+ raise e from e
+ finally:
+ # log in case the tax_data is missing
if tax_data is None:
log_address_if_validation_skipped_for_checkout(checkout_info, logger)
- validate_tax_data(tax_data, lines)
- _apply_tax_data(checkout, lines, tax_data)
+
+ if not tax_data and not allowed_empty_tax_data:
+ raise TaxDataError(TaxDataErrorMessage.EMPTY)
+
+ return tax_data
def _remove_tax(checkout, lines_info):
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index f50b9c1041..1514f81819 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -17,7 +17,7 @@ from prices import Money
from ..channel.models import Channel
from ..core.db.fields import MoneyField, TaxedMoneyField
from ..core.models import ModelWithMetadata
-from ..core.taxes import zero_money
+from ..core.taxes import TAX_ERROR_FIELD_LENGTH, zero_money
from ..giftcard.models import GiftCard
from ..permission.enums import CheckoutPermissions
from ..shipping.models import ShippingMethod
@@ -220,7 +220,9 @@ class Checkout(models.Model):
)
tax_exemption = models.BooleanField(default=False)
- tax_error = models.CharField(max_length=255, blank=True, null=True)
+ tax_error = models.CharField(
+ max_length=TAX_ERROR_FIELD_LENGTH, blank=True, null=True
+ )
class Meta:
ordering = ("-last_change", "pk")
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index ebe1ee308a..2f9d280f88 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -14,7 +14,13 @@ from ...checkout.utils import (
assign_external_shipping_to_checkout,
)
from ...core.prices import quantize_price
-from ...core.taxes import TaxData, TaxDataErrorMessage, TaxLineData, zero_taxed_money
+from ...core.taxes import (
+ TaxData,
+ TaxDataError,
+ TaxDataErrorMessage,
+ TaxLineData,
+ zero_taxed_money,
+)
from ...graphql.core.utils import to_global_id_or_none
from ...plugins import PLUGIN_IDENTIFIER_PREFIX
from ...plugins.avatax.plugin import AvataxPlugin
@@ -34,6 +40,7 @@ from ..calculations import (
_calculate_and_add_tax,
_set_checkout_base_prices,
fetch_checkout_data,
+ logger,
)
from ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_lines
@@ -639,7 +646,6 @@ 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")
@@ -648,16 +654,17 @@ def test_fetch_checkout_data_calls_tax_app(
mock_apply_tax_data,
mock_get_taxes,
mock_calculate_checkout_total,
- mock_validate_tax_data,
checkout_with_items,
+ tax_data_response,
):
# given
- mock_validate_tax_data.return_value = False
checkout = checkout_with_items
checkout.price_expiration = timezone.now()
checkout.save()
+ mock_get_taxes.return_value = tax_data_response
+
checkout.channel.tax_configuration.tax_app_id = "test.app"
checkout.channel.tax_configuration.save()
@@ -682,7 +689,6 @@ def test_fetch_checkout_data_calls_tax_app(
@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")
@@ -691,11 +697,9 @@ def test_fetch_checkout_data_calls_tax_app_when_allow_sync_webhooks_set_to_false
mock_apply_tax_data,
mock_get_taxes,
mock_calculate_checkout_total,
- mock_validate_tax_data,
checkout_with_items,
):
# given
- mock_validate_tax_data.return_value = False
checkout = checkout_with_items
checkout.price_expiration = timezone.now()
@@ -737,7 +741,6 @@ def test_fetch_checkout_data_calls_tax_app_when_allow_sync_webhooks_set_to_false
mock_apply_tax_data.assert_not_called()
mock_get_taxes.assert_not_called()
mock_calculate_checkout_total.assert_not_called()
- mock_validate_tax_data.assert_not_called()
@freeze_time()
@@ -902,13 +905,14 @@ def test_calculate_and_add_tax_empty_tax_data_logging_address(
("prices_entered_with_tax", "tax_app_id"),
[(True, None), (True, "test.app"), (False, None), (False, "test.app")],
)
[email protected](logger, "warning")
@patch("saleor.checkout.calculations._set_checkout_base_prices")
-def test_fetch_checkout_data_tax_data_with_negative_values(
+def test_fetch_checkout_data_tax_data_with_tax_data_error(
mock_set_base_prices,
+ mocked_logger,
prices_entered_with_tax,
tax_app_id,
checkout_with_single_item,
- caplog,
):
# given
checkout = checkout_with_single_item
@@ -918,19 +922,9 @@ def test_fetch_checkout_data_tax_data_with_negative_values(
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"),
- ),
- ],
- )
-
+ error_msg = "Invalid tax data"
+ errors = [{"error1": "Negative tax data"}, {"error2": "Invalid tax data"}]
+ returned_tax_error = TaxDataError(message=error_msg, errors=errors)
zero_money = zero_taxed_money(checkout.currency)
manager_methods = {
"calculate_checkout_total": Mock(return_value=zero_money),
@@ -939,7 +933,7 @@ def test_fetch_checkout_data_tax_data_with_negative_values(
"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),
+ "get_taxes_for_checkout": Mock(side_effect=returned_tax_error),
}
manager = Mock(**manager_methods)
@@ -950,49 +944,34 @@ def test_fetch_checkout_data_tax_data_with_negative_values(
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)
+ assert checkout_info.checkout.tax_error == error_msg
+ assert mocked_logger.call_count == 1
+ assert len(mocked_logger.call_args) == 2
+ assert mocked_logger.call_args[0][0] == error_msg
+ assert mocked_logger.call_args[1]["extra"]["errors"] == errors
+ mock_set_base_prices.assert_called_once()
@pytest.mark.parametrize(
- ("prices_entered_with_tax", "tax_app_id"),
- [(True, None), (True, "test.app"), (False, None), (False, "test.app")],
+ "prices_entered_with_tax",
+ [True, False],
)
[email protected](logger, "warning")
@patch("saleor.checkout.calculations._set_checkout_base_prices")
-def test_fetch_checkout_data_tax_data_with_wrong_number_of_lines(
+def test_fetch_checkout_data_tax_data_missing_tax_id_empty_tax_data(
mock_set_base_prices,
+ mocked_logger,
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.tax_app_id = None
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),
@@ -1001,64 +980,7 @@ def test_fetch_checkout_data_tax_data_with_wrong_number_of_lines(
"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),
+ "get_taxes_for_checkout": Mock(return_value=None),
}
manager = Mock(**manager_methods)
@@ -1069,9 +991,10 @@ def test_fetch_checkout_data_tax_data_with_price_overflow(
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)
+ # In case the app identifier is not set, in case of error in tax data, it's skipped.
+ assert not checkout_info.checkout.tax_error
+ assert mocked_logger.call_count == 0
+ mock_set_base_prices.assert_not_called()
@patch("saleor.plugins.avatax.plugin.get_checkout_tax_data")
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index c071332b9e..e7820301b2 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -1045,9 +1045,9 @@ def test_create_order_with_voucher_0_total(
)
-@patch("saleor.checkout.calculations.validate_tax_data")
+@patch("saleor.checkout.calculations._calculate_and_add_tax")
def test_create_order_from_checkout_update_tax_error(
- mock_validate_tax_data,
+ _calculate_and_add_tax_mock,
checkout_with_items_and_shipping,
customer_user,
app,
@@ -1055,10 +1055,9 @@ def test_create_order_from_checkout_update_tax_error(
caplog,
):
# given
- mock_validate_tax_data.side_effect = TaxDataError(TaxDataErrorMessage.EMPTY)
-
checkout = checkout_with_items_and_shipping
lines, _ = fetch_checkout_lines(checkout)
+ _calculate_and_add_tax_mock.side_effect = TaxDataError(TaxDataErrorMessage.EMPTY)
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager, [])
@@ -1071,6 +1070,7 @@ def test_create_order_from_checkout_update_tax_error(
user=None,
app=app,
)
+
assert not Order.objects.exists()
assert "Tax app error for checkout" in caplog.text
assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index 1fd5593a1f..352267810d 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -3,6 +3,8 @@ from decimal import Decimal
from prices import Money, TaxedMoney
+TAX_ERROR_FIELD_LENGTH = 255
+
class TaxError(Exception):
"""Default tax error."""
@@ -11,6 +13,10 @@ class TaxError(Exception):
class TaxDataError(Exception):
"""Error in tax data received from tax app or plugin."""
+ def __init__(self, message: str, errors: list | None = None):
+ super().__init__(message)
+ self.errors = errors or []
+
def zero_money(currency: str) -> Money:
"""Return a money object set to zero.
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index ce22153d2c..35c0b035e5 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -435,28 +435,28 @@ def test_checkout_complete_fails_with_invalid_tax_app(
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 == "Configured tax app doesn't exist."
@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,
address,
tax_app,
- tax_data_response, # noqa: F811
+ tax_data_response_factory, # noqa: F811
settings,
):
# given
- mock_request.return_value = tax_data_response
- mock_validate_tax_data.return_value = False
checkout = checkout_without_shipping_required
+ mock_request.return_value = tax_data_response_factory(
+ lines_length=checkout.lines.count()
+ )
+
checkout.billing_address = address
checkout.price_expiration = timezone.now()
checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
@@ -553,24 +553,25 @@ def test_checkout_complete_calls_failing_plugin(
@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,
address,
tax_app,
- tax_data_response, # noqa: F811
+ tax_data_response_factory, # noqa: F811
settings,
):
# given
- mock_request.return_value = tax_data_response
- mock_validate_tax_data.return_value = False
checkout = checkout_without_shipping_required
+
+ mock_request.return_value = tax_data_response_factory(
+ lines_length=checkout.lines.count()
+ )
+
checkout.billing_address = address
checkout.price_expiration = (
timezone.now() + settings.CHECKOUT_PRICES_TTL + timezone.timedelta(hours=1)
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 4c5cd8da54..6cacc7665a 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -17,7 +17,6 @@ from .....checkout.models import Checkout, CheckoutLine
from .....checkout.payment_utils import update_checkout_payment_statuses
from .....core.taxes import (
TaxDataError,
- TaxDataErrorMessage,
TaxError,
zero_money,
zero_taxed_money,
@@ -2666,16 +2665,18 @@ def test_order_from_draft_create_0_total_value_from_giftcard(
)
-@patch("saleor.checkout.calculations.validate_tax_data")
+@patch(
+ "saleor.checkout.calculations._get_taxes_for_checkout",
+ side_effect=TaxDataError("Invalid data"),
+)
def test_order_from_checkout_tax_error(
- mock_validate_tax_data,
+ mocked_get_taxes_for_order,
app_api_client,
permission_handle_checkouts,
checkout_with_items_and_shipping,
caplog,
):
# given
- mock_validate_tax_data.side_effect = TaxDataError(TaxDataErrorMessage.EMPTY)
checkout = checkout_with_items_and_shipping
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index 6704cfd084..0abf94b115 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1089,10 +1089,12 @@ def test_draft_order_complete_fails_with_invalid_tax_app(
draft_order,
channel_USD,
tax_app,
- tax_data_response, # noqa: F811
+ tax_data_response_factory,
):
# given
- mock_request.return_value = tax_data_response
+ mock_request.return_value = tax_data_response_factory(
+ lines_length=draft_order.lines.count()
+ )
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
@@ -1120,26 +1122,25 @@ def test_draft_order_complete_fails_with_invalid_tax_app(
order.refresh_from_db()
assert not order.should_refresh_prices
- assert order.tax_error == "Empty tax data."
+ assert order.tax_error == "Configured tax app doesn't exist."
@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,
channel_USD,
tax_app,
- tax_data_response, # noqa: F811
+ tax_data_response_factory, # noqa: F811
):
# given
- mock_request.return_value = tax_data_response
- mock_validate_tax_data.return_value = False
+ mock_request.return_value = tax_data_response_factory(
+ lines_length=draft_order.lines.count()
+ )
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
@@ -1173,21 +1174,20 @@ 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,
channel_USD,
tax_app,
- tax_data_response, # noqa: F811
+ tax_data_response_factory, # noqa: F811
):
# given
- mock_request.return_value = tax_data_response
- mock_validate_tax_data.return_value = False
+ mock_request.return_value = tax_data_response_factory(
+ lines_length=draft_order.lines.count()
+ )
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index d149491e8d..3af8c9139e 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -2413,7 +2413,7 @@ def test_transaction_create_create_event_message_limit_exceeded(
transaction = order_with_lines.payment_transactions.first()
event = transaction.events.last()
- assert event.message == transaction_msg[:509] + "..."
+ assert event.message == transaction_msg[:511] + "…"
assert event.psp_reference == transaction_reference
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 26d90c6d7c..1e6dfb43c7 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -3223,7 +3223,7 @@ def test_transaction_event_report_message_limit_exceeded(
assert event.app_identifier == app_api_client.app.identifier
assert event.app == app_api_client.app
assert event.user is None
- assert event.message == message[:509] + "..."
+ assert event.message == message[:511] + "…"
def test_transaction_event_report_empty_message(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 671250df91..ee536d3392 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -2721,7 +2721,7 @@ def test_for_checkout_too_long_message_in_response(
mocked_initialize=mocked_initialize,
charged_value=expected_amount,
returned_data=expected_response["data"],
- expected_message=expected_response["message"][:509] + "...",
+ expected_message=expected_response["message"][:511] + "…",
)
assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index c8eaec48f2..f26ade42de 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -2301,7 +2301,7 @@ def test_for_order_too_long_message_in_response(
mocked_process=mocked_process,
charged_value=expected_amount,
returned_data=None,
- expected_message=expected_response["message"][:509] + "...",
+ expected_message=expected_response["message"][:511] + "…",
)
assert (
"Value for field: message in response of transaction action webhook "
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 2136ca59bf..d37a8b5e33 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -3425,7 +3425,7 @@ def test_transaction_uodate_transaction_event_message_limit_exceeded(
transaction = order_with_lines.payment_transactions.first()
event = transaction.events.last()
- assert event.message == transaction_msg[:509] + "..."
+ assert event.message == transaction_msg[:511] + "…"
assert event.psp_reference == transaction_reference
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index d8495431e1..6a159bed3c 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -38,7 +38,6 @@ 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_STATUS, OrderStatus
from .base_calculations import base_order_line_total, calculate_prices
@@ -199,7 +198,10 @@ def calculate_taxes(
)
except TaxDataError as e:
if str(e) != TaxDataErrorMessage.EMPTY:
- logger.warning(str(e), extra=order_info_for_logs(order, lines))
+ extra = order_info_for_logs(order, lines)
+ if e.errors:
+ extra["errors"] = e.errors
+ logger.warning(str(e), extra=extra)
order.tax_error = str(e)
if not should_charge_tax:
@@ -224,7 +226,10 @@ def calculate_taxes(
)
except TaxDataError as e:
if str(e) != TaxDataErrorMessage.EMPTY:
- logger.warning(str(e), extra=order_info_for_logs(order, lines))
+ extra = order_info_for_logs(order, lines)
+ if e.errors:
+ extra["errors"] = e.errors
+ logger.warning(str(e), extra=extra)
order.tax_error = str(e)
else:
remove_tax(order, lines, prices_entered_with_tax)
@@ -248,10 +253,12 @@ def _calculate_and_add_tax(
# In Saleor 4.0 `tax_app_identifier` should be required and the flow should
# be dropped.
_recalculate_with_plugins(manager, order, lines, prices_entered_with_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)
+ # Get the taxes calculated with apps and apply to order.
+ # We should allow empty tax_data in case any tax webhook has not been
+ # configured - handled by `allowed_empty_tax_data`
+ tax_data = _get_taxes_for_order(
+ order, tax_app_identifier, manager, allowed_empty_tax_data=True
+ )
_apply_tax_data(order, lines, tax_data, prices_entered_with_tax)
else:
_call_plugin_or_tax_app(
@@ -295,11 +302,35 @@ def _call_plugin_or_tax_app(
if order.tax_error:
raise TaxDataError(order.tax_error)
else:
+ tax_data = _get_taxes_for_order(order, tax_app_identifier, manager)
+ _apply_tax_data(order, lines, tax_data, prices_entered_with_tax)
+
+
+def _get_taxes_for_order(
+ order: "Order",
+ tax_app_identifier: str | None,
+ manager: "PluginsManager",
+ allowed_empty_tax_data: bool = False,
+):
+ """Get taxes for order from tax apps.
+
+ The `allowed_empty_tax_data` flag prevents an error from being raised when tax data
+ is missing due to the absence of a configured tax app.
+ """
+ tax_data = None
+ try:
tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
+ except TaxDataError as e:
+ raise e from e
+ finally:
+ # log in case the tax_data is missing
if tax_data is None:
log_address_if_validation_skipped_for_order(order, logger)
- validate_tax_data(tax_data, lines)
- _apply_tax_data(order, lines, tax_data, prices_entered_with_tax)
+
+ if not tax_data and not allowed_empty_tax_data:
+ raise TaxDataError(TaxDataErrorMessage.EMPTY)
+
+ return tax_data
def _recalculate_with_plugins(
diff --git a/saleor/order/models.py b/saleor/order/models.py
index bce6f0c59e..6019809399 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -21,6 +21,7 @@ from ..app.models import App
from ..channel.models import Channel
from ..core.db.fields import MoneyField, TaxedMoneyField
from ..core.models import ModelWithExternalReference, ModelWithMetadata
+from ..core.taxes import TAX_ERROR_FIELD_LENGTH
from ..core.units import WeightUnits
from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.weight import zero_weight
@@ -357,7 +358,9 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
# this field is used only for draft/unconfirmed orders
should_refresh_prices = models.BooleanField(default=True)
tax_exemption = models.BooleanField(default=False)
- tax_error = models.CharField(max_length=255, null=True, blank=True)
+ tax_error = models.CharField(
+ max_length=TAX_ERROR_FIELD_LENGTH, null=True, blank=True
+ )
objects = OrderManager()
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index e0a86faea6..d9ad32f40f 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -9,6 +9,7 @@ from prices import Money, TaxedMoney
from ...core.prices import quantize_price
from ...core.taxes import (
TaxData,
+ TaxDataError,
TaxDataErrorMessage,
TaxError,
TaxLineData,
@@ -25,6 +26,7 @@ from ...tax import TaxCalculationStrategy
from ...tax.calculations.order import update_order_prices_with_flat_rates
from ...tax.utils import get_tax_calculation_strategy_for_order
from .. import OrderStatus, calculations
+from ..calculations import logger
from ..interface import OrderTaxedPricesData
@@ -1508,7 +1510,6 @@ 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")
@@ -1517,17 +1518,17 @@ 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,
+ tax_data_response,
):
# given
- mock_validate_tax_data.return_value = False
-
order = order_with_lines
order.channel.tax_configuration.tax_app_id = "test.app"
order.channel.tax_configuration.save()
+ mock_get_taxes.return_value = tax_data_response
+
fetch_kwargs = {
"order": order,
"manager": get_plugins_manager(allow_replica=False),
@@ -1615,11 +1616,12 @@ def test_calculate_taxes_empty_tax_data_logging_address(
("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(
[email protected](logger, "warning")
+def test_fetch_order_data_tax_data_with_tax_data_error(
+ mocked_logger,
prices_entered_with_tax,
tax_app_id,
order_with_lines,
- caplog,
):
# given
order = order_with_lines
@@ -1629,24 +1631,9 @@ def test_fetch_order_data_tax_data_with_negative_values(
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"),
- ),
- ],
- )
-
+ error_msg = "Invalid tax data"
+ errors = [{"error1": "Negative tax data"}, {"error2": "Invalid tax data"}]
+ returned_tax_error = TaxDataError(message=error_msg, errors=errors)
zero_money = zero_taxed_money(order.currency)
zero_prices = OrderTaxedPricesData(
undiscounted_price=zero_money,
@@ -1659,7 +1646,7 @@ def test_fetch_order_data_tax_data_with_negative_values(
"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),
+ "get_taxes_for_order": Mock(side_effect=returned_tax_error),
}
manager = Mock(**manager_methods)
@@ -1667,101 +1654,31 @@ def test_fetch_order_data_tax_data_with_negative_values(
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)
+ assert order.tax_error == error_msg
+ assert mocked_logger.call_count == 1
+ assert len(mocked_logger.call_args) == 2
+ assert mocked_logger.call_args[0][0] == error_msg
+ assert mocked_logger.call_args[1]["extra"]["errors"] == errors
@pytest.mark.parametrize(
- ("prices_entered_with_tax", "tax_app_id"),
- [(True, None), (True, "test.app"), (False, None), (False, "test.app")],
+ "prices_entered_with_tax",
+ [True, False],
)
-def test_fetch_order_data_tax_data_with_wrong_number_of_lines(
[email protected](logger, "warning")
+def test_fetch_order_data_tax_data_missing_tax_id_empty_tax_data(
+ mocked_logger,
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.tax_app_id = None
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,
@@ -1774,7 +1691,7 @@ def test_fetch_order_data_tax_data_with_price_overflow(
"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),
+ "get_taxes_for_order": Mock(return_value=None),
}
manager = Mock(**manager_methods)
@@ -1782,9 +1699,8 @@ def test_fetch_order_data_tax_data_with_price_overflow(
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)
+ assert not order.tax_error
+ assert mocked_logger.call_count == 0
@patch("saleor.plugins.avatax.plugin.get_order_tax_data")
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index c8f39910bb..a08551a930 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1809,7 +1809,7 @@ def test_create_transaction_event_from_request_and_webhook_response_message_loo_
assert event.amount_value == event_amount
assert event.created_at == datetime.datetime.fromisoformat(event_time)
assert event.external_url == event_url
- assert event.message == event_message[:509] + "..."
+ assert event.message == event_message[:511] + "…"
assert event.type == event_type
assert len(caplog.records) == 1
assert caplog.records[0].message == (
@@ -2719,7 +2719,7 @@ def test_create_transaction_event_message_limit_exceeded(
transaction.refresh_from_db()
assert transaction.events.count() == 2
event = transaction.events.last()
- assert event.message == message[:509] + "..."
+ assert event.message == message[:511] + "…"
assert len(caplog.records) == 1
assert caplog.records[0].message == (
"Value for field: message in response of transaction action webhook "
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 6f9a73b539..827d44add1 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -11,6 +11,7 @@ from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import IntegrityError, transaction
from django.db.models import Q
+from django.template.defaultfilters import truncatechars
from django.utils import timezone
from ..account.models import User
@@ -1002,11 +1003,7 @@ def parse_transaction_action_data(
def truncate_transaction_event_message(message: str):
- return (
- message[: TRANSACTION_EVENT_MSG_MAX_LENGTH - 3] + "..."
- if len(message) > TRANSACTION_EVENT_MSG_MAX_LENGTH
- else message
- )
+ return truncatechars(message, TRANSACTION_EVENT_MSG_MAX_LENGTH)
def get_failed_transaction_event_type_for_request_event(
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 044256980c..26c97d5372 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -15,7 +15,7 @@ from ..core.db.connection import allow_writer
from ..core.models import EventDelivery
from ..core.payments import PaymentInterface
from ..core.prices import quantize_price
-from ..core.taxes import TaxData, TaxType, zero_money, zero_taxed_money
+from ..core.taxes import TaxData, TaxDataError, TaxType, zero_money, zero_taxed_money
from ..graphql.core import SaleorContext
from ..order import base_calculations as base_order_calculations
from ..order.base_calculations import (
@@ -639,7 +639,7 @@ class PluginsManager(PaymentInterface):
) -> TaxData | None:
if pregenerated_subscription_payloads is None:
pregenerated_subscription_payloads = {}
- return self.__run_plugin_method_until_first_success(
+ return self.__run_tax_method_until_first_success(
"get_taxes_for_checkout",
checkout_info,
lines,
@@ -651,13 +651,40 @@ class PluginsManager(PaymentInterface):
# Note: this method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from plugin to core modules.
def get_taxes_for_order(self, order: "Order", app_identifier) -> TaxData | None:
- return self.__run_plugin_method_until_first_success(
+ return self.__run_tax_method_until_first_success(
"get_taxes_for_order",
order,
app_identifier,
channel_slug=order.channel.slug,
)
+ def __run_tax_method_until_first_success(
+ self,
+ method_name: str,
+ *args,
+ channel_slug: str | None,
+ **kwargs,
+ ) -> TaxData | None:
+ plugins = self.get_plugins(channel_slug=channel_slug, active_only=True)
+ default_value = None
+ error = None
+ if plugins:
+ # try to get the proper response from the plugins; in case any plugin
+ # return proper response, raise an error from last plugin
+ for plugin in plugins:
+ try:
+ tax_data = self.__run_method_on_single_plugin(
+ plugin, method_name, default_value, *args, **kwargs
+ )
+ except TaxDataError as e:
+ error = e
+ continue
+ if tax_data is not None:
+ return tax_data
+ if error:
+ raise error
+ return default_value
+
def preprocess_order_creation(
self,
checkout_info: "CheckoutInfo",
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index d62e05015e..1c392bc0d9 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -47,7 +47,6 @@ from ..tests.sample_plugins import (
InactivePaymentGateway,
PluginInactive,
PluginSample,
- sample_tax_data,
)
@@ -537,49 +536,6 @@ def test_manager_uses_get_tax_rate_choices(plugins, tax_rate_list):
assert tax_rate_list == PluginsManager(plugins=plugins).get_tax_rate_type_choices()
-def sample_none_data(obj):
- return None
-
-
- ("plugins", "expected_tax_data"),
- [
- ([], sample_none_data),
- (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
- ],
-)
-def test_manager_get_taxes_for_checkout(
- checkout,
- plugins,
- expected_tax_data,
-):
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- app_identifier = None
- assert PluginsManager(plugins=plugins).get_taxes_for_checkout(
- checkout_info, lines, app_identifier
- ) == expected_tax_data(checkout)
-
-
- ("plugins", "expected_tax_data"),
- [
- ([], sample_none_data),
- (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
- ],
-)
-def test_manager_get_taxes_for_order(
- order,
- plugins,
- expected_tax_data,
-):
- app_identifier = None
- assert PluginsManager(plugins=plugins).get_taxes_for_order(
- order, app_identifier
- ) == expected_tax_data(order)
-
-
def test_manager_sale_created(promotion_converted_from_sale):
plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
diff --git a/saleor/plugins/tests/test_manager_get_taxes.py b/saleor/plugins/tests/test_manager_get_taxes.py
new file mode 100644
index 0000000000..83f07cc712
--- /dev/null
+++ b/saleor/plugins/tests/test_manager_get_taxes.py
@@ -0,0 +1,210 @@
+from unittest.mock import patch
+
+import pytest
+
+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ...core.taxes import TaxDataError
+from ..manager import PluginsManager, get_plugins_manager
+from ..tests.sample_plugins import sample_tax_data
+
+
+def sample_none_data(obj):
+ return None
+
+
+ ("plugins", "expected_tax_data"),
+ [
+ ([], sample_none_data),
+ (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
+ ],
+)
+def test_manager_get_taxes_for_checkout(
+ checkout,
+ plugins,
+ expected_tax_data,
+):
+ # given
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ app_identifier = None
+
+ # when
+ tax_data = PluginsManager(plugins=plugins).get_taxes_for_checkout(
+ checkout_info, lines, app_identifier
+ )
+
+ # then
+ assert tax_data == expected_tax_data(checkout)
+
+
+@patch(
+ "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_checkout",
+ side_effect=TaxDataError("test error"),
+)
+def test_manager_get_taxes_for_checkout_raises_error(
+ mocked_get_taxes_for_checkout,
+ checkout,
+):
+ # given
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ app_identifier = None
+ plugins = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ PluginsManager(plugins=plugins).get_taxes_for_checkout(
+ checkout_info, lines, app_identifier
+ )
+
+ mocked_get_taxes_for_checkout.assert_called_once()
+
+
+def test_manager_get_taxes_for_checkout_raises_no_active_plugin(
+ checkout,
+):
+ # given
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ app_identifier = None
+
+ # when
+ tax_data = PluginsManager(plugins=[]).get_taxes_for_checkout(
+ checkout_info, lines, app_identifier
+ )
+
+ # then
+ assert tax_data is None
+
+
+ "plugins",
+ [
+ # first plugin that raises an error
+ [
+ "saleor.plugins.webhook.plugin.WebhookPlugin",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ],
+ # as a second plugin that raises an error
+ [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.webhook.plugin.WebhookPlugin",
+ ],
+ ],
+)
+@patch(
+ "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_checkout",
+ side_effect=TaxDataError("test error"),
+)
+def test_manager_get_taxes_for_checkout_multiple_plugins(
+ mocked_get_taxes_for_checkout,
+ plugins,
+ checkout,
+):
+ # given
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ app_identifier = None
+
+ # when
+ tax_data = PluginsManager(plugins).get_taxes_for_checkout(
+ checkout_info, lines, app_identifier
+ )
+
+ # then
+ assert tax_data == sample_tax_data(checkout)
+
+
+ ("plugins", "expected_tax_data"),
+ [
+ ([], sample_none_data),
+ (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
+ ],
+)
+def test_manager_get_taxes_for_order(
+ order,
+ plugins,
+ expected_tax_data,
+):
+ # given
+ app_identifier = None
+
+ # when
+ tax_data = PluginsManager(plugins=plugins).get_taxes_for_order(
+ order, app_identifier
+ )
+
+ # then
+ assert tax_data == expected_tax_data(order)
+
+
+@patch(
+ "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_order",
+ side_effect=TaxDataError("test error"),
+)
+def test_manager_get_taxes_for_order_raises_error(
+ mocked_get_taxes_for_order,
+ order,
+):
+ # given
+ app_identifier = None
+ plugins = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ PluginsManager(plugins=plugins).get_taxes_for_order(order, app_identifier)
+
+ mocked_get_taxes_for_order.assert_called_once()
+
+
+def test_manager_get_taxes_for_order_raises_no_active_plugin(
+ order,
+):
+ # given
+ app_identifier = None
+
+ # when
+ tax_data = PluginsManager(plugins=[]).get_taxes_for_order(order, app_identifier)
+
+ # then
+ assert tax_data is None
+
+
+ "plugins",
+ [
+ # first plugin that raises an error
+ [
+ "saleor.plugins.webhook.plugin.WebhookPlugin",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ],
+ # as a second plugin that raises an error
+ [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.webhook.plugin.WebhookPlugin",
+ ],
+ ],
+)
+@patch(
+ "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_order",
+ side_effect=TaxDataError("test error"),
+)
+def test_manager_get_taxes_for_order_multiple_plugins(
+ mocked_get_taxes_for_order,
+ plugins,
+ order,
+):
+ # given
+ app_identifier = None
+
+ # when
+ tax_data = PluginsManager(plugins).get_taxes_for_order(order, app_identifier)
+
+ # then
+ assert tax_data == sample_tax_data(order)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 98cfe2ed40..cde83d153b 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -8,6 +8,8 @@ from typing import TYPE_CHECKING, Any, Final, Optional, Union
import graphene
from django.conf import settings
+from django.template.defaultfilters import truncatechars
+from pydantic import ValidationError
from ...app.models import App
from ...channel.models import Channel
@@ -16,7 +18,7 @@ from ...checkout.models import Checkout
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
from ...core.notify import NotifyEventType
-from ...core.taxes import TaxData, TaxType
+from ...core.taxes import TAX_ERROR_FIELD_LENGTH, TaxData, TaxDataError, TaxType
from ...core.utils import build_absolute_uri
from ...core.utils.json_serializer import CustomJsonEncoder
from ...csv.notifications import get_default_export_payload
@@ -29,6 +31,7 @@ from ...graphql.webhook.utils import (
get_pregenerated_subscription_payload,
get_subscription_query_hash,
)
+from ...order.models import Order
from ...payment import PaymentError, TransactionKind
from ...payment.interface import (
GatewayResponse,
@@ -107,7 +110,7 @@ from ...webhook.transport.shipping import (
parse_list_shipping_methods_response,
)
from ...webhook.transport.synchronous.transport import (
- trigger_all_webhooks_sync,
+ trigger_taxes_all_webhooks_sync,
trigger_transaction_request,
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
@@ -159,7 +162,6 @@ if TYPE_CHECKING:
# (FedEx, UPS, TNT, DHL).
CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT: Final[int] = 3600 * 12
-
logger = logging.getLogger(__name__)
@@ -3387,9 +3389,10 @@ class WebhookPlugin(BasePlugin):
event_type: str,
app_identifier: str,
payload_gen: Callable,
+ expected_lines_count: int,
subscriptable_object=None,
pregenerated_subscription_payloads: dict | None = None,
- ):
+ ) -> TaxData:
if pregenerated_subscription_payloads is None:
pregenerated_subscription_payloads = {}
app = (
@@ -3402,14 +3405,14 @@ class WebhookPlugin(BasePlugin):
.first()
)
if app is None:
- logger.warning("Configured tax app doesn't exists.")
- return None
+ msg = "Configured tax app doesn't exist."
+ logger.warning(msg)
+ raise TaxDataError(msg)
webhook = get_webhooks_for_event(event_type, apps_ids=[app.id]).first()
if webhook is None:
- logger.warning(
- "Configured tax app's webhook for checkout taxes doesn't exists."
- )
- return None
+ msg = "Configured tax app's webhook for taxes calculation doesn't exists."
+ logger.warning(msg)
+ raise TaxDataError(msg)
request_context = initialize_request(
self.requestor,
@@ -3431,7 +3434,19 @@ class WebhookPlugin(BasePlugin):
requestor=self.requestor,
pregenerated_subscription_payload=pregenerated_subscription_payload,
)
- return parse_tax_data(response)
+ try:
+ tax_data = parse_tax_data(response, expected_lines_count)
+ except ValidationError as e:
+ errors = e.errors()
+ logger.warning(
+ "Webhook response for event %s is invalid: %s",
+ event_type,
+ str(e),
+ extra={"errors": errors},
+ )
+ error_msg = truncatechars(str(e), TAX_ERROR_FIELD_LENGTH)
+ raise TaxDataError(error_msg, errors=errors) from e
+ return tax_data
def get_taxes_for_checkout(
self,
@@ -3440,10 +3455,11 @@ class WebhookPlugin(BasePlugin):
app_identifier,
previous_value,
pregenerated_subscription_payloads: dict | None = None,
- ) -> Optional["TaxData"]:
+ ) -> TaxData | None:
if pregenerated_subscription_payloads is None:
pregenerated_subscription_payloads = {}
event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ lines_count = len(lines)
if app_identifier:
return self.__run_tax_webhook(
event_type,
@@ -3451,16 +3467,20 @@ class WebhookPlugin(BasePlugin):
lambda: generate_checkout_payload_for_tax_calculation(
checkout_info, lines
),
+ lines_count,
checkout_info.checkout,
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
- return trigger_all_webhooks_sync(
+ # This is deprecated flow, kept to maintain backward compatibility.
+ # In Saleor 4.0 `tax_app_identifier` should be required and the flow should
+ # be dropped.
+ return trigger_taxes_all_webhooks_sync(
event_type,
lambda: generate_checkout_payload_for_tax_calculation(
checkout_info,
lines,
),
- parse_tax_data,
+ lines_count,
checkout_info.checkout,
self.requestor,
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
@@ -3468,19 +3488,24 @@ class WebhookPlugin(BasePlugin):
def get_taxes_for_order(
self, order: "Order", app_identifier, previous_value
- ) -> Optional["TaxData"]:
+ ) -> TaxData | None:
event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ lines_count = order.lines.count()
if app_identifier:
return self.__run_tax_webhook(
event_type,
app_identifier,
lambda: generate_order_payload_for_tax_calculation(order),
+ lines_count,
order,
)
- return trigger_all_webhooks_sync(
+ # This is deprecated flow, kept to maintain backward compatibility.
+ # In Saleor 4.0 `tax_app_identifier` should be required and the flow should
+ # be dropped.
+ return trigger_taxes_all_webhooks_sync(
WebhookEventSyncType.ORDER_CALCULATE_TAXES,
lambda: generate_order_payload_for_tax_calculation(order),
- parse_tax_data,
+ lines_count,
order,
self.requestor,
)
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index a99e4e210c..b706411b57 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -8,7 +8,7 @@ from freezegun import freeze_time
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....core import EventDeliveryStatus
from ....core.models import EventDelivery
-from ....core.taxes import TaxType
+from ....core.taxes import TaxDataError, TaxType
from ....graphql.webhook.utils import get_subscription_query_hash
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.payloads import generate_order_payload_for_tax_calculation
@@ -77,7 +77,7 @@ def test_get_taxes_for_order(
assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, order.lines.count())
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -195,7 +195,7 @@ def test_get_taxes_for_order_with_sync_subscription(
assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, order.lines.count())
@freeze_time()
@@ -247,7 +247,7 @@ def test_get_taxes_for_checkout_with_sync_subscription(
assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, checkout.lines.count())
@freeze_time()
@@ -302,4 +302,289 @@ def test_get_taxes_for_checkout_with_sync_subscription_with_pregenerated_payload
assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, checkout.lines.count())
+
+
+def test_get_taxes_for_checkout_with_app_identifier_app_missing(
+ checkout_info, webhook_plugin
+):
+ # given
+ app_identifier = "missing_app"
+ plugin = webhook_plugin()
+
+ # when & then
+ with pytest.raises(TaxDataError, match="Configured tax app doesn't exist."):
+ plugin.get_taxes_for_checkout(
+ checkout_info, checkout_info.lines, app_identifier, None
+ )
+
+
+def test_get_taxes_for_checkout_with_app_identifier_webhook_is_missing(
+ checkout_info, webhook_plugin, app
+):
+ # given
+ plugin = webhook_plugin()
+
+ # when & then
+ with pytest.raises(
+ TaxDataError,
+ match="Configured tax app's webhook for taxes calculation doesn't exists.",
+ ):
+ plugin.get_taxes_for_checkout(
+ checkout_info, checkout_info.lines, app.identifier, None
+ )
+
+
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_checkout_with_app_identifier_invalid_response(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response_factory,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ # mock returning invalid data - tax_rate above 100
+ mock_request.return_value = tax_data_response_factory(shipping_tax_rate=120)
+ mock_generate_payload.return_value = expected_payload
+ plugin = webhook_plugin()
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when
+ with pytest.raises(TaxDataError):
+ plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
+
+
+@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_checkout_with_app_identifier(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = tax_data_response
+ mock_generate_payload.return_value = expected_payload
+ plugin = webhook_plugin()
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when
+ tax_data = plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
+
+ # then
+ mock_generate_payload.assert_called_once_with(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ subscribable_object=checkout,
+ subscription_query=subscription_query,
+ request=ANY, # SaleorContext,
+ app=tax_app,
+ )
+ mock_request.assert_called_once()
+ assert not EventDelivery.objects.exists()
+
+ delivery = mock_request.mock_calls[0].args[0]
+ assert delivery.payload.get_payload() == json.dumps(expected_payload)
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(tax_data_response, checkout.lines.count())
+
+
+def test_get_taxes_for_order_with_app_identifier_app_missing(order, webhook_plugin):
+ # given
+ app_identifier = "missing_app"
+ plugin = webhook_plugin()
+
+ # when & then
+ with pytest.raises(TaxDataError, match="Configured tax app doesn't exist."):
+ plugin.get_taxes_for_order(order, app_identifier, None)
+
+
+def test_get_taxes_for_order_with_app_identifier_webhook_is_missing(
+ order, webhook_plugin, app
+):
+ # given
+ plugin = webhook_plugin()
+
+ # when & then
+ with pytest.raises(
+ TaxDataError,
+ match="Configured tax app's webhook for taxes calculation doesn't exists.",
+ ):
+ plugin.get_taxes_for_order(order, app.identifier, None)
+
+
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_order_with_app_identifier_invalid_response(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response_factory,
+ order,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ # mock returning invalid data - tax_rate above 100
+ mock_request.return_value = tax_data_response_factory(shipping_tax_rate=120)
+ mock_generate_payload.return_value = expected_payload
+ plugin = webhook_plugin()
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ plugin.get_taxes_for_order(order, app_identifier, None)
+
+
+@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_order_with_app_identifier(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ order,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ mock_request.return_value = tax_data_response
+ mock_generate_payload.return_value = expected_payload
+ plugin = webhook_plugin()
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when
+ tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
+
+ # then
+ mock_generate_payload.assert_called_once_with(
+ event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ subscribable_object=order,
+ subscription_query=subscription_query,
+ request=ANY, # SaleorContext,
+ app=tax_app,
+ )
+ mock_request.assert_called_once()
+ assert not EventDelivery.objects.exists()
+
+ delivery = mock_request.mock_calls[0].args[0]
+ assert delivery.payload.get_payload() == json.dumps(expected_payload)
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(tax_data_response, order.lines.count())
+
+
+@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_order_with_app_identifier_empty_response(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ order,
+ tax_app,
+):
+ # given
+ mock_request.return_value = None
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ mock_generate_payload.return_value = expected_payload
+ plugin = webhook_plugin()
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ plugin.get_taxes_for_order(order, app_identifier, None)
+
+
+@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_checkout_with_app_identifier_empty_response(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = None
+ mock_generate_payload.return_value = expected_payload
+ plugin = webhook_plugin()
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
diff --git a/saleor/tax/tests/test_utils.py b/saleor/tax/tests/test_utils.py
index c956db1a37..88ac2d89d3 100644
--- a/saleor/tax/tests/test_utils.py
+++ b/saleor/tax/tests/test_utils.py
@@ -1,14 +1,10 @@
-from decimal import Decimal
-
import pytest
-from ...core.taxes import TaxData, TaxDataError, TaxLineData
from ...core.utils.country import get_active_country
from ..utils import (
get_charge_taxes,
get_display_gross_prices,
get_tax_app_id,
- validate_tax_data,
)
@@ -115,113 +111,3 @@ def test_get_tax_country_fallbacks_to_channel_country(channel_USD):
# then
assert 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.py
index 7223670a57..5d0e5c7a15 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -6,8 +6,6 @@ from typing import TYPE_CHECKING, Optional
from django.conf import settings
from prices import TaxedMoney
-from ..core.prices import MAXIMUM_PRICE
-from ..core.taxes import TaxData, TaxDataError, TaxDataErrorMessage
from ..core.utils.country import get_active_country
from . import TaxCalculationStrategy
@@ -259,78 +257,3 @@ 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: TaxData | None,
- 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: TaxData | None) -> 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: TaxData | None, 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: TaxData | None) -> 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 False
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 2ccdc878cc..3171bc5006 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -689,18 +689,32 @@ def tax_line_data_response():
@pytest.fixture
-def tax_data_response(tax_line_data_response):
- return {
- "currency": "PLN",
- "total_net_amount": 12.34,
- "total_gross_amount": 12.34,
- "subtotal_net_amount": 12.34,
- "subtotal_gross_amount": 12.34,
- "shipping_price_gross_amount": 12.34,
- "shipping_price_net_amount": 12.34,
- "shipping_tax_rate": 23,
- "lines": [tax_line_data_response] * 5,
- }
+def tax_data_response(tax_data_response_factory):
+ return tax_data_response_factory()
+
+
+def tax_data_response_factory(tax_line_data_response):
+ def factory(
+ shipping_price_gross_amount=12.34,
+ shipping_price_net_amount=12.34,
+ shipping_tax_rate=23,
+ lines_length=5,
+ ):
+ lines = [tax_line_data_response] * lines_length
+ return {
+ "currency": "PLN",
+ "total_net_amount": 12.34,
+ "total_gross_amount": 12.34,
+ "subtotal_net_amount": 12.34,
+ "subtotal_gross_amount": 12.34,
+ "shipping_price_gross_amount": shipping_price_gross_amount,
+ "shipping_price_net_amount": shipping_price_net_amount,
+ "shipping_tax_rate": shipping_tax_rate,
+ "lines": lines,
+ }
+
+ return factory
@pytest.fixture
diff --git a/saleor/webhook/response_schemas/annotations.py b/saleor/webhook/response_schemas/annotations.py
index 9f39a437ca..4c3e5ba486 100644
--- a/saleor/webhook/response_schemas/annotations.py
+++ b/saleor/webhook/response_schemas/annotations.py
@@ -7,8 +7,10 @@ from pydantic_core import PydanticUseDefault
from ...core.utils.metadata_manager import metadata_is_valid
+M = TypeVar("M")
-def skip_invalid_metadata(value: Any) -> Any:
+
+def skip_invalid_metadata(value: M) -> M:
if not metadata_is_valid(value):
raise PydanticUseDefault()
return value
diff --git a/saleor/webhook/response_schemas/shipping.py b/saleor/webhook/response_schemas/shipping.py
index 0c5ec2b653..5aa752e222 100644
--- a/saleor/webhook/response_schemas/shipping.py
+++ b/saleor/webhook/response_schemas/shipping.py
@@ -41,9 +41,9 @@ OnErrorSkipShippingMethod = Annotated[T, WrapValidator(skip_invalid_shipping_met
class ShippingMethodSchema(BaseModel):
- id: str = Field(coerce_numbers_to_str=True)
- name: str = Field(max_length=name_max_length)
- amount: Decimal = Field(ge=0)
+ id: Annotated[str, Field(coerce_numbers_to_str=True)]
+ name: Annotated[str, Field(max_length=name_max_length)]
+ amount: Annotated[Decimal, Field(ge=0)]
currency: str
maximum_delivery_days: Annotated[int, Field(ge=0)] | None = None
minimum_delivery_days: Annotated[int, Field(ge=0)] | None = None
diff --git a/saleor/webhook/response_schemas/taxes.py b/saleor/webhook/response_schemas/taxes.py
new file mode 100644
index 0000000000..8168bbc195
--- /dev/null
+++ b/saleor/webhook/response_schemas/taxes.py
@@ -0,0 +1,36 @@
+from decimal import Decimal
+from typing import Annotated
+
+from pydantic import BaseModel, Field, ValidationInfo, field_validator
+
+from ...core.prices import MAXIMUM_PRICE
+
+
+class LineCalculateTaxesSchema(BaseModel):
+ tax_rate: Annotated[Decimal, Field(ge=0, le=100)]
+ total_gross_amount: Annotated[Decimal, Field(ge=0, le=MAXIMUM_PRICE)]
+ total_net_amount: Annotated[Decimal, Field(ge=0, le=MAXIMUM_PRICE)]
+
+
+class CalculateTaxesSchema(BaseModel):
+ shipping_tax_rate: Annotated[Decimal, Field(ge=0, le=100)]
+ shipping_price_gross_amount: Annotated[Decimal, Field(ge=0, le=MAXIMUM_PRICE)]
+ shipping_price_net_amount: Annotated[Decimal, Field(ge=0, le=MAXIMUM_PRICE)]
+ lines: list[LineCalculateTaxesSchema] = []
+
+ @field_validator("lines")
+ @classmethod
+ def clean_lines_length(
+ cls, lines: list[LineCalculateTaxesSchema], info: ValidationInfo
+ ):
+ context = info.context
+ if not context:
+ raise ValueError("Context is required to validate the number of lines.")
+
+ expected_line_count = context.get("expected_line_count")
+ if expected_line_count and len(lines) != expected_line_count:
+ raise ValueError(
+ f"Number of lines from tax data doesn't match the line number from order. "
+ f"Expected {expected_line_count} but got {len(lines)}."
+ )
+ return lines
diff --git a/saleor/webhook/tests/response_schemas/test_shipping.py b/saleor/webhook/tests/response_schemas/test_shipping.py
index c590d0b453..374c4da9ba 100644
--- a/saleor/webhook/tests/response_schemas/test_shipping.py
+++ b/saleor/webhook/tests/response_schemas/test_shipping.py
@@ -35,11 +35,32 @@ def decode_id(id):
},
# Optional fields not provided
{
- "id": 2, # Integer ID
+ "id": 2,
"name": "Express Shipping",
"amount": Decimal("20.00"),
"currency": "EUR",
},
+ # Amount as str
+ {
+ "id": 2,
+ "name": "Express Shipping",
+ "amount": "20.00",
+ "currency": "EUR",
+ },
+ # Amount as float
+ {
+ "id": "2",
+ "name": "Express Shipping",
+ "amount": 20.00,
+ "currency": "EUR",
+ },
+ # Amount as int
+ {
+ "id": 2,
+ "name": "Express Shipping",
+ "amount": 20,
+ "currency": "EUR",
+ },
# Metadata is empty, delivery days, and description as None
{
"id": "3",
@@ -78,7 +99,7 @@ def test_shipping_method_schema_valid(data):
# then
assert shipping_method_model.id == str(data["id"])
assert shipping_method_model.name == data["name"]
- assert shipping_method_model.amount == data["amount"]
+ assert shipping_method_model.amount == Decimal(data["amount"])
assert shipping_method_model.currency == data["currency"]
assert shipping_method_model.maximum_delivery_days == data.get(
"maximum_delivery_days"
@@ -201,9 +222,11 @@ def test_shipping_method_schema_invalid_metadata_skipped(metadata):
],
)
def test_shipping_method_schema_invalid(data):
- with pytest.raises(ValidationError):
+ with pytest.raises(ValidationError) as e:
ShippingMethodSchema.model_validate(data)
+ assert len(e.value.errors()) == 1
+
@pytest.mark.parametrize("data", [None, []])
def test_list_shipping_methods_schema_skipped_values(data):
diff --git a/saleor/webhook/tests/response_schemas/test_taxes.py b/saleor/webhook/tests/response_schemas/test_taxes.py
new file mode 100644
index 0000000000..d7a680c831
--- /dev/null
+++ b/saleor/webhook/tests/response_schemas/test_taxes.py
@@ -0,0 +1,270 @@
+from decimal import Decimal
+
+import pytest
+from pydantic import ValidationError
+
+from ....core.prices import MAXIMUM_PRICE
+from ...response_schemas.taxes import CalculateTaxesSchema, LineCalculateTaxesSchema
+
+
+ "data",
+ [
+ # Decimal values
+ {
+ "tax_rate": Decimal("20.12"),
+ "total_gross_amount": Decimal("100.33"),
+ "total_net_amount": Decimal("80.00"),
+ },
+ # String values with decimal points
+ {
+ "tax_rate": "20.12",
+ "total_gross_amount": "100.33",
+ "total_net_amount": "80.23",
+ },
+ # String values
+ {
+ "tax_rate": "20",
+ "total_gross_amount": "100",
+ "total_net_amount": "80",
+ },
+ # Integer values
+ {
+ "tax_rate": 20,
+ "total_gross_amount": 100,
+ "total_net_amount": 80,
+ },
+ # Float values
+ {
+ "tax_rate": 20.11,
+ "total_gross_amount": 100.21,
+ "total_net_amount": 80.32,
+ },
+ ],
+)
+def test_line_calculate_taxes_schema_valid(data):
+ # when
+ line_model = LineCalculateTaxesSchema.model_validate(data)
+
+ # then
+ assert line_model.tax_rate == Decimal(str(data["tax_rate"]))
+ assert line_model.total_gross_amount == Decimal(str(data["total_gross_amount"]))
+ assert line_model.total_net_amount == Decimal(str(data["total_net_amount"]))
+
+
+ "data",
+ [
+ # Negative tax_rate
+ {
+ "tax_rate": -5,
+ "total_gross_amount": 100,
+ "total_net_amount": Decimal("80.00"),
+ },
+ # Negative total_gross_amount
+ {
+ "tax_rate": 5,
+ "total_gross_amount": -100,
+ "total_net_amount": Decimal("80.00"),
+ },
+ # Negative total_net_amount
+ {
+ "tax_rate": 5,
+ "total_gross_amount": 100,
+ "total_net_amount": Decimal("-80.00"),
+ },
+ # Invalid tax_rate (greater than 100)
+ {
+ "tax_rate": Decimal("120.00"),
+ "total_gross_amount": Decimal("100.00"),
+ "total_net_amount": Decimal("80.00"),
+ },
+ # Invalid total_gross_amount (greater than MAXIMUM_PRICE)
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": 100000000000,
+ "total_net_amount": Decimal("80.00"),
+ },
+ # Invalid total_net_amount (greater than MAXIMUM_PRICE)
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": Decimal("100.00"),
+ "total_net_amount": Decimal("10000000000"),
+ },
+ ],
+)
+def test_line_calculate_taxes_schema_invalid(data):
+ """Test LineCalculateTaxesSchema with invalid data."""
+ with pytest.raises(ValidationError) as e:
+ LineCalculateTaxesSchema(**data)
+
+ assert len(e.value.errors()) == 1
+
+
+ "data",
+ [
+ {
+ "shipping_tax_rate": Decimal("10.00"),
+ "shipping_price_gross_amount": Decimal("110.00"),
+ "shipping_price_net_amount": Decimal("100.00"),
+ "lines": [
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": Decimal("120.00"),
+ "total_net_amount": Decimal("100.00"),
+ },
+ {
+ "tax_rate": "15.00",
+ "total_gross_amount": "115.00",
+ "total_net_amount": "100.00",
+ },
+ ],
+ },
+ {
+ "shipping_tax_rate": 10,
+ "shipping_price_gross_amount": 110,
+ "shipping_price_net_amount": 100,
+ "lines": [],
+ },
+ {
+ "shipping_tax_rate": "10.00",
+ "shipping_price_gross_amount": "110.00",
+ "shipping_price_net_amount": "100.00",
+ "lines": [
+ {
+ "tax_rate": "20.00",
+ "total_gross_amount": "120.00",
+ "total_net_amount": "100.00",
+ },
+ ],
+ },
+ ],
+)
+def test_calculate_taxes_schema_valid(data):
+ # given
+ expected_line_count = len(data["lines"])
+
+ # when
+ calculate_taxes_model = CalculateTaxesSchema.model_validate(
+ data, context={"expected_line_count": expected_line_count}
+ )
+
+ # then
+ assert calculate_taxes_model.shipping_tax_rate == Decimal(data["shipping_tax_rate"])
+ assert calculate_taxes_model.shipping_price_gross_amount == Decimal(
+ data["shipping_price_gross_amount"]
+ )
+ assert calculate_taxes_model.shipping_price_net_amount == Decimal(
+ data["shipping_price_net_amount"]
+ )
+ assert len(calculate_taxes_model.lines) == expected_line_count
+
+
+ ("data", "expected_line_count"),
+ [
+ # Invalid case with mismatched line count
+ (
+ {
+ "shipping_tax_rate": Decimal("10.00"),
+ "shipping_price_gross_amount": Decimal("110.00"),
+ "shipping_price_net_amount": Decimal("100.00"),
+ "lines": [
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": Decimal("120.00"),
+ "total_net_amount": Decimal("100.00"),
+ }
+ ],
+ },
+ 2,
+ ),
+ # Invalid case with negative shipping_price_gross_amount
+ (
+ {
+ "shipping_tax_rate": Decimal("10.00"),
+ "shipping_price_gross_amount": -111,
+ "shipping_price_net_amount": Decimal("100.00"),
+ "lines": [],
+ },
+ 0,
+ ),
+ # Invalid case with negative shipping_price_net_amount
+ (
+ {
+ "shipping_tax_rate": 10,
+ "shipping_price_gross_amount": 111,
+ "shipping_price_net_amount": -100,
+ "lines": [],
+ },
+ 0,
+ ),
+ # Invalid case with shipping_tax_rate greater than 100
+ (
+ {
+ "shipping_tax_rate": Decimal("120.00"),
+ "shipping_price_gross_amount": "110",
+ "shipping_price_net_amount": "100",
+ "lines": [
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": Decimal("120.00"),
+ "total_net_amount": Decimal("100.00"),
+ }
+ ],
+ },
+ 1,
+ ),
+ # Invalid case with shipping_price_gross_amount (greater than MAXIMUM_PRICE)
+ (
+ {
+ "shipping_tax_rate": Decimal("100.00"),
+ "shipping_price_gross_amount": MAXIMUM_PRICE + 1,
+ "shipping_price_net_amount": "100",
+ "lines": [
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": Decimal("120.00"),
+ "total_net_amount": Decimal("100.00"),
+ }
+ ],
+ },
+ 1,
+ ),
+ # Invalid case with shipping_price_net_amount (greater than MAXIMUM_PRICE)
+ (
+ {
+ "shipping_tax_rate": Decimal("100.00"),
+ "shipping_price_gross_amount": "100",
+ "shipping_price_net_amount": MAXIMUM_PRICE + 1,
+ "lines": [
+ {
+ "tax_rate": Decimal("20.00"),
+ "total_gross_amount": Decimal("120.00"),
+ "total_net_amount": Decimal("100.00"),
+ }
+ ],
+ },
+ 1,
+ ),
+ ],
+)
+def test_calculate_taxes_schema_invalid(data, expected_line_count):
+ """Test CalculateTaxesSchema with invalid data."""
+ with pytest.raises(ValidationError) as e:
+ CalculateTaxesSchema.model_validate(
+ data, context={"expected_line_count": expected_line_count}
+ )
+
+ assert len(e.value.errors()) == 1
+
+
+def test_calculate_taxes_schema_missing_context():
+ """Test CalculateTaxesSchema with invalid data."""
+ # given
+ data = {}
+
+ # when & then
+ with pytest.raises(ValidationError):
+ CalculateTaxesSchema.model_validate(data)
diff --git a/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py b/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py
index 43f724041b..203861efc4 100644
--- a/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py
+++ b/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py
@@ -4,7 +4,7 @@ from django.utils import timezone
from ...core.models import EventDelivery, EventPayload
from ..event_types import WebhookEventSyncType
-from ..transport.synchronous.transport import trigger_all_webhooks_sync
+from ..transport.synchronous.transport import trigger_taxes_all_webhooks_sync
from ..transport.utils import parse_tax_data
@@ -20,7 +20,7 @@ def test_not_trigger_sync_webhook_for_removed_app(
data = '{"key": "value"}'
# when
- trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+ trigger_taxes_all_webhooks_sync(event_type, lambda: data, parse_tax_data, [0])
# then
assert EventPayload.objects.count() == 0
diff --git a/saleor/webhook/tests/test_tax_webhook_tasks.py b/saleor/webhook/tests/test_tax_webhook_tasks.py
index ab53a1427b..acf3fe65de 100644
--- a/saleor/webhook/tests/test_tax_webhook_tasks.py
+++ b/saleor/webhook/tests/test_tax_webhook_tasks.py
@@ -6,7 +6,7 @@ from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
from ..event_types import WebhookEventSyncType
from ..models import Webhook, WebhookEvent
-from ..transport.synchronous import trigger_all_webhooks_sync
+from ..transport.synchronous import trigger_taxes_all_webhooks_sync
from ..transport.utils import parse_tax_data
@@ -50,9 +50,10 @@ def test_trigger_tax_webhook_sync(
webhook = tax_app.webhooks.get(name="tax-webhook-1")
webhook.subscription_query = None
webhook.save(update_fields=["subscription_query"])
+ lines_count = len(tax_data_response["lines"])
# when
- tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+ tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, lines_count)
# then
mock_request.assert_called_once()
@@ -63,7 +64,7 @@ def test_trigger_tax_webhook_sync(
assert delivery.status == EventDeliveryStatus.PENDING
assert delivery.event_type == event_type
assert delivery.webhook == webhook
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, lines_count)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -76,9 +77,10 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_first(
mock_request.side_effect = [tax_data_response, {}, {}]
event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
data = '{"key": "value"}'
+ lines_count = len(tax_data_response["lines"])
# when
- tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+ tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, lines_count)
# then
successful_webhook = tax_checkout_webhooks[0]
@@ -89,7 +91,7 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_first(
assert delivery.status == EventDeliveryStatus.PENDING
assert delivery.event_type == event_type
assert delivery.webhook == successful_webhook
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, lines_count)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -102,9 +104,10 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_last(
mock_request.side_effect = [{}, {}, tax_data_response]
event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
data = '{"key": "value"}'
+ lines_count = len(tax_data_response["lines"])
# when
- tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+ tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, lines_count)
# then
assert mock_request.call_count == 3
@@ -119,7 +122,7 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_last(
assert delivery.payload.get_payload() == data
assert delivery.webhook == webhook
- assert tax_data == parse_tax_data(tax_data_response)
+ assert tax_data == parse_tax_data(tax_data_response, lines_count)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -134,7 +137,7 @@ def test_trigger_tax_webhook_sync_invalid_webhooks(
data = '{"key": "value"}'
# when
- tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+ tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, 0)
# then
assert mock_request.call_count == len(tax_checkout_webhooks)
diff --git a/saleor/webhook/tests/test_tax_webhook_utils.py b/saleor/webhook/tests/test_tax_webhook_utils.py
index af0e867aba..f545fb27a0 100644
--- a/saleor/webhook/tests/test_tax_webhook_utils.py
+++ b/saleor/webhook/tests/test_tax_webhook_utils.py
@@ -1,10 +1,10 @@
import decimal
import pytest
+from pydantic import ValidationError
from ...core.taxes import TaxData
from ..transport.utils import (
- _unsafe_parse_tax_data,
_unsafe_parse_tax_line_data,
parse_tax_data,
)
@@ -45,45 +45,12 @@ def test_unsafe_parse_tax_line_data_decimalexception(tax_line_data_response):
_unsafe_parse_tax_line_data(tax_line_data_response)
-def test_unsafe_parse_tax_data_success(tax_data_response):
- # when
- tax_data = _unsafe_parse_tax_data(tax_data_response)
-
- # then
- assert not tax_data.shipping_price_gross_amount.compare(
- decimal.Decimal(tax_data_response["shipping_price_gross_amount"])
- )
- assert not tax_data.shipping_price_net_amount.compare(
- decimal.Decimal(tax_data_response["shipping_price_net_amount"])
- )
- assert tax_data.shipping_tax_rate == tax_data_response["shipping_tax_rate"]
- assert tax_data.lines == [
- _unsafe_parse_tax_line_data(line) for line in tax_data_response["lines"]
- ]
-
-
-def test_unsafe_parse_tax_data_keyerror(tax_data_response):
- # given
- tax_data_response["shipping_tax_rate_2"] = tax_data_response["shipping_tax_rate"]
- del tax_data_response["shipping_tax_rate"]
-
- # when
- with pytest.raises(KeyError):
- _unsafe_parse_tax_data(tax_data_response)
-
-
-def test_unsafe_parse_tax_data_decimalexception(tax_data_response):
+def test_parse_tax_data_success(tax_data_response):
# given
- tax_data_response["shipping_price_gross_amount"] = "invalid value"
-
- # when
- with pytest.raises(decimal.DecimalException):
- _unsafe_parse_tax_data(tax_data_response)
-
+ line_count = len(tax_data_response["lines"])
-def test_parse_tax_data_success(tax_data_response):
# when
- tax_data = parse_tax_data(tax_data_response)
+ tax_data = parse_tax_data(tax_data_response, line_count)
# then
assert isinstance(tax_data, TaxData)
@@ -93,23 +60,21 @@ def test_parse_tax_data_keyerror(tax_data_response):
# given
tax_data_response["shipping_tax_rate_2"] = tax_data_response["shipping_tax_rate"]
del tax_data_response["shipping_tax_rate"]
+ line_count = len(tax_data_response["lines"])
- # when
- tax_data = parse_tax_data(tax_data_response)
-
- # then
- assert tax_data is None
+ # when & then
+ with pytest.raises(ValidationError):
+ parse_tax_data(tax_data_response, line_count)
def test_parse_tax_data_decimalexception(tax_data_response):
# given
tax_data_response["shipping_price_gross_amount"] = "invalid value"
+ line_count = len(tax_data_response["lines"])
- # when
- tax_data = parse_tax_data(tax_data_response)
-
- # then
- assert tax_data is None
+ # when & then
+ with pytest.raises(ValidationError):
+ parse_tax_data(tax_data_response, line_count)
@pytest.mark.parametrize(
@@ -130,4 +95,5 @@ def test_parse_tax_data_decimalexception(tax_data_response):
],
)
def test_parse_tax_data_malformed(response_data):
- assert parse_tax_data(response_data) is None
+ with pytest.raises(ValidationError):
+ parse_tax_data(response_data, 1)
diff --git a/saleor/webhook/transport/synchronous/__init__.py b/saleor/webhook/transport/synchronous/__init__.py
index 91a0906f5c..4816f83b9a 100644
--- a/saleor/webhook/transport/synchronous/__init__.py
+++ b/saleor/webhook/transport/synchronous/__init__.py
@@ -1,11 +1,11 @@
from .transport import (
- trigger_all_webhooks_sync,
+ trigger_taxes_all_webhooks_sync,
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
)
__all__ = [
- "trigger_all_webhooks_sync",
+ "trigger_taxes_all_webhooks_sync",
"trigger_webhook_sync",
"trigger_webhook_sync_if_not_cached",
]
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index d9c418b566..cd34799531 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -8,11 +8,13 @@ from urllib.parse import urlparse
from django.conf import settings
from django.core.cache import cache
from django.db import transaction
+from pydantic import ValidationError
from ....celeryconf import app
from ....core import EventDeliveryStatus
from ....core.db.connection import allow_writer
from ....core.models import EventDelivery, EventPayload
+from ....core.taxes import TaxData
from ....core.tracing import webhooks_opentracing_trace
from ....core.utils import get_domain
from ....core.utils.events import call_event
@@ -50,6 +52,7 @@ from ..utils import (
generate_cache_key_for_webhook,
get_delivery_for_webhook,
handle_webhook_retry,
+ parse_tax_data,
save_unsuccessful_delivery_attempt,
send_webhook_using_http,
)
@@ -337,15 +340,14 @@ if breaker_board := initialize_breaker_board():
trigger_webhook_sync = breaker_board(trigger_webhook_sync)
-def trigger_all_webhooks_sync(
+def trigger_taxes_all_webhooks_sync(
event_type: str,
generate_payload: Callable,
- parse_response: Callable[[Any], R | None],
+ expected_lines_count: int,
subscribable_object=None,
requestor=None,
- allow_replica=False,
pregenerated_subscription_payloads: dict | None = None,
-) -> R | None:
+) -> TaxData | None:
"""Send all synchronous webhook request for given event type.
Requests are send sequentially.
@@ -366,7 +368,6 @@ def trigger_all_webhooks_sync(
request_context = initialize_request(
requestor,
event_type in WebhookEventSyncType.ALL,
- allow_replica,
event_type=event_type,
)
@@ -396,8 +397,17 @@ def trigger_all_webhooks_sync(
)
response_data = send_webhook_request_sync(delivery)
- if parsed_response := parse_response(response_data):
- return parsed_response
+ try:
+ parsed_response = parse_tax_data(response_data, expected_lines_count)
+ except ValidationError as e:
+ logger.warning(
+ "Webhook response for event %s is invalid: %s",
+ event_type,
+ str(e),
+ extra={"errors": e.errors()},
+ )
+ continue
+ return parsed_response
return None
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index ab22e50c21..5bd0db76da 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -47,6 +47,7 @@ from .. import observability
from ..const import APP_ID_PREFIX
from ..event_types import WebhookEventSyncType
from ..models import Webhook
+from ..response_schemas.taxes import CalculateTaxesSchema
from . import signature_for_payload
logger = logging.getLogger(__name__)
@@ -546,11 +547,25 @@ def save_unsuccessful_delivery_attempt(attempt: "EventDeliveryAttempt"):
def parse_tax_data(
response_data: Any,
-) -> TaxData | None:
- try:
- return _unsafe_parse_tax_data(response_data)
- except (TypeError, KeyError, decimal.DecimalException):
- return None
+ lines_count: int,
+) -> TaxData:
+ calculated_taxes_model = CalculateTaxesSchema.model_validate(
+ response_data,
+ context={"expected_line_count": lines_count},
+ )
+ return TaxData(
+ shipping_price_gross_amount=calculated_taxes_model.shipping_price_gross_amount,
+ shipping_price_net_amount=calculated_taxes_model.shipping_price_net_amount,
+ shipping_tax_rate=calculated_taxes_model.shipping_tax_rate,
+ lines=[
+ TaxLineData(
+ tax_rate=tax_line.tax_rate,
+ total_gross_amount=tax_line.total_gross_amount,
+ total_net_amount=tax_line.total_net_amount,
+ )
+ for tax_line in calculated_taxes_model.lines
+ ],
+ )
def parse_payment_action_response(
@@ -617,30 +632,6 @@ def _unsafe_parse_tax_line_data(
)
-def _unsafe_parse_tax_data(
- tax_data_response: Any,
-) -> TaxData:
- """Unsafe TaxData parser.
-
- Raises KeyError or DecimalException on invalid data.
- """
- shipping_price_gross_amount = decimal.Decimal(
- tax_data_response["shipping_price_gross_amount"]
- )
- shipping_price_net_amount = decimal.Decimal(
- tax_data_response["shipping_price_net_amount"]
- )
- shipping_tax_rate = decimal.Decimal(tax_data_response["shipping_tax_rate"])
- lines = [_unsafe_parse_tax_line_data(line) for line in tax_data_response["lines"]]
-
- return TaxData(
- shipping_price_gross_amount=shipping_price_gross_amount,
- shipping_price_net_amount=shipping_price_net_amount,
- shipping_tax_rate=shipping_tax_rate,
- lines=lines,
- )
-
-
def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
splitted_id = app_gateway_id.split(":", maxsplit=2)
if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):