Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix bug with voucher usage when preprocess_order_creation breaks (#8799)
Tomasz Szymański1db17770d199
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 5d1226dbb4..e5232ef27e 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -19,9 +19,8 @@ from ..discount import DiscountInfo, DiscountValueType, OrderDiscountTypefrom ..discount.models import NotApplicablefrom ..discount.utils import (add_voucher_usage_by_customer,- decrease_voucher_usage,increase_voucher_usage,- remove_voucher_usage_by_customer,+ release_voucher_usage,)from ..giftcard.models import GiftCardfrom ..giftcard.utils import fulfill_non_shippable_gift_cards@@ -52,10 +51,11 @@ if TYPE_CHECKING:from .fetch import CheckoutInfo, CheckoutLineInfo-def _get_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:+def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:"""Fetch, process and return voucher/discount data from checkout.Careful! It should be called inside a transaction.+ If voucher has a usage limit, it will be increased!:raises NotApplicable: When the voucher is not applicable in the current checkout."""@@ -341,8 +341,7 @@ def _prepare_order_data(# validate checkout gift cards_validate_gift_cards(checkout)- # Get voucher data (last) as they require a transaction- order_data.update(_get_voucher_data_for_order(checkout_info))+ order_data.update(_process_voucher_data_for_order(checkout_info))order_data["total_price_left"] = (manager.calculate_checkout_subtotal(checkout_info, lines, address, discounts)@@ -350,7 +349,12 @@ def _prepare_order_data(- checkout.discount).gross- manager.preprocess_order_creation(checkout_info, discounts, lines)+ try:+ manager.preprocess_order_creation(checkout_info, discounts, lines)+ except TaxError:+ release_voucher_usage(order_data)+ raise+return order_data@@ -524,14 +528,6 @@ def _prepare_checkout(checkout.save(update_fields=to_update)-def release_voucher_usage(order_data: dict):- voucher = order_data.get("voucher")- if voucher and voucher.usage_limit:- decrease_voucher_usage(voucher)- if "user_email" in order_data:- remove_voucher_usage_by_customer(voucher, order_data["user_email"])--def _get_order_data(manager: "PluginsManager",checkout_info: "CheckoutInfo",diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex c8c9f2c1ab..8049cd4ea2 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -52,6 +52,14 @@ def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str) ->voucher_customer.delete()+def release_voucher_usage(order_data: dict):+ voucher = order_data.get("voucher")+ if voucher and voucher.usage_limit:+ decrease_voucher_usage(voucher)+ if "user_email" in order_data:+ remove_voucher_usage_by_customer(voucher, order_data["user_email"])++def get_product_discount_on_sale(product: "Product",product_collections: Set[int],diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex b272ddb9eb..3deb594310 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -14,7 +14,7 @@ from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.models import Checkoutfrom ....core.exceptions import InsufficientStock, InsufficientStockData-from ....core.taxes import zero_money, zero_taxed_money+from ....core.taxes import TaxError, zero_money, zero_taxed_moneyfrom ....giftcard import GiftCardEventsfrom ....giftcard.models import GiftCard, GiftCardEventfrom ....order import OrderOrigin, OrderStatus@@ -676,6 +676,51 @@ def test_checkout_with_voucher_complete().exists(), "Checkout should have been deleted"[email protected](PluginsManager, "preprocess_order_creation")+def test_checkout_with_voucher_not_increase_uses_on_preprocess_order_creation_failure(+ mocked_preprocess_order_creation,+ user_api_client,+ checkout_with_voucher_percentage,+ voucher_percentage,+ payment_dummy,+ address,+ shipping_method,+):+ mocked_preprocess_order_creation.side_effect = TaxError("tax error!")+ voucher_percentage.used = 0+ voucher_percentage.usage_limit = 1+ voucher_percentage.save(update_fields=["used", "usage_limit"])++ checkout = checkout_with_voucher_percentage+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ variables = {"token": checkout.token, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert data["errors"][0]["code"] == CheckoutErrorCode.TAX_ERROR.name++ voucher_percentage.refresh_from_db()+ assert voucher_percentage.used == 0++ assert Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout shouldn't have been deleted"++@pytest.mark.integrationdef test_checkout_complete_without_inventory_tracking(user_api_client,