Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix crashing checkout complete (#12895)
Iga Karbowiak27597d135500
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex b61222f62f..ce14b9d8e7 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -230,7 +230,6 @@ def _fetch_checkout_prices_if_expired(Prices can be updated only if force_update == True, or if time elapsed from thelast price update is greater than settings.CHECKOUT_PRICES_TTL."""-checkout = checkout_info.checkoutif not force_update and checkout.price_expiration > timezone.now():diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 2e49f087ab..b0b9218d80 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -80,7 +80,12 @@ from .checkout_cleaner import (clean_checkout_payment,clean_checkout_shipping,)-from .fetch import CheckoutInfo, CheckoutLineInfo+from .fetch import (+ CheckoutInfo,+ CheckoutLineInfo,+ fetch_checkout_info,+ fetch_checkout_lines,+)from .models import Checkoutfrom .utils import (get_checkout_metadata,@@ -1203,7 +1208,6 @@ def _create_order_from_checkout(def create_order_from_checkout(checkout_info: CheckoutInfo,- checkout_lines: Iterable["CheckoutLineInfo"],manager: "PluginsManager",user: Optional["User"],app: Optional["App"],@@ -1230,11 +1234,26 @@ def create_order_from_checkout(:raises: InsufficientStock, GiftCardNotApplicable"""- if checkout_info.voucher:+ voucher = None+ if voucher := checkout_info.voucher:with transaction.atomic():_increase_voucher_usage(checkout_info=checkout_info)with transaction.atomic():+ checkout_pk = checkout_info.checkout.pk+ checkout = Checkout.objects.select_for_update().filter(pk=checkout_pk).first()+ if not checkout:+ order = Order.objects.get_by_checkout_token(checkout_pk)+ return order++ # Fetching checkout info inside the transaction block with select_for_update+ # enure that we are processing checkout on the current data.+ checkout_lines, _ = fetch_checkout_lines(checkout, voucher=voucher)+ checkout_info = fetch_checkout_info(+ checkout, checkout_lines, manager, voucher=voucher+ )+ assign_checkout_user(user, checkout_info)+try:order = _create_order_from_checkout(checkout_info=checkout_info,@@ -1261,6 +1280,19 @@ def create_order_from_checkout(raise+def assign_checkout_user(+ user: Optional["User"],+ checkout_info: "CheckoutInfo",+):+ # Assign checkout user to an existing user if checkout email matches a valid+ # customer account+ if user is None and not checkout_info.user and checkout_info.checkout.email:+ existing_user = retrieve_user_by_email(checkout_info.checkout.email)+ checkout_info.user = (+ existing_user if existing_user and existing_user.is_active else None+ )++def complete_checkout(manager: "PluginsManager",checkout_info: "CheckoutInfo",@@ -1275,14 +1307,6 @@ def complete_checkout(metadata_list: Optional[List] = None,private_metadata_list: Optional[List] = None,) -> Tuple[Optional[Order], bool, dict]:- # Assign checkout user to an existing user if checkout email matches a valid- # customer account- if user is None and checkout_info.checkout.email:- existing_user = retrieve_user_by_email(checkout_info.checkout.email)- checkout_info.user = (- existing_user if existing_user and existing_user.is_active else None- )-transactions = checkout_info.checkout.payment_transactions.all()fetch_checkout_data(checkout_info, manager, lines)@@ -1311,8 +1335,7 @@ def complete_checkout(return complete_checkout_with_payment(manager=manager,- checkout_info=checkout_info,- lines=lines,+ checkout_pk=checkout_info.checkout.pk,payment_data=payment_data,store_source=store_source,user=user,@@ -1346,7 +1369,6 @@ def complete_checkout_with_transaction(return create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=user,app=app,@@ -1359,8 +1381,7 @@ def complete_checkout_with_transaction(def complete_checkout_with_payment(manager: "PluginsManager",- checkout_info: "CheckoutInfo",- lines: Iterable["CheckoutLineInfo"],+ checkout_pk: UUID,payment_data,store_source,user,@@ -1378,15 +1399,17 @@ def complete_checkout_with_payment(:raises ValidationError"""with transaction_with_commit_on_errors():- checkout = (- Checkout.objects.select_for_update()- .filter(pk=checkout_info.checkout.pk)- .first()- )+ checkout = Checkout.objects.select_for_update().filter(pk=checkout_pk).first()if not checkout:- order = Order.objects.get_by_checkout_token(checkout_info.checkout.token)+ order = Order.objects.get_by_checkout_token(checkout_pk)return order, False, {}+ # Fetching checkout info inside the transaction block with select_for_update+ # enure that we are processing checkout on the current data.+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ assign_checkout_user(user, checkout_info)+payment, customer_id, order_data = complete_checkout_pre_payment_part(manager=manager,checkout_info=checkout_info,@@ -1396,7 +1419,8 @@ def complete_checkout_with_payment(tracking_code=tracking_code,redirect_url=redirect_url,)- reservations = _reserve_stocks_without_availability_check(checkout_info, lines)++ _reserve_stocks_without_availability_check(checkout_info, lines)# Process payments out of transaction to unlock stock rows for another user,# who potentially can order the same product variants.@@ -1434,62 +1458,29 @@ def complete_checkout_with_payment(order = Order.objects.get_by_checkout_token(checkout_info.checkout.token)return order, False, {}- # Run pre-payment checks to make sure, that nothing has changed to the- # checkout, during processing payment.+ # We need to refetch the checkout info to ensure that we process checkout+ # for correct data.+ lines, _ = fetch_checkout_lines(checkout, skip_recalculation=True)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+checkout_info.checkout.voucher_code = None- _, _, post_payment_order_data = complete_checkout_pre_payment_part(+ order, action_required, action_data = complete_checkout_post_payment_part(manager=manager,checkout_info=checkout_info,lines=lines,+ payment=payment,+ txn=txn,+ order_data=order_data,user=user,+ app=app,site_settings=site_settings,- tracking_code=tracking_code,- redirect_url=redirect_url,+ metadata_list=metadata_list,+ private_metadata_list=private_metadata_list,)- if _compare_order_data(order_data, post_payment_order_data):- order, action_required, action_data = complete_checkout_post_payment_part(- manager=manager,- checkout_info=checkout_info,- lines=lines,- payment=payment,- txn=txn,- order_data=order_data,- user=user,- app=app,- site_settings=site_settings,- metadata_list=metadata_list,- private_metadata_list=private_metadata_list,- )- else:- release_voucher_usage(- order_data.get("voucher"), order_data.get("user_email")- )- gateway.payment_refund_or_void(- payment,- manager,- channel_slug=checkout_info.channel.slug,- )- if not is_reservation_enabled(site_settings):- Reservation.objects.filter(id__in=[r.id for r in reservations]).delete()- raise ValidationError("Checkout has changed during payment processing")return order, action_required, action_data-def _compare_order_data(order_data_1, order_data_2):- order_total_check = (- order_data_1["total"].gross.amount == order_data_2["total"].gross.amount- )- order_lines_quantity_check = len(order_data_1["lines"]) == len(- order_data_2["lines"]- )- variants_id_1 = [line.variant.id for line in order_data_1["lines"]]- order_lines_check = all(- [line.variant.id in variants_id_1 for line in order_data_2["lines"]]- )- return order_total_check and order_lines_quantity_check and order_lines_check--def _reserve_stocks_without_availability_check(checkout_info: CheckoutInfo,lines: Iterable[CheckoutLineInfo],diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 5f5994eca5..f6d023eba0 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -225,8 +225,10 @@ def get_delivery_method_info(def fetch_checkout_lines(checkout: "Checkout",- prefetch_variant_attributes=False,- skip_lines_with_unavailable_variants=True,+ prefetch_variant_attributes: bool = False,+ skip_lines_with_unavailable_variants: bool = True,+ skip_recalculation: bool = False,+ voucher: Optional["Voucher"] = None,) -> Tuple[Iterable[CheckoutLineInfo], Iterable[int]]:"""Fetch checkout lines as CheckoutLineInfo objects."""from .utils import get_voucher_for_checkout@@ -266,7 +268,7 @@ def fetch_checkout_lines(variant, checkout.channel_id)- if not _is_variant_valid(+ if not skip_recalculation and not _is_variant_valid(checkout, product, variant_channel_listing, product_channel_listing_mapping):unavailable_variant_pks.append(variant.pk)@@ -300,10 +302,11 @@ def fetch_checkout_lines())- if checkout.voucher_code and lines_info:- voucher = get_voucher_for_checkout(- checkout, channel_slug=channel.slug, with_prefetch=True- )+ if not skip_recalculation and checkout.voucher_code and lines_info:+ if not voucher:+ voucher = get_voucher_for_checkout(+ checkout, channel_slug=channel.slug, with_prefetch=True+ )if not voucher:# in case when voucher is expired, it will be null so no need to apply any# discount from voucher@@ -421,6 +424,7 @@ def fetch_checkout_info(Iterable["ShippingMethodChannelListing"]] = None,fetch_delivery_methods=True,+ voucher: Optional["Voucher"] = None,) -> CheckoutInfo:"""Fetch checkout as CheckoutInfo object."""from .utils import get_voucher_for_checkout@@ -430,7 +434,8 @@ def fetch_checkout_info(shipping_address = checkout.shipping_addressif shipping_channel_listings is None:shipping_channel_listings = channel.shipping_method_listings.all()- voucher = get_voucher_for_checkout(checkout, channel_slug=channel.slug)+ if not voucher:+ voucher = get_voucher_for_checkout(checkout, channel_slug=channel.slug)delivery_method_info = get_delivery_method_info(None, shipping_address)checkout_info = CheckoutInfo(diff --git a/saleor/checkout/tests/test_associate_checkout_with_account.py b/saleor/checkout/tests/test_associate_checkout_with_account.pyindex 2b3661412d..10069a85c1 100644--- a/saleor/checkout/tests/test_associate_checkout_with_account.py+++ b/saleor/checkout/tests/test_associate_checkout_with_account.py@@ -20,12 +20,12 @@ def test_associate_guest_checkout_with_account_if_exists():# set the checkout emailcheckout.email = "[email protected]"+ checkout.billing_address = addresscheckout.save()user = Nonemanager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.billing_address = address+ checkout_info = fetch_checkout_info(checkout, lines, manager)checkout_info.channel.order_mark_as_paid_strategy == paid_strategy# call the complete_checkout function with the checkout object@@ -59,12 +59,12 @@ def test_associate_guest_checkout_with_account_if_exists_with_guest_user():# set the checkout emailcheckout.email = "[email protected]"+ checkout.billing_address = addresscheckout.save()user = Nonemanager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.billing_address = address+ checkout_info = fetch_checkout_info(checkout, lines, manager)checkout_info.channel.order_mark_as_paid_strategy == paid_strategy# call the complete_checkout function with the checkout object@@ -95,6 +95,7 @@ def test_associate_guest_checkout_with_account_if_exists_with_inactive_user():# set the checkout emailcheckout.email = "[email protected]"+ checkout.billing_address = addresscheckout.save()# deactivate the customer usercustomer_user.is_active = False@@ -102,8 +103,7 @@ def test_associate_guest_checkout_with_account_if_exists_with_inactive_user(user = Nonemanager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.billing_address = address+ checkout_info = fetch_checkout_info(checkout, lines, manager)checkout_info.channel.order_mark_as_paid_strategy == paid_strategy# call the complete_checkout function with the checkout objectdiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 10a3acdd9e..beb2a8455e 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom decimal import Decimalfrom unittest import mock@@ -5,6 +6,7 @@ import before_afterimport pytestfrom django.core.exceptions import ValidationErrorfrom django.test import override_settings+from django.utils import timezonefrom prices import TaxedMoneyfrom ...account import CustomerEvents@@ -21,6 +23,7 @@ from ...order import OrderAuthorizeStatus, OrderChargeStatus, OrderEventsfrom ...order.models import OrderEventfrom ...order.notifications import get_default_order_payloadfrom ...payment import TransactionKind+from ...payment.interface import GatewayResponsefrom ...payment.models import Paymentfrom ...plugins.manager import get_plugins_managerfrom ...product.models import ProductTranslation, ProductVariantTranslation@@ -1249,8 +1252,8 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(checkout_info = fetch_checkout_info(checkout, lines, manager)order, action_required, action_data = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1369,8 +1372,8 @@ def test_complete_checkout_action_required_voucher_once_per_customer(# whenorder, action_required, _ = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1423,8 +1426,8 @@ def test_complete_checkout_order_not_created_when_the_refund_is_ongoing(# whenorder, _, _ = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1478,8 +1481,8 @@ def test_complete_checkout_when_checkout_doesnt_exists(# whenorder_from_checkout, _, _ = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1494,7 +1497,7 @@ def test_complete_checkout_when_checkout_doesnt_exists(@mock.patch("saleor.checkout.complete_checkout._create_order")@mock.patch("saleor.checkout.complete_checkout._process_payment")-def test_complete_checkout_checkout_was_deleted_before_compliting(+def test_complete_checkout_checkout_was_deleted_before_completing(mocked_process_payment,mocked_create_order,customer_user,@@ -1535,8 +1538,8 @@ def test_complete_checkout_checkout_was_deleted_before_compliting():order_from_checkout, action_required, _ = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1794,8 +1797,8 @@ def test_complete_checkout_invalid_shipping_method(with pytest.raises(ValidationError):order, action_required, _ = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1940,8 +1943,8 @@ def test_checkout_complete_pick_payment_flow(# whenorder, action_required, _ = complete_checkout(checkout_info=checkout_info,- manager=manager,lines=lines,+ manager=manager,payment_data={},store_source=False,user=customer_user,@@ -1951,8 +1954,7 @@ def test_checkout_complete_pick_payment_flow(# thenmocked_flow.assert_called_once_with(manager=manager,- checkout_info=checkout_info,- lines=lines,+ checkout_pk=checkout.pk,payment_data={},store_source=False,user=customer_user,@@ -1963,3 +1965,85 @@ def test_checkout_complete_pick_payment_flow(metadata_list=None,private_metadata_list=None,)++[email protected]("saleor.checkout.calculations.get_tax_calculation_strategy_for_checkout")[email protected]("saleor.checkout.complete_checkout._create_order")[email protected]("saleor.checkout.complete_checkout._process_payment")+def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_part(+ mocked_process_payment,+ mocked_create_order,+ mocked_get_tax_calculation_strategy_for_checkout,+ customer_user,+ checkout_with_item,+ shipping_method,+ app,+ address,+ payment_dummy,+):+ # given+ checkout = checkout_with_item+ mocked_process_payment.return_value = GatewayResponse(+ is_success=True,+ action_required=False,+ action_required_data={},+ kind=TransactionKind.CAPTURE,+ amount=Decimal(3.0),+ currency="usd",+ transaction_id="1234",+ error=None,+ )+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ calculation_call_count = mocked_get_tax_calculation_strategy_for_checkout.call_count++ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = ""+ checkout.redirect_url = "https://www.example.com"+ checkout.price_expiration = timezone.now() + timedelta(hours=2)+ checkout.save()++ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ def update_price_expiration(*args, **kwargs):+ # Invalidate checkout prices just after processing payment+ checkout.price_expiration = timezone.now() - timedelta(hours=2)+ checkout.save(update_fields=["price_expiration"])++ # when+ with before_after.after(+ "saleor.checkout.complete_checkout._process_payment", update_price_expiration+ ):+ order, action_required, _ = complete_checkout(+ checkout_info=checkout_info,+ lines=lines,+ manager=manager,+ payment_data={},+ store_source=False,+ user=customer_user,+ app=app,+ )++ # then+ assert order++ assert (+ mocked_get_tax_calculation_strategy_for_checkout.call_count+ == calculation_call_count+ )diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.pyindex 384b756450..8f6e233d14 100644--- a/saleor/checkout/tests/test_order_from_checkout.py+++ b/saleor/checkout/tests/test_order_from_checkout.py@@ -1,10 +1,12 @@from decimal import Decimalfrom unittest import mock+import before_afterimport pytestfrom django.test import override_settingsfrom prices import TaxedMoney+from ...checkout.models import Checkout, CheckoutLinefrom ...core.exceptions import InsufficientStockfrom ...core.taxes import zero_money, zero_taxed_moneyfrom ...giftcard import GiftCardEvents@@ -38,7 +40,6 @@ def test_create_order_insufficient_stock(with pytest.raises(InsufficientStock):create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -83,7 +84,6 @@ def test_create_order_with_gift_card(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -131,7 +131,6 @@ def test_create_order_with_gift_card_partial_use(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -193,7 +192,6 @@ def test_create_order_with_many_gift_cards(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -267,7 +265,6 @@ def test_create_order_gift_card_bought(# whenorder = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -343,7 +340,6 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -399,7 +395,6 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -427,7 +422,6 @@ def test_note_in_created_order(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -472,7 +466,6 @@ def test_create_order_use_translations(order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -507,7 +500,6 @@ def test_create_order_from_checkout_updates_total_authorized_amount(# whenorder = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -545,7 +537,6 @@ def test_create_order_from_checkout_updates_total_charged_amount(# whenorder = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -575,7 +566,6 @@ def test_create_order_from_checkout_update_display_gross_prices(# whenorder = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=None,app=app,@@ -615,7 +605,6 @@ def test_create_order_from_checkout_store_shipping_prices(# whenorder = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -626,11 +615,11 @@ def test_create_order_from_checkout_store_shipping_prices(assert order.base_shipping_price == expected_base_shipping_priceassert order.shipping_price == expected_shipping_pricemanager.calculate_checkout_shipping.assert_called_once_with(- checkout_info, lines, checkout.shipping_address+ mock.ANY, lines, checkout.shipping_address)assert order.shipping_tax_rate == expected_shipping_tax_ratemanager.get_checkout_shipping_tax_rate.assert_called_once_with(- checkout_info, lines, checkout.shipping_address, expected_shipping_price+ mock.ANY, lines, checkout.shipping_address, expected_shipping_price)@@ -662,7 +651,6 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(# whenorder = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=lines,manager=manager,user=None,app=app,@@ -673,9 +661,81 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(assert order.base_shipping_price == expected_base_shipping_priceassert order.shipping_price == expected_shipping_pricemanager.calculate_checkout_shipping.assert_called_once_with(- checkout_info, lines, checkout.shipping_address+ mock.ANY, lines, checkout.shipping_address)assert order.shipping_tax_rate == expected_shipping_tax_ratemanager.get_checkout_shipping_tax_rate.assert_called_once_with(- checkout_info, lines, checkout.shipping_address, expected_shipping_price+ mock.ANY, lines, checkout.shipping_address, expected_shipping_price)+++def test_note_in_created_order_checkout_line_deleted_in_the_meantime(+ checkout_with_item, address, shipping_method, app, voucher_percentage+):+ # given+ checkout_with_item.voucher_code = voucher_percentage.code+ checkout_with_item.shipping_address = address+ checkout_with_item.billing_address = address+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.tracking_code = "tracking_code"+ checkout_with_item.redirect_url = "https://www.example.com"+ checkout_with_item.save()+ manager = get_plugins_manager()++ checkout_lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, checkout_lines, manager)++ def delete_checkout_line(*args, **kwargs):+ CheckoutLine.objects.get(id=checkout_with_item.lines.first().id).delete()++ # when+ with before_after.after(+ "saleor.checkout.complete_checkout._increase_voucher_usage",+ delete_checkout_line,+ ):+ order = create_order_from_checkout(+ checkout_info=checkout_info,+ manager=manager,+ user=None,+ app=app,+ tracking_code="tracking_code",+ )++ # then+ assert order+++def test_note_in_created_order_checkout_deleted_in_the_meantime(+ checkout_with_item, address, shipping_method, app, voucher_percentage+):+ # given+ checkout_with_item.voucher_code = voucher_percentage.code+ checkout_with_item.shipping_address = address+ checkout_with_item.billing_address = address+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.tracking_code = "tracking_code"+ checkout_with_item.redirect_url = "https://www.example.com"+ checkout_with_item.save()+ manager = get_plugins_manager()++ checkout_lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, checkout_lines, manager)++ def delete_checkout(*args, **kwargs):+ Checkout.objects.get(pk=checkout_with_item.pk).delete()++ # when+ with before_after.after(+ "saleor.checkout.complete_checkout._increase_voucher_usage",+ delete_checkout,+ ):+ order = create_order_from_checkout(+ checkout_info=checkout_info,+ manager=manager,+ user=None,+ app=app,+ tracking_code="tracking_code",+ )++ # then+ assert order is Nonediff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.pyindex ce4a5c9bd3..ccfe6e08ab 100644--- a/saleor/graphql/checkout/mutations/checkout_complete.py+++ b/saleor/graphql/checkout/mutations/checkout_complete.py@@ -265,9 +265,9 @@ class CheckoutComplete(BaseMutation, I18nMixin):site = get_site_promise(info.context).get()order, action_required, action_data = complete_checkout(- manager=manager,checkout_info=checkout_info,lines=lines,+ manager=manager,payment_data=payment_data or {},store_source=store_source,user=customer,diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.pyindex 781f328d99..3a69f549d2 100644--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py@@ -138,7 +138,6 @@ class OrderCreateFromCheckout(BaseMutation):try:order = create_order_from_checkout(checkout_info=checkout_info,- checkout_lines=checkout_lines,manager=manager,user=user,app=app,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 0046f02fcb..ab641dcf34 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -16,7 +16,7 @@ from .....account.models import Addressfrom .....checkout import calculationsfrom .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkout+from .....checkout.models import Checkout, CheckoutLinefrom .....core.exceptions import InsufficientStock, InsufficientStockDatafrom .....core.taxes import TaxError, zero_money, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType@@ -612,9 +612,9 @@ def test_checkout_complete_by_app(assert not data["errors"]mocked_complete_checkout.assert_called_once_with(- manager=ANY,checkout_info=ANY,lines=ANY,+ manager=ANY,payment_data=ANY,store_source=ANY,user=checkout.user,@@ -676,9 +676,9 @@ def test_checkout_complete_by_app_with_missing_permission(assert not data["errors"]mocked_complete_checkout.assert_called_once_with(- manager=ANY,checkout_info=ANY,lines=ANY,+ manager=ANY,payment_data=ANY,store_source=ANY,user=None,@@ -4152,3 +4152,68 @@ def test_checkout_complete_payment_create_create_run_in_meantime(errors = data["errors"]assert len(errors) == 1assert errors[0]["code"] == CheckoutErrorCode.INACTIVE_PAYMENT.name+++def test_checkout_complete_line_deleted_in_the_meantime(+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy,+ address,+ shipping_method,+):+ # given+ assert not gift_card.last_used_on++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})+ checkout.metadata_storage.store_value_in_private_metadata(+ items={"accepted": "false"}+ )+ checkout.tax_exemption = True+ checkout.save()+ checkout.metadata_storage.save()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ channel = checkout.channel+ channel.automatically_confirm_all_new_orders = True+ channel.save()+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ redirect_url = "https://www.example.com"+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}++ def delete_order_line(*args, **kwargs):+ CheckoutLine.objects.get(id=checkout.lines.first().id).delete()++ # when+ with before_after.before(+ "saleor.graphql.checkout.mutations.checkout_complete.complete_checkout",+ delete_order_line,+ ):+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert data["order"]+ assert not data["errors"]+ assert Order.objects.count() == orders_count + 1+ assert not Checkout.objects.filter(pk=checkout.pk).exists()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.pyindex 541028c173..8c660dd4b6 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@@ -755,6 +755,7 @@ def test_order_from_checkout_with_voucher(assert str(order.pk) == order_tokenassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata+ assert order.total_gross_amount < order.undiscounted_total_gross_amountorder_line = order.lines.first()assert checkout_line_quantity == order_line.quantitydiff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex 1b84a7831b..84e37842b2 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -202,9 +202,9 @@ def create_order(payment, checkout, manager):"Cannot create order - some products do not exist anymore.")order, _, _ = complete_checkout(- manager=manager,checkout_info=checkout_info,lines=lines,+ manager=manager,payment_data={},store_source=False,user=checkout.user or None,diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.pyindex 853c104387..7c5c010e5d 100644--- a/saleor/payment/gateways/stripe/webhooks.py+++ b/saleor/payment/gateways/stripe/webhooks.py@@ -197,9 +197,9 @@ def _finalize_checkout()order, _, _ = complete_checkout(- manager=manager,checkout_info=checkout_info,lines=lines,+ manager=manager,payment_data={},store_source=False,user=checkout.user or None,