Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove stock rows from lock during `checkoutComplete` (#11069)
Piotr Zabieglik349d88efcfec
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 665aa07234..a7f43a9452 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom typing import (TYPE_CHECKING,Any,@@ -12,9 +13,11 @@ from typing import (from uuid import UUIDimport graphene+from django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.db import transaction+from django.utils import timezonefrom prices import Money, TaxedMoneyfrom ..account.error_codes import AccountErrorCode@@ -26,6 +29,7 @@ from ..core.exceptions import GiftCardNotApplicable, InsufficientStockfrom ..core.postgres import FlatConcatSearchVectorfrom ..core.taxes import TaxError, zero_taxed_moneyfrom ..core.tracing import traced_atomic_transaction+from ..core.transactions import transaction_with_commit_on_errorsfrom ..core.utils.url import validate_storefront_urlfrom ..discount import DiscountInfo, DiscountValueType, OrderDiscountType, VoucherTypefrom ..discount.models import NotApplicable@@ -51,6 +55,7 @@ from ..payment.utils import fetch_customer_id, store_customer_idfrom ..product.models import ProductTranslation, ProductVariantTranslationfrom ..warehouse.availability import check_stock_and_preorder_quantity_bulkfrom ..warehouse.management import allocate_preorders, allocate_stocks+from ..warehouse.models import Reservation, Stockfrom ..warehouse.reservations import is_reservation_enabledfrom . import AddressTypefrom .base_calculations import (@@ -306,7 +311,6 @@ def _create_lines_for_order(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],discounts: Iterable[DiscountInfo],- check_reservations: bool,taxes_included_in_prices: bool,) -> Iterable[OrderLineInfo]:"""Create a lines for the given order.@@ -353,7 +357,7 @@ def _create_lines_for_order(additional_filter_lookup=additional_warehouse_lookup,existing_lines=lines,replace=True,- check_reservations=check_reservations,+ check_reservations=True,)return [@@ -378,7 +382,6 @@ def _prepare_order_data(lines: Iterable["CheckoutLineInfo"],discounts: Iterable["DiscountInfo"],taxes_included_in_prices: bool,- check_reservations: bool = False,) -> dict:"""Run checks and return all the data from a given checkout to create an order.@@ -435,7 +438,6 @@ def _prepare_order_data(checkout_info,lines,discounts,- check_reservations,taxes_included_in_prices,)@@ -557,7 +559,7 @@ def _create_order(manager,checkout_info.delivery_method_info.warehouse_pk,additional_warehouse_lookup,- check_reservations=is_reservation_enabled(site_settings),+ check_reservations=True,checkout_lines=[line.line for line in checkout_lines],)allocate_preorders(@@ -683,7 +685,6 @@ def _get_order_data(checkout_info=checkout_info,lines=lines,discounts=discounts,- check_reservations=is_reservation_enabled(site_settings),taxes_included_in_prices=site_settings.include_taxes_in_prices,)except InsufficientStock as e:@@ -732,6 +733,7 @@ def _process_payment(additional_data=payment_data,channel_slug=channel_slug,)+payment.refresh_from_db()if not txn.is_success:raise PaymentError(txn.error)@@ -741,22 +743,17 @@ def _process_payment(return txn-def complete_checkout(+def complete_checkout_pre_payment_part(manager: "PluginsManager",checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],- payment_data,- store_source,discounts,user,- app,site_settings=None,tracking_code=None,redirect_url=None,- metadata_list: Optional[List] = None,- private_metadata_list: Optional[List] = None,-) -> Tuple[Optional[Order], bool, dict]:- """Logic required to finalize the checkout and convert it to order.+) -> Tuple[Optional[Payment], Optional[str], dict]:+ """Logic required to process checkout before payment.Should be used with transaction_with_commit_on_errors, as there is a possibilityfor thread race.@@ -766,7 +763,11 @@ def complete_checkout(site_settings = Site.objects.get_current().settingsfetch_checkout_prices_if_expired(- checkout_info, manager, lines, discounts=discounts, site_settings=site_settings+ checkout_info,+ manager,+ lines,+ discounts=discounts,+ site_settings=site_settings,)checkout = checkout_info.checkout@@ -798,21 +799,28 @@ def complete_checkout(if payment and user:customer_id = fetch_customer_id(user=user, gateway=payment.gateway)+ return payment, customer_id, order_data+++def complete_checkout_post_payment_part(+ manager: "PluginsManager",+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ payment: Optional[Payment],+ txn: Optional[Transaction],+ order_data,+ user,+ app,+ site_settings=None,+ metadata_list: Optional[List] = None,+ private_metadata_list: Optional[List] = None,+) -> Tuple[Optional[Order], bool, dict]:action_required = Falseaction_data: Dict[str, str] = {}- if payment:- txn = _process_payment(- payment=payment, # type: ignore- customer_id=customer_id,- store_source=store_source,- payment_data=payment_data,- order_data=order_data,- manager=manager,- channel_slug=channel_slug,- )+ if payment and txn:if txn.customer_id and user:- store_customer_id(user, payment.gateway, txn.customer_id) # type: ignore+ store_customer_id(user, payment.gateway, txn.customer_id) # type:ignoreaction_required = txn.action_requiredif action_required:@@ -836,19 +844,23 @@ def complete_checkout(private_metadata_list=private_metadata_list,)# remove checkout after order is successfully created- checkout.delete()+ checkout_info.checkout.delete()except InsufficientStock as e:release_voucher_usage(order_data.get("voucher"), order_data.get("user_email"))- gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)+ gateway.payment_refund_or_void(+ payment, manager, channel_slug=checkout_info.channel.slug+ )error = prepare_insufficient_stock_checkout_validation_error(e)raise errorexcept GiftCardNotApplicable as e:release_voucher_usage(order_data.get("voucher"), order_data.get("user_email"))- gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)+ gateway.payment_refund_or_void(+ payment, manager, channel_slug=checkout_info.channel.slug+ )raise ValidationError(code=e.code, message=e.message)# if the order total value is 0 it is paid from the definition@@ -889,7 +901,6 @@ def _create_order_lines_from_checkout_lines(discounts: List["DiscountInfo"],manager: "PluginsManager",order_pk: Union[str, UUID],- reservation_enabled: bool,taxes_included_in_prices: bool,) -> List[OrderLineInfo]:order_lines_info = _create_lines_for_order(@@ -897,7 +908,6 @@ def _create_order_lines_from_checkout_lines(checkout_info,lines,discounts,- reservation_enabled,taxes_included_in_prices,)order_lines = []@@ -928,7 +938,7 @@ def _handle_allocations_of_order_lines(manager,checkout_info.delivery_method_info.warehouse_pk,additional_warehouse_lookup,- check_reservations=reservation_enabled,+ check_reservations=True,checkout_lines=[line.line for line in checkout_lines],)allocate_preorders(@@ -1106,7 +1116,6 @@ def _create_order_from_checkout(discounts=discounts,manager=manager,order_pk=order.pk,- reservation_enabled=reservation_enabled,taxes_included_in_prices=taxes_included_in_prices,)@@ -1213,3 +1222,142 @@ def create_order_from_checkout(checkout_info.voucher, checkout_info.checkout.get_customer_email())raise+++def complete_checkout(+ manager: "PluginsManager",+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ payment_data,+ store_source,+ discounts,+ user,+ app,+ site_settings=None,+ tracking_code=None,+ redirect_url=None,+ metadata_list: Optional[List] = None,+ private_metadata_list: Optional[List] = None,+) -> Tuple[Optional[Order], bool, dict]:+ """Logic required to finalize the checkout and convert it to order.++ Should be used with transaction_with_commit_on_errors, as there is a possibility+ for thread race.+ :raises ValidationError+ """+ with transaction_with_commit_on_errors():+ payment, customer_id, order_data = complete_checkout_pre_payment_part(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ discounts=discounts,+ user=user,+ site_settings=site_settings,+ tracking_code=tracking_code,+ redirect_url=redirect_url,+ )+ reservations = _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.+ txn = None+ if payment:+ txn = _process_payment(+ payment=payment,+ customer_id=customer_id,+ store_source=store_source,+ payment_data=payment_data,+ order_data=order_data,+ manager=manager,+ channel_slug=checkout_info.channel.slug,+ )++ with transaction_with_commit_on_errors():+ # Run pre-payment checks to make sure, that nothing has changed to the+ # checkout, during processing payment.+ checkout_info.checkout.voucher_code = None+ _, _, post_payment_order_data = complete_checkout_pre_payment_part(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ discounts=discounts,+ user=user,+ site_settings=site_settings,+ tracking_code=tracking_code,+ redirect_url=redirect_url,+ )+ 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],+):+ """Add additional temporary reservation for stock.++ Due to unlocking rows, for the time of external payment call, it prevents users+ ordering the same product, in the same time, which is out of stock.+ """+ variants = [line.variant for line in lines]+ stocks = Stock.objects.get_variants_stocks_for_country(+ country_code=checkout_info.get_country(),+ channel_slug=checkout_info.channel,+ products_variants=variants,+ )+ variants_stocks_map = {stock.product_variant_id: stock for stock in stocks}++ reservations = []+ for line in lines:+ if line.variant.id in variants_stocks_map:+ reservations.append(+ Reservation(+ quantity_reserved=line.line.quantity,+ reserved_until=timezone.now()+ + timedelta(seconds=settings.RESERVE_DURATION),+ stock=variants_stocks_map[line.variant.id],+ checkout_line=line.line,+ )+ )+ Reservation.objects.bulk_create(reservations)+ return reservationsdiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 3f94b453fb..a9dda54f79 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -1295,9 +1295,7 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(@mock.patch("saleor.checkout.complete_checkout._create_order")- "saleor.checkout.complete_checkout._process_payment",-)[email protected]("saleor.checkout.complete_checkout._process_payment")def test_complete_checkout_action_required_voucher_once_per_customer(mocked_process_payment,mocked_create_order,diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.pyindex 08daac5d07..3705b2d997 100644--- a/saleor/graphql/checkout/mutations/checkout_complete.py+++ b/saleor/graphql/checkout/mutations/checkout_complete.py@@ -19,7 +19,6 @@ from ....checkout.fetch import (from ....checkout.utils import is_shipping_requiredfrom ....core import analyticsfrom ....core.permissions import AccountPermissions-from ....core.transactions import transaction_with_commit_on_errorsfrom ....order import models as order_modelsfrom ...account.i18n import I18nMixinfrom ...app.dataloaders import load_app@@ -172,108 +171,109 @@ class CheckoutComplete(BaseMutation, I18nMixin):validate_one_of_args_is_in_mutation(CheckoutErrorCode, "checkout_id", checkout_id, "token", token, "id", id)-tracking_code = analytics.get_client_id(info.context)- with transaction_with_commit_on_errors():- try:- checkout = get_checkout(- cls,- info,- checkout_id=checkout_id,- token=token,- id=id,- error_class=CheckoutErrorCode,++ try:+ checkout = get_checkout(+ cls,+ info,+ checkout_id=checkout_id,+ token=token,+ id=id,+ error_class=CheckoutErrorCode,+ )+ except ValidationError as e:+ # DEPRECATED+ if id or checkout_id:+ id = id or checkout_id+ token = cls.get_global_id_or_error(+ id, only_type=Checkout, field="id" if id else "checkout_id")- except ValidationError as e:- # DEPRECATED- if id or checkout_id:- id = id or checkout_id- token = cls.get_global_id_or_error(- id, only_type=Checkout, field="id" if id else "checkout_id"- )- order = order_models.Order.objects.get_by_checkout_token(token)- if order:- if not order.channel.is_active:- raise ValidationError(- {- "channel": ValidationError(- "Cannot complete checkout with inactive channel.",- code=CheckoutErrorCode.CHANNEL_INACTIVE.value,- )- }- )- # The order is already created. We return it as a success- # checkoutComplete response. Order is anonymized for not logged in- # user- return CheckoutComplete(- order=order, confirmation_needed=False, confirmation_data={}+ order = order_models.Order.objects.get_by_checkout_token(token)+ if order:+ if not order.channel.is_active:+ raise ValidationError(+ {+ "channel": ValidationError(+ "Cannot complete checkout with inactive channel.",+ code=CheckoutErrorCode.CHANNEL_INACTIVE.value,+ )+ })- raise e-- metadata = data.get("metadata")- if metadata is not None:- cls.check_metadata_permissions(- info,- id or checkout_id or graphene.Node.to_global_id("Checkout", token),+ # The order is already created. We return it as a success+ # checkoutComplete response. Order is anonymized for not logged in+ # user+ return CheckoutComplete(+ order=order, confirmation_needed=False, confirmation_data={})- cls.validate_metadata_keys(metadata)+ raise e- validate_checkout_email(checkout)+ metadata = data.get("metadata")+ if metadata is not None:+ cls.check_metadata_permissions(+ info,+ id or checkout_id or graphene.Node.to_global_id("Checkout", token),+ )+ cls.validate_metadata_keys(metadata)- manager = load_plugin_manager(info.context)- lines, unavailable_variant_pks = fetch_checkout_lines(checkout)- if unavailable_variant_pks:- not_available_variants_ids = {- graphene.Node.to_global_id("ProductVariant", pk)- for pk in unavailable_variant_pks+ validate_checkout_email(checkout)++ manager = load_plugin_manager(info.context)+ lines, unavailable_variant_pks = fetch_checkout_lines(checkout)+ if unavailable_variant_pks:+ not_available_variants_ids = {+ graphene.Node.to_global_id("ProductVariant", pk)+ for pk in unavailable_variant_pks+ }+ raise ValidationError(+ {+ "lines": ValidationError(+ "Some of the checkout lines variants are unavailable.",+ code=CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value,+ params={"variants": not_available_variants_ids},+ )}- raise ValidationError(- {- "lines": ValidationError(- "Some of the checkout lines variants are unavailable.",- code=CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value,- params={"variants": not_available_variants_ids},- )- }- )- if not lines:- raise ValidationError(- {- "lines": ValidationError(- "Cannot complete checkout without lines.",- code=CheckoutErrorCode.NO_LINES.value,- )- }- )- discounts = load_discounts(info.context)- checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)+ )+ if not lines:+ raise ValidationError(+ {+ "lines": ValidationError(+ "Cannot complete checkout without lines.",+ code=CheckoutErrorCode.NO_LINES.value,+ )+ }+ )+ discounts = load_discounts(info.context)+ checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)- cls.validate_checkout_addresses(checkout_info, lines)+ cls.validate_checkout_addresses(checkout_info, lines)- requestor = get_user_or_app_from_context(info.context)- if requestor and requestor.has_perm(AccountPermissions.IMPERSONATE_USER):- # Allow impersonating user and process a checkout by using user details- # assigned to checkout.- customer = checkout.user- else:- customer = info.context.user+ requestor = get_user_or_app_from_context(info.context)+ if requestor and requestor.has_perm(AccountPermissions.IMPERSONATE_USER):+ # Allow impersonating user and process a checkout by using user details+ # assigned to checkout.+ customer = checkout.user+ else:+ customer = info.context.user++ site = load_site(info.context)++ order, action_required, action_data = complete_checkout(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ payment_data=data.get("payment_data", {}),+ store_source=store_source,+ discounts=discounts,+ user=customer,+ app=load_app(info.context),+ site_settings=site.settings,+ tracking_code=tracking_code,+ redirect_url=data.get("redirect_url"),+ metadata_list=data.get("metadata"),+ )- site = load_site(info.context)- order, action_required, action_data = complete_checkout(- manager=manager,- checkout_info=checkout_info,- lines=lines,- payment_data=data.get("payment_data", {}),- store_source=store_source,- discounts=discounts,- user=customer,- app=load_app(info.context),- site_settings=site.settings,- tracking_code=tracking_code,- redirect_url=data.get("redirect_url"),- metadata_list=data.get("metadata"),- )# If gateway returns information that additional steps are required we need# to inform the frontend and pass all required datareturn CheckoutComplete(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex a5115c65aa..c3809f4e3f 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -5,6 +5,7 @@ from unittest.mock import ANY, patchimport grapheneimport pytestimport pytz+from django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.db.models.aggregates import Sumfrom django.utils import timezone@@ -302,13 +303,14 @@ def test_checkout_complete(assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER)-assert not Checkout.objects.filter(pk=checkout.pk).exists(), "Checkout should have been deleted"order_confirmed_mock.assert_called_once_with(order)_recalculate_order_prices_mock.assert_not_called()+ assert not len(Reservation.objects.all())+@pytest.mark.integration@patch("saleor.plugins.manager.PluginsManager.order_confirmed")@@ -1739,7 +1741,6 @@ def test_checkout_complete_payment_payment_total_different_than_checkout(def test_order_already_exists(user_api_client, checkout_ready_to_complete, payment_dummy, order_with_lines):-checkout = checkout_ready_to_completeorder_with_lines.checkout_token = checkout.tokenorder_with_lines.save()@@ -3198,3 +3199,111 @@ def test_checkout_complete_with_not_normalized_billing_address(assert billing_addressassert billing_address.city == "WASHINGTON"assert billing_address.country_area == "DC"++[email protected](PluginsManager, "process_payment")+def test_checkout_complete_check_reservations_create(+ mocked_process_payment,+ user_api_client,+ checkout_with_item,+ address,+ payment_dummy,+ shipping_method,+ action_required_gateway_response,+):+ # given+ mocked_process_payment.return_value = action_required_gateway_response++ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ 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()++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ orders_count = Order.objects.count()+ assert not len(Reservation.objects.all())++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["errors"]+ assert data["confirmationNeeded"] is True++ reservations = Reservation.objects.all()+ assert len(reservations) == 1+ assert reservations[0].checkout_line.checkout.token == checkout.token+ assert reservations[0].reserved_until <= timezone.now() + timedelta(+ seconds=settings.RESERVE_DURATION+ )+ assert Order.objects.count() == orders_count+++def test_checkout_complete_reservations_drop(+ site_settings,+ 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.tax_exemption = True+ checkout.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+ )+ site_settings.automatically_confirm_all_new_orders = True+ site_settings.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()++ redirect_url = "https://www.example.com"+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["errors"]+ assert not len(Reservation.objects.all())diff --git a/saleor/settings.py b/saleor/settings.pyindex 21061d1502..c3ed605d93 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -722,6 +722,11 @@ if (WEBHOOK_TIMEOUT = 10WEBHOOK_SYNC_TIMEOUT = 20+# Since we split checkout complete logic into two separate transactions, in order to+# mimic stock lock, we apply short reservation for the stocks. The value represents+# time of the reservation in seconds.+RESERVE_DURATION = 45+# Initialize a simple and basic Jaeger Tracing integration# for open-tracing if enabled.#