Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Block `orderCreateFromCheckout` mutation when tax error occur (#17258)
Piotr Zabieglik11e3199c0d99
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 272599da92..32d418c0b0 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -127,6 +127,7 @@ def calculate_checkout_total_with_gift_cards(address: Optional["Address"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,pregenerated_subscription_payloads: dict | None = None,+ force_update: bool = False,) -> "TaxedMoney":if pregenerated_subscription_payloads is None:pregenerated_subscription_payloads = {}@@ -137,6 +138,7 @@ def calculate_checkout_total_with_gift_cards(address=address,database_connection_name=database_connection_name,pregenerated_subscription_payloads=pregenerated_subscription_payloads,+ force_update=force_update,) - checkout_info.checkout.get_total_gift_cards_balance(database_connection_name)return max(total, zero_taxed_money(total.currency))@@ -150,6 +152,7 @@ def checkout_total(address: Optional["Address"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,pregenerated_subscription_payloads: dict | None = None,+ force_update: bool = False,) -> "TaxedMoney":"""Return the total cost of the checkout.@@ -168,6 +171,7 @@ def checkout_total(address=address,database_connection_name=database_connection_name,pregenerated_subscription_payloads=pregenerated_subscription_payloads,+ force_update=force_update,)return quantize_price(checkout_info.checkout.total, currency)diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 16205c844b..35484a8505 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -5,6 +5,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Any, Optional, castfrom uuid import UUID+import graphenefrom django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationError@@ -21,7 +22,7 @@ from ..checkout import CheckoutAuthorizeStatus, calculationsfrom ..checkout.error_codes import CheckoutErrorCodefrom ..core.exceptions import GiftCardNotApplicable, InsufficientStockfrom ..core.postgres import FlatConcatSearchVector-from ..core.taxes import TaxError, zero_taxed_money+from ..core.taxes import TaxDataError, TaxError, zero_taxed_moneyfrom ..core.tracing import traced_atomic_transactionfrom ..core.transactions import transaction_with_commit_on_errorsfrom ..core.utils.url import validate_storefront_url@@ -579,6 +580,7 @@ def _prepare_order_data("subtotal": subtotal,"undiscounted_total": undiscounted_total,"shipping_tax_rate": shipping_tax_rate,+ "tax_error": checkout.tax_error,})@@ -1224,6 +1226,7 @@ def _create_order_from_checkout(metadata_list: list | None = None,private_metadata_list: list | None = None,is_automatic_completion: bool = False,+ force_update: bool = False,):from ..order.utils import add_gift_cards_to_order@@ -1241,6 +1244,7 @@ def _create_order_from_checkout(checkout_info=checkout_info,lines=checkout_lines_info,address=address,+ force_update=force_update,)# voucher@@ -1306,6 +1310,7 @@ def _create_order_from_checkout(redirect_url=checkout_info.checkout.redirect_url,should_refresh_prices=False,tax_exemption=checkout_info.checkout.tax_exemption,+ tax_error=checkout_info.checkout.tax_error,**_process_shipping_data_for_order(checkout_info,undiscounted_base_shipping_price,@@ -1440,6 +1445,7 @@ def create_order_from_checkout(# Fetching checkout info inside the transaction block with select_for_update# ensure that we are processing checkout on the current data.+ force_update = checkout.tax_error is not Nonecheckout_lines, _ = fetch_checkout_lines(checkout, voucher=voucher)checkout_info = fetch_checkout_info(checkout, checkout_lines, manager, voucher=voucher, voucher_code=code@@ -1456,7 +1462,23 @@ def create_order_from_checkout(metadata_list=metadata_list,private_metadata_list=private_metadata_list,is_automatic_completion=is_automatic_completion,+ force_update=force_update,)++ if checkout_info.checkout.tax_error is not None:+ checkout_id = graphene.Node.to_global_id(+ "Checkout", checkout_info.checkout.pk+ )+ logger.warning(+ "Tax app error for checkout %s",+ checkout_id,+ extra={+ "tax_error": checkout_info.checkout.tax_error,+ "checkout_id": checkout_id,+ },+ )+ raise TaxDataError("Configured Tax App returned invalid response.")+if delete_checkout:delete_checkouts([checkout_info.checkout.pk])checkout_info.checkout.pk = None@@ -1518,7 +1540,7 @@ def complete_checkout()if checkout_info.checkout.tax_error is not None:raise ValidationError(- "Configured Tax App didn't responded.",+ "Configured Tax App returned invalid response.",code=CheckoutErrorCode.TAX_ERROR.value,)diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.pyindex 86ae50ad05..6961832c43 100644--- a/saleor/checkout/tests/test_order_from_checkout.py+++ b/saleor/checkout/tests/test_order_from_checkout.py@@ -1,5 +1,6 @@from decimal import Decimalfrom unittest import mock+from unittest.mock import patchimport pytestfrom django.test import override_settings@@ -9,10 +10,17 @@ from ...channel import MarkAsPaidStrategyfrom ...checkout.models import Checkout, CheckoutLinefrom ...core.exceptions import InsufficientStockfrom ...core.prices import quantize_price-from ...core.taxes import zero_money, zero_taxed_money+from ...core.taxes import (+ TaxDataError,+ TaxDataErrorMessage,+ zero_money,+ zero_taxed_money,+)from ...giftcard import GiftCardEventsfrom ...giftcard.models import GiftCard, GiftCardEvent+from ...graphql.core.utils import to_global_id_or_nonefrom ...order import OrderStatus+from ...order.models import Orderfrom ...plugins.manager import get_plugins_managerfrom ...product.models import ProductTranslation, ProductVariantTranslationfrom ...tests import race_condition@@ -1034,3 +1042,34 @@ def test_create_order_with_voucher_0_total(assert (discount.amount_value == (order.undiscounted_total - order.total).gross.amount)+++@patch("saleor.checkout.calculations.validate_tax_data")+def test_create_order_from_checkout_update_tax_error(+ mock_validate_tax_data,+ checkout_with_items_and_shipping,+ customer_user,+ app,+ tax_configuration_tax_app,+ caplog,+):+ # given+ mock_validate_tax_data.side_effect = TaxDataError(TaxDataErrorMessage.EMPTY)++ checkout = checkout_with_items_and_shipping+ lines, _ = fetch_checkout_lines(checkout)++ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout, lines, manager, [])++ # when & then+ with pytest.raises(TaxDataError):+ create_order_from_checkout(+ checkout_info=checkout_info,+ manager=manager,+ 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/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.pyindex 81a746beca..1720e35434 100644--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py@@ -5,6 +5,7 @@ from ....checkout.checkout_cleaner import validate_checkoutfrom ....checkout.complete_checkout import create_order_from_checkoutfrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....core.exceptions import GiftCardNotApplicable, InsufficientStock+from ....core.taxes import TaxDataErrorfrom ....discount.models import NotApplicablefrom ....permission.enums import CheckoutPermissionsfrom ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType@@ -206,5 +207,10 @@ class OrderCreateFromCheckout(BaseMutation):raise error from eexcept GiftCardNotApplicable as e:raise ValidationError({"gift_cards": e}) from e+ except TaxDataError as e:+ raise ValidationError(+ "Configured Tax App returned invalid response.",+ code=OrderCreateFromCheckoutErrorCode.TAX_ERROR.value,+ ) from ereturn OrderCreateFromCheckout(order=order)diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex fb56a94de5..b3a2c6b6ca 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -428,7 +428,9 @@ def test_checkout_complete_fails_with_invalid_tax_app(data = content["data"]["checkoutComplete"]assert len(data["errors"]) == 1assert data["errors"][0]["code"] == CheckoutErrorCode.TAX_ERROR.name- assert data["errors"][0]["message"] == "Configured Tax App didn't responded."+ assert (+ data["errors"][0]["message"] == "Configured Tax App returned invalid response."+ )assert not EventDelivery.objects.exists()checkout.refresh_from_db()@@ -540,7 +542,9 @@ def test_checkout_complete_calls_failing_plugin(data = content["data"]["checkoutComplete"]assert len(data["errors"]) == 1assert data["errors"][0]["code"] == CheckoutErrorCode.TAX_ERROR.name- assert data["errors"][0]["message"] == "Configured Tax App didn't responded."+ assert (+ data["errors"][0]["message"] == "Configured Tax App returned invalid response."+ )checkout.refresh_from_db()assert checkout.price_expiration == timezone.now() + settings.CHECKOUT_PRICES_TTLdiff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.pyindex dc42dd9cd8..6908d22d6a 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@@ -12,7 +12,13 @@ from .....checkout import calculationsfrom .....checkout.error_codes import OrderCreateFromCheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkout, CheckoutLine-from .....core.taxes import TaxError, zero_money, zero_taxed_money+from .....core.taxes import (+ TaxDataError,+ TaxDataErrorMessage,+ TaxError,+ zero_money,+ zero_taxed_money,+)from .....discount import DiscountType, DiscountValueType, RewardValueTypefrom .....discount.models import CheckoutLineDiscountfrom .....giftcard import GiftCardEvents@@ -2501,3 +2507,32 @@ def test_order_from_draft_create_0_total_value_from_giftcard(assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")+++@patch("saleor.checkout.calculations.validate_tax_data")+def test_order_from_checkout_tax_error(+ mock_validate_tax_data,+ 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)}++ # when+ response = app_api_client.post_graphql(+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderCreateFromCheckout"]+ assert data["errors"][0]["code"] == OrderCreateFromCheckoutErrorCode.TAX_ERROR.name+ assert data["errors"][0]["field"] is None+ assert not Order.objects.exists()+ assert "Tax app error for checkout" in caplog.textdiff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex c7edc4fbaa..85b80fdd70 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -105,7 +105,7 @@ class DraftOrderComplete(BaseMutation):)if order.tax_error is not None:raise ValidationError(- "Configured Tax App didn't responded.",+ "Configured Tax App returned invalid response.",code=OrderErrorCode.TAX_ERROR.value,)cls.validate_order(order)diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 42ba15fbc2..4f771bcc37 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -1103,7 +1103,9 @@ def test_draft_order_complete_fails_with_invalid_tax_app(data = content["data"]["draftOrderComplete"]assert len(data["errors"]) == 1assert data["errors"][0]["code"] == OrderErrorCode.TAX_ERROR.name- assert data["errors"][0]["message"] == "Configured Tax App didn't responded."+ assert (+ data["errors"][0]["message"] == "Configured Tax App returned invalid response."+ )assert not EventDelivery.objects.exists()order.refresh_from_db()@@ -1251,7 +1253,9 @@ def test_draft_order_complete_calls_failing_plugin(data = content["data"]["draftOrderComplete"]assert len(data["errors"]) == 1assert data["errors"][0]["code"] == OrderErrorCode.TAX_ERROR.name- assert data["errors"][0]["message"] == "Configured Tax App didn't responded."+ assert (+ data["errors"][0]["message"] == "Configured Tax App returned invalid response."+ )order.refresh_from_db()assert not order.should_refresh_pricesdiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex ebd4966981..8a978e47a9 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -5,6 +5,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Optional, TypedDictfrom uuid import UUID+import graphenefrom django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.db import transaction@@ -287,6 +288,15 @@ def order_created(automatic: bool = False,):order = order_info.order++ if order.tax_error is not None and not order.is_draft():+ order_id = graphene.Node.to_global_id("Order", order.pk)+ logger.error(+ "Created non-draft order with tax_error for order: %s",+ order_id,+ extra={"tax_error": order.tax_error, "order_id": order_id},+ )+events.order_created_event(order=order, user=user, app=app, from_draft=from_draft, automatic=automatic)diff --git a/saleor/order/tests/test_actions.py b/saleor/order/tests/test_actions.pyindex a967baf208..fb8e79f105 100644--- a/saleor/order/tests/test_actions.py+++ b/saleor/order/tests/test_actions.py@@ -2,6 +2,7 @@ from unittest.mock import patchimport pytest+from ...graphql.core.utils import to_global_id_or_nonefrom ...webhook.utils import get_webhooks_for_multiple_eventsfrom .. import OrderStatusfrom ..actions import WEBHOOK_EVENTS_FOR_ORDER_CREATED, order_confirmed, order_created@@ -64,3 +65,24 @@ def test_order_created_order_confirmed_with_turned_flag_off(# thenmock_order_confirmed.assert_not_called()+++def test_order_created_with_tax_error(order, customer_user, plugins_manager, caplog):+ # given+ order.tax_error = "Empty tax data."+ order.save(update_fields=["tax_error"])++ order_info = OrderInfo(+ order=order,+ customer_email=order.get_customer_email(),+ channel=order.channel,+ payment=order.get_last_payment(),+ lines_data=[],+ )++ # when+ order_created(order_info, user=customer_user, app=None, manager=plugins_manager)++ # then+ assert "Created non-draft order with tax_error for order" in caplog.text+ assert caplog.records[0].order_id == to_global_id_or_none(order)diff --git a/saleor/tests/e2e/checkout/taxes/test_checkout_complete_return_tax_error.py b/saleor/tests/e2e/checkout/taxes/test_checkout_complete_return_tax_error.pyindex 72e26f84be..727bb67cbc 100644--- a/saleor/tests/e2e/checkout/taxes/test_checkout_complete_return_tax_error.py+++ b/saleor/tests/e2e/checkout/taxes/test_checkout_complete_return_tax_error.py@@ -133,4 +133,7 @@ def test_checkout_calculate_return_tax_error_when_app_not_respond_CORE_2013()assert order_data["errors"] is not Noneassert order_data["errors"][0]["code"] == "TAX_ERROR"- assert order_data["errors"][0]["message"] == "Configured Tax App didn't responded."+ assert (+ order_data["errors"][0]["message"]+ == "Configured Tax App returned invalid response."+ )diff --git a/saleor/tests/e2e/checkout/taxes/test_order_create_from_checkout_return_tax_error.py b/saleor/tests/e2e/checkout/taxes/test_order_create_from_checkout_return_tax_error.pyindex 6223577391..3d1e5822fb 100644--- a/saleor/tests/e2e/checkout/taxes/test_order_create_from_checkout_return_tax_error.py+++ b/saleor/tests/e2e/checkout/taxes/test_order_create_from_checkout_return_tax_error.py@@ -1,8 +1,7 @@import pytestfrom ...apps.utils import add_app--# from ...orders.utils import raw_order_create_from_checkout+from ...orders.utils import raw_order_create_from_checkoutfrom ...product.utils.preparing_product import prepare_productfrom ...shop.utils import prepare_default_shopfrom ...taxes.utils import get_tax_configurations, update_tax_configuration@@ -124,13 +123,14 @@ def test_order_create_from_checkout_return_tax_error_when_app_not_respond_CORE_2calculated_total_net = product_variant_price + shipping_priceassert checkout_data["totalPrice"]["net"]["amount"] == calculated_total_net- # BUG: https://linear.app/saleor/issue/SHOPX-1712/- # uncomment this step when the bug is fixed- # # Step 4 - Place order via orderCreateFromCheckout- # order_data = raw_order_create_from_checkout(- # e2e_app_api_client,- # checkout_id,- # )- # assert order_data["errors"] is not None- # assert order_data["errors"][0]["code"] == "TAX_ERROR"- # assert order_data["errors"][0]["message"] == "Configured Tax App didn't responded."+ # Step 4 - Place order via orderCreateFromCheckout+ order_data = raw_order_create_from_checkout(+ e2e_app_api_client,+ checkout_id,+ )+ assert order_data["errors"] is not None+ assert order_data["errors"][0]["code"] == "TAX_ERROR"+ assert (+ order_data["errors"][0]["message"]+ == "Configured Tax App returned invalid response."+ )diff --git a/saleor/tests/e2e/orders/taxes/test_draft_order_complete_return_tax_error.py b/saleor/tests/e2e/orders/taxes/test_draft_order_complete_return_tax_error.pyindex c4fb2da890..b842f72d66 100644--- a/saleor/tests/e2e/orders/taxes/test_draft_order_complete_return_tax_error.py+++ b/saleor/tests/e2e/orders/taxes/test_draft_order_complete_return_tax_error.py@@ -129,4 +129,6 @@ def test_draft_order_complte_return_tax_error_when_app_not_respond_CORE_2015()assert order["errors"] is not Noneassert order["errors"][0]["code"] == "TAX_ERROR"- assert order["errors"][0]["message"] == "Configured Tax App didn't responded."+ assert (+ order["errors"][0]["message"] == "Configured Tax App returned invalid response."+ )