Skip to content

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

Handle concurrency `checkoutPaymentCreate` and `checkoutComplete` (#15994)

Iga Karbowiak65dfc61ec9fc
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 92b92ead51..5fe7a3b07a 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -148,12 +148,16 @@ def _release_checkout_voucher_usage(
voucher_code: Optional["VoucherCode"],
voucher: Optional["Voucher"],
user_email: Optional[str],
+ checkout_update_fields: Optional[list[str]] = None,
):
if not checkout.is_voucher_usage_increased:
return
checkout.is_voucher_usage_increased = False
- checkout.save(update_fields=["is_voucher_usage_increased"])
+ if checkout_update_fields is None:
+ checkout.save(update_fields=["is_voucher_usage_increased"])
+ else:
+ checkout_update_fields.append("is_voucher_usage_increased")
if voucher_code:
release_voucher_code_usage(
@@ -856,12 +860,11 @@ def _get_order_data(
def _process_payment(
- checkout: Checkout,
+ checkout_info: CheckoutInfo,
payment: Payment,
customer_id: Optional[str],
store_source: bool,
payment_data: Optional[dict],
- order_data: dict,
manager: "PluginsManager",
channel_slug: str,
voucher_code: Optional["VoucherCode"] = None,
@@ -891,9 +894,7 @@ def _process_payment(
if not txn.is_success:
raise PaymentError(txn.error)
except PaymentError as e:
- _release_checkout_voucher_usage(
- checkout, voucher_code, voucher, order_data.get("user_email")
- )
+ _complete_checkout_fail_handler(checkout_info, manager)
raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR.value)
return txn
@@ -918,7 +919,6 @@ def complete_checkout_pre_payment_part(
fetch_checkout_data(checkout_info, manager, lines)
checkout = checkout_info.checkout
- channel_slug = checkout_info.channel.slug
payment = checkout.get_last_active_payment()
try:
_prepare_checkout_with_payment(
@@ -929,13 +929,13 @@ def complete_checkout_pre_payment_part(
payment=payment,
)
except ValidationError as exc:
- gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)
+ _complete_checkout_fail_handler(checkout_info, manager, payment=payment)
raise exc
try:
order_data = _get_order_data(manager, checkout_info, lines, site_settings)
except ValidationError as exc:
- gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)
+ _complete_checkout_fail_handler(checkout_info, manager, payment=payment)
raise exc
customer_id = None
@@ -992,26 +992,22 @@ def complete_checkout_post_payment_part(
# remove checkout after order is successfully created
checkout_info.checkout.delete()
except InsufficientStock as e:
- _release_checkout_voucher_usage(
- checkout_info.checkout,
- checkout_info.voucher_code,
- checkout_info.voucher,
- order_data.get("user_email"),
- )
- gateway.payment_refund_or_void(
- payment, manager, channel_slug=checkout_info.channel.slug
+ _complete_checkout_fail_handler(
+ checkout_info,
+ manager,
+ voucher_code=checkout_info.voucher_code,
+ voucher=checkout_info.voucher,
+ payment=payment,
)
error = prepare_insufficient_stock_checkout_validation_error(e)
raise error
except GiftCardNotApplicable as e:
- _release_checkout_voucher_usage(
- checkout_info.checkout,
- checkout_info.voucher_code,
- checkout_info.voucher,
- order_data.get("user_email"),
- )
- gateway.payment_refund_or_void(
- payment, manager, channel_slug=checkout_info.channel.slug
+ _complete_checkout_fail_handler(
+ checkout_info,
+ manager,
+ voucher_code=checkout_info.voucher_code,
+ voucher=checkout_info.voucher,
+ payment=payment,
)
raise ValidationError(code=e.code, message=e.message)
@@ -1411,13 +1407,19 @@ def create_order_from_checkout(
checkout_info.checkout.delete()
return order
except InsufficientStock:
- _release_checkout_voucher_usage(
- checkout, code, voucher, checkout_info.checkout.get_customer_email()
+ _complete_checkout_fail_handler(
+ checkout_info,
+ manager,
+ voucher_code=code,
+ voucher=voucher,
)
raise
except GiftCardNotApplicable:
- _release_checkout_voucher_usage(
- checkout, code, voucher, checkout_info.checkout.get_customer_email()
+ _complete_checkout_fail_handler(
+ checkout_info,
+ manager,
+ voucher_code=code,
+ voucher=voucher,
)
raise
@@ -1571,6 +1573,9 @@ def complete_checkout_with_payment(
order = Order.objects.get_by_checkout_token(checkout_pk)
return order, False, {}
+ checkout.completing_started_at = timezone.now()
+ checkout.save(update_fields=["completing_started_at"])
+
# 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)
@@ -1606,12 +1611,11 @@ def complete_checkout_with_payment(
payment = Payment.objects.select_for_update().get(id=payment.id)
txn = _process_payment(
- checkout=checkout,
+ checkout_info=checkout_info,
payment=payment,
customer_id=customer_id,
store_source=store_source,
payment_data=payment_data,
- order_data=order_data,
manager=manager,
channel_slug=channel_slug,
voucher_code=checkout_info.voucher_code,
@@ -1623,8 +1627,11 @@ def complete_checkout_with_payment(
# refund the payment.
payment.refresh_from_db()
if not payment.is_active:
- gateway.payment_refund_or_void(
- payment, manager, channel_slug=channel_slug
+ _complete_checkout_fail_handler(
+ checkout_info,
+ manager,
+ voucher=order_data.get("voucher"),
+ payment=payment,
)
raise ValidationError(
f"The payment with pspReference: {payment.psp_reference} is "
@@ -1665,6 +1672,9 @@ def complete_checkout_with_payment(
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
)
+ if checkout.pk:
+ checkout.completing_started_at = None
+ checkout.save(update_fields=["completing_started_at"])
return order, action_required, action_data
@@ -1700,3 +1710,43 @@ def _reserve_stocks_without_availability_check(
)
Reservation.objects.bulk_create(reservations)
return reservations
+
+
+def _complete_checkout_fail_handler(
+ checkout_info: "CheckoutInfo",
+ manager: "PluginsManager",
+ *,
+ voucher_code: Optional["VoucherCode"] = None,
+ voucher: Optional["Voucher"] = None,
+ payment: Optional[Payment] = None,
+) -> None:
+ """Handle the case when the checkout completion failed.
+
+ - Release the checkout processing indicator.
+ - Release the voucher usage.
+ - Refund or void the payment.
+ """
+ checkout = checkout_info.checkout
+ update_fields = []
+ if checkout.completing_started_at is not None:
+ # release the checkout processing indicator
+ checkout.completing_started_at = None
+ update_fields.append("completing_started_at")
+
+ # release the voucher usage
+ if voucher:
+ _release_checkout_voucher_usage(
+ checkout,
+ voucher_code,
+ voucher,
+ checkout.get_customer_email(),
+ update_fields,
+ )
+
+ if update_fields:
+ checkout.save(update_fields=update_fields)
+
+ if payment:
+ gateway.payment_refund_or_void(
+ payment, manager, channel_slug=checkout_info.channel.slug
+ )
diff --git a/saleor/checkout/migrations/0065_checkout_completing_started_at.py b/saleor/checkout/migrations/0065_checkout_completing_started_at.py
new file mode 100644
index 0000000000..311bfda03b
--- /dev/null
+++ b/saleor/checkout/migrations/0065_checkout_completing_started_at.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.23 on 2024-05-08 12:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0064_checkout_is_voucher_usage_increased"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="completing_started_at",
+ field=models.DateTimeField(blank=True, null=True),
+ )
+ ]
diff --git a/saleor/checkout/migrations/0069_merge_20240514_1008.py b/saleor/checkout/migrations/0069_merge_20240514_1008.py
new file mode 100644
index 0000000000..4d077827ed
--- /dev/null
+++ b/saleor/checkout/migrations/0069_merge_20240514_1008.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.25 on 2024-05-14 10:08
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0065_checkout_completing_started_at"),
+ ("checkout", "0068_merge_20240424_1209"),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 291965a248..e034d7a064 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -37,6 +37,7 @@ class Checkout(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
last_change = models.DateTimeField(auto_now=True, db_index=True)
+ completing_started_at = models.DateTimeField(blank=True, null=True)
# Denormalized modified_at for the latest modified transactionItem assigned to
# checkout
@@ -218,6 +219,15 @@ class Checkout(models.Model):
"""Return `True` if any of the lines requires shipping."""
return any(line.is_shipping_required() for line in self)
+ def is_checkout_locked(self) -> bool:
+ return bool(
+ self.completing_started_at
+ and (
+ (timezone.now() - self.completing_started_at).seconds
+ < settings.CHECKOUT_COMPLETION_LOCK_TIME
+ )
+ )
+
def get_total_gift_cards_balance(
self, database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME
) -> Money:
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 635976016c..9537c2c358 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -30,6 +30,7 @@ from ...product.models import ProductTranslation, ProductVariantTranslation
from ...tests.utils import flush_post_commit_hooks
from .. import calculations
from ..complete_checkout import (
+ _complete_checkout_fail_handler,
_create_order,
_increase_checkout_voucher_usage,
_prepare_order_data,
@@ -1456,6 +1457,10 @@ def test_complete_checkout_action_required_voucher_single_use(
assert action_required is True
assert not voucher_customer.exists()
mocked_create_order.assert_not_called()
+ checkout.refresh_from_db()
+ assert checkout.is_voucher_usage_increased is False
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
code.refresh_from_db()
assert code.is_active is True
@@ -1512,6 +1517,8 @@ def test_complete_checkout_order_not_created_when_the_refund_is_ongoing(
# then
assert not order
mocked_create_order.assert_not_called()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@mock.patch("saleor.checkout.complete_checkout._create_order")
@@ -2355,3 +2362,113 @@ def test_release_checkout_voucher_usage_no_voucher_code(
checkout_with_voucher.refresh_from_db()
assert checkout_with_voucher.is_voucher_usage_increased is False
release_voucher_usage_mock.assert_not_called()
+
+
[email protected]("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
[email protected]("saleor.checkout.complete_checkout._release_checkout_voucher_usage")
+def test_complete_checkout_fail_handler(
+ _release_checkout_voucher_usage_mock,
+ _payment_refund_or_void_mock,
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+ checkout.completing_started_at = timezone.now()
+ checkout.save(update_fields=["completing_started_at"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ _complete_checkout_fail_handler(checkout_info, manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+ _payment_refund_or_void_mock.assert_not_called()
+ _release_checkout_voucher_usage_mock.assert_not_called()
+
+
[email protected]("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
[email protected]("saleor.checkout.complete_checkout._release_checkout_voucher_usage")
+def test_complete_checkout_fail_handler_with_voucher(
+ _release_checkout_voucher_usage_mock,
+ _payment_refund_or_void_mock,
+ checkout_with_voucher,
+ voucher,
+):
+ # given
+ checkout = checkout_with_voucher
+ checkout.completing_started_at = timezone.now()
+ checkout.save(update_fields=["completing_started_at"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ _complete_checkout_fail_handler(checkout_info, manager, voucher=voucher)
+
+ # then
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+ _payment_refund_or_void_mock.assert_not_called()
+ _release_checkout_voucher_usage_mock.assert_called_once()
+
+
[email protected]("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
[email protected]("saleor.checkout.complete_checkout._release_checkout_voucher_usage")
+def test_complete_checkout_fail_handler_with_payment(
+ _release_checkout_voucher_usage_mock,
+ _payment_refund_or_void_mock,
+ checkout_with_item,
+ payment,
+):
+ # given
+ checkout = checkout_with_item
+ checkout.completing_started_at = timezone.now()
+ checkout.save(update_fields=["completing_started_at"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ _complete_checkout_fail_handler(checkout_info, manager, payment=payment)
+
+ # then
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+ _payment_refund_or_void_mock.assert_called_once()
+ _release_checkout_voucher_usage_mock.assert_not_called()
+
+
[email protected]("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
[email protected]("saleor.checkout.complete_checkout._release_checkout_voucher_usage")
+def test_complete_checkout_fail_handler_with_voucher_and_payment(
+ _release_checkout_voucher_usage_mock,
+ _payment_refund_or_void_mock,
+ checkout_with_voucher,
+ payment,
+ voucher,
+):
+ # given
+ checkout = checkout_with_voucher
+ checkout.completing_started_at = timezone.now()
+ checkout.save(update_fields=["completing_started_at"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ _complete_checkout_fail_handler(
+ checkout_info, manager, voucher=voucher, payment=payment
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+ _payment_refund_or_void_mock.assert_called_once()
+ _release_checkout_voucher_usage_mock.assert_called_once()
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index c772786682..a67f5f79cb 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -25,6 +25,7 @@ from .....giftcard.models import GiftCard, GiftCardEvent
from .....order import OrderOrigin, OrderStatus
from .....order.models import Fulfillment, Order
from .....payment import ChargeStatus, PaymentError, TransactionKind
+from .....payment.error_codes import PaymentErrorCode
from .....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPING
from .....payment.interface import GatewayResponse
from .....payment.model_helpers import get_subtotal
@@ -153,6 +154,8 @@ def test_checkout_complete_with_inactive_channel(
data = content["data"]["checkoutComplete"]
assert data["errors"][0]["code"] == CheckoutErrorCode.CHANNEL_INACTIVE.name
assert data["errors"][0]["field"] == "channel"
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@pytest.mark.integration
@@ -785,6 +788,8 @@ def test_checkout_complete_with_variant_without_price(
assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
assert errors[0]["field"] == "lines"
assert errors[0]["variants"] == [variant_id]
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@patch("saleor.order.calculations._recalculate_with_plugins")
@@ -1882,6 +1887,8 @@ def test_checkout_with_voucher_not_increase_uses_on_preprocess_order_creation_fa
assert Checkout.objects.filter(
pk=checkout.pk
).exists(), "Checkout shouldn't have been deleted"
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@pytest.mark.integration
@@ -2011,6 +2018,8 @@ def test_checkout_complete_checkout_without_lines(
assert len(errors) == 1
assert errors[0]["field"] == "lines"
assert errors[0]["code"] == CheckoutErrorCode.NO_LINES.name
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@pytest.mark.integration
@@ -2072,6 +2081,8 @@ def test_checkout_complete_error_in_gateway_response_for_dummy_credit_card(
assert data["errors"][0]["message"] == error
assert payment.transactions.count() == 1
assert Order.objects.count() == orders_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
ERROR_GATEWAY_RESPONSE = GatewayResponse(
@@ -2157,6 +2168,8 @@ def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
assert Checkout.objects.filter(
pk=checkout.pk
).exists(), "Checkout should not have been deleted"
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
mocked_process_payment.assert_called_once()
@@ -2193,6 +2206,8 @@ def test_checkout_complete_no_payment(
"Provided payment methods can not cover the checkout's total amount"
)
assert orders_count == Order.objects.count()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@patch.object(PluginsManager, "process_payment")
@@ -2205,6 +2220,7 @@ def test_checkout_complete_confirmation_needed(
shipping_method,
action_required_gateway_response,
):
+ # given
mocked_process_payment.return_value = action_required_gateway_response
checkout = checkout_with_item
@@ -2233,7 +2249,10 @@ def test_checkout_complete_confirmation_needed(
}
orders_count = Order.objects.count()
+ # 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"]
@@ -2249,6 +2268,9 @@ def test_checkout_complete_confirmation_needed(
mocked_process_payment.assert_called_once()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+
@patch.object(PluginsManager, "confirm_payment")
def test_checkout_confirm(
@@ -2342,6 +2364,9 @@ def test_checkout_complete_insufficient_stock(
assert data["errors"][0]["message"] == "Insufficient product stock: 123"
assert orders_count == Order.objects.count()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+
@patch("saleor.checkout.complete_checkout.gateway.refund")
def test_checkout_complete_insufficient_stock_payment_refunded(
@@ -2401,6 +2426,9 @@ def test_checkout_complete_insufficient_stock_payment_refunded(
payment, ANY, channel_slug=checkout_info.channel.slug
)
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+
@patch("saleor.checkout.complete_checkout.gateway.void")
def test_checkout_complete_insufficient_stock_payment_voided(
@@ -2460,6 +2488,9 @@ def test_checkout_complete_insufficient_stock_payment_voided(
payment, ANY, channel_slug=checkout_info.channel.slug
)
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+
def test_checkout_complete_insufficient_stock_reserved_by_other_user(
site_settings_with_reservations,
@@ -2518,6 +2549,8 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
data = content["data"]["checkoutComplete"]
assert data["errors"][0]["message"] == "Insufficient product stock: 123"
assert orders_count == Order.objects.count()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_own_reservation(
@@ -2710,6 +2743,8 @@ def test_checkout_complete_payment_payment_total_different_than_checkout(
assert data["errors"][0]["code"] == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name
assert orders_count == Order.objects.count()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
gateway_refund_or_void_mock.assert_called_with(
payment, ANY, channel_slug=checkout_info.channel.slug
@@ -2776,6 +2811,8 @@ def test_create_order_raises_insufficient_stock(
data = content["data"]["checkoutComplete"]
assert data["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name
assert mocked_create_order.called
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
@@ -3243,6 +3280,8 @@ def test_checkout_complete_raises_InvalidShippingMethod_when_warehouse_disabled(
content["errors"][0]["code"] == CheckoutErrorCode.INVALID_SHIPPING_METHOD.name
)
assert Order.objects.count() == initial_order_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@pytest.mark.integration
@@ -3398,6 +3437,8 @@ def test_checkout_complete_with_click_collect_preorder_fails_for_disabled_wareho
content["errors"][0]["code"] == CheckoutErrorCode.INVALID_SHIPPING_METHOD.name
)
assert Order.objects.count() == initial_order_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_variant_channel_listing_does_not_exist(
@@ -3460,6 +3501,8 @@ def test_checkout_complete_variant_channel_listing_does_not_exist(
assert Order.objects.count() == orders_count
assert Checkout.objects.filter(pk=checkout.pk).exists()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_variant_channel_listing_no_price(
@@ -3527,6 +3570,8 @@ def test_checkout_complete_variant_channel_listing_no_price(
assert Order.objects.count() == orders_count
assert Checkout.objects.filter(pk=checkout.pk).exists()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_product_channel_listing_does_not_exist(
@@ -3590,6 +3635,8 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
assert Order.objects.count() == orders_count
assert Checkout.objects.filter(pk=checkout.pk).exists()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@pytest.mark.parametrize(
@@ -3659,6 +3706,8 @@ def test_checkout_complete_product_channel_listing_not_available_for_purchase(
assert Order.objects.count() == orders_count
assert Checkout.objects.filter(pk=checkout.pk).exists()
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_fields(
@@ -3719,6 +3768,8 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_
assert data["errors"][0]["code"] == "REQUIRED"
assert data["errors"][0]["field"] == "postalCode"
assert Order.objects.count() == orders_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fields(
@@ -3780,6 +3831,8 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fie
assert data["errors"][0]["code"] == "INVALID"
assert data["errors"][0]["field"] == "postalCode"
assert Order.objects.count() == orders_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_fields(
@@ -3839,6 +3892,8 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_f
assert data["errors"][0]["code"] == "REQUIRED"
assert data["errors"][0]["field"] == "postalCode"
assert Order.objects.count() == orders_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fields(
@@ -3900,6 +3955,8 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fiel
assert data["errors"][0]["code"] == "INVALID"
assert data["errors"][0]["field"] == "postalCode"
assert Order.objects.count() == orders_count
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
def test_checkout_complete_with_not_normalized_shipping_address(
@@ -4180,7 +4237,8 @@ def test_checkout_complete_payment_create_create_run_in_meantime(
variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
# Call CheckoutPaymentCreate mutation during the CheckoutComplete call processing.
- # It should cause deactivation of current payment and creation of new one.
+ # CheckoutPaymentCreate should raise an error and do not influence
+ # the CheckoutComplete call.
def call_payment_create_mutation(*args, **kwargs):
from ....payment.tests.mutations.test_checkout_payment_create import (
CREATE_PAYMENT_MUTATION,
@@ -4196,7 +4254,13 @@ def test_checkout_complete_payment_create_create_run_in_meantime(
},
}
- user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)
+ response = user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)
+ data = get_graphql_content(response)["data"]["checkoutPaymentCreate"]
+ assert len(data["errors"]) == 1
+ assert (
+ data["errors"][0]["code"]
+ == PaymentErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.name
+ )
# when
with before_after.after(
@@ -4205,12 +4269,75 @@ def test_checkout_complete_payment_create_create_run_in_meantime(
):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ errors = data["errors"]
+ assert not errors
+ assert data["order"]
+
+
[email protected]_db(transaction=True)
+def test_checkout_complete_payment_payment_deactivated_in_meantime(
+ site_settings,
+ user_api_client,
+ checkout_without_shipping_required,
+ gift_card,
+ payment_dummy,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_without_shipping_required
+ 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.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ 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()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ def deactivate_payment(*args, **kwargs):
+ payment.is_active = False
+ payment.save(update_fields=["is_active"])
+
+ # when
+ with before_after.after(
+ "saleor.checkout.complete_checkout._process_payment",
+ deactivate_payment,
+ ):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
# then
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
errors = data["errors"]
assert len(errors) == 1
assert errors[0]["code"] == CheckoutErrorCode.INACTIVE_PAYMENT.name
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
@pytest.mark.integration
diff --git a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
index fba470127c..7e27c8b0cb 100644
--- a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
+++ b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
@@ -1,4 +1,5 @@
import graphene
+from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -294,6 +295,13 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
"Checkout doesn't exist anymore.",
code=PaymentErrorCode.NOT_FOUND.value,
)
+ if checkout.is_checkout_locked():
+ raise ValidationError(
+ "Payment cannot be created - the checkout completion is currently "
+ "in progress. Please wait until the process is finished "
+ f"(max {settings.CHECKOUT_COMPLETION_LOCK_TIME} seconds).",
+ code=PaymentErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.value,
+ )
cancel_active_payments(checkout)
diff --git a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
index 0fdfeef6ab..55e6d0c85f 100644
--- a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import before_after
import graphene
import pytest
+from django.utils import timezone
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
@@ -807,3 +808,81 @@ def test_with_active_problems_flow(
# then
assert not content["data"]["checkoutPaymentCreate"]["errors"]
+
+
+def test_checkout_payment_create_checkout_locked(
+ user_api_client, checkout_without_shipping_required, address, customer_user
+):
+ # given
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.email = "old@example"
+ checkout.user = customer_user
+ checkout.completing_started_at = timezone.now()
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ 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
+ )
+ return_url = "https://www.example.com"
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "input": {
+ "gateway": DUMMY_GATEWAY,
+ "token": "sample-token",
+ "amount": total.gross.amount,
+ "returnUrl": return_url,
+ },
+ }
+
+ # when
+ response = user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutPaymentCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] is None
+ assert errors[0]["code"] == PaymentErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.name
+
+
+def test_checkout_payment_create_checkout_locked_time_pass(
+ user_api_client, checkout_without_shipping_required, address, customer_user
+):
+ # given
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.email = "old@example"
+ checkout.user = customer_user
+ checkout.completing_started_at = timezone.now() - timezone.timedelta(minutes=10)
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ 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
+ )
+ return_url = "https://www.example.com"
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "input": {
+ "gateway": DUMMY_GATEWAY,
+ "token": "sample-token",
+ "amount": total.gross.amount,
+ "returnUrl": return_url,
+ },
+ }
+
+ # when
+ response = user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutPaymentCreate"]
+ assert not data["errors"]
+ assert data["payment"]
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 8beb9a4126..a4b01ca810 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -24437,6 +24437,7 @@ enum PaymentErrorCode @doc(category: "Payments") {
CHECKOUT_EMAIL_NOT_SET
UNAVAILABLE_VARIANT_IN_CHANNEL
NO_CHECKOUT_LINES
+ CHECKOUT_COMPLETION_IN_PROGRESS
}
"""
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index f0883ecc8a..856a8397d8 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -19,6 +19,7 @@ class PaymentErrorCode(Enum):
CHECKOUT_EMAIL_NOT_SET = "checkout_email_not_set"
UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"
NO_CHECKOUT_LINES = "no_checkout_lines"
+ CHECKOUT_COMPLETION_IN_PROGRESS = "checkout_completion_in_progress"
class TransactionCreateErrorCode(Enum):
diff --git a/saleor/payment/migrations/0056_fix_invalid_atobarai_payments.py b/saleor/payment/migrations/0056_fix_invalid_atobarai_payments.py
new file mode 100644
index 0000000000..bd28310d98
--- /dev/null
+++ b/saleor/payment/migrations/0056_fix_invalid_atobarai_payments.py
@@ -0,0 +1,64 @@
+from django.db import migrations
+from django.db.models import Exists, OuterRef
+
+# Batch size of size 3000 took about 0.2s and consume about 5MB memory usage
+PAYMENT_BATCH_SIZE = 3000
+
+
+def fix_invalid_atobarai_payments(apps, schema_editor):
+ Payment = apps.get_model("payment", "Payment")
+ not_charged_active_payments = Payment.objects.filter(
+ is_active=True,
+ charge_status="not-charged",
+ captured_amount=0,
+ gateway="saleor.payments.np-atobarai",
+ )
+ payments = Payment.objects.filter(
+ Exists(not_charged_active_payments.filter(order_id=OuterRef("order_id"))),
+ is_active=False,
+ charge_status__in=[
+ "fully-charged",
+ "partially-charged",
+ ],
+ captured_amount__gt=0,
+ gateway="saleor.payments.np-atobarai",
+ )
+ for ids in queryset_in_batches(payments):
+ payments_to_activate = Payment.objects.filter(pk__in=ids)
+
+ related_order_ids = payments_to_activate.values("order_id")
+ payments_to_deactivate = Payment.objects.filter(
+ order_id__in=related_order_ids, is_active=True
+ ).exclude(pk__in=ids)
+
+ payments_to_deactivate.update(is_active=False)
+ payments_to_activate.update(is_active=True)
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:PAYMENT_BATCH_SIZE]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0055_add_constraints_from_indexes"),
+ ]
+
+ operations = [
+ migrations.RunPython(fix_invalid_atobarai_payments, migrations.RunPython.noop),
+ ]
diff --git a/saleor/payment/migrations/0057_merge_20240514_0825.py b/saleor/payment/migrations/0057_merge_20240514_0825.py
new file mode 100644
index 0000000000..b0a6e3e9d7
--- /dev/null
+++ b/saleor/payment/migrations/0057_merge_20240514_0825.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2024-05-14 08:25
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0056_fix_invalid_atobarai_payments"),
+ ("payment", "0056_merge_20231213_0755"),
+ ]
+
+ operations = []
diff --git a/saleor/payment/migrations/0058_merge_20240514_1004.py b/saleor/payment/migrations/0058_merge_20240514_1004.py
new file mode 100644
index 0000000000..5ee170b28b
--- /dev/null
+++ b/saleor/payment/migrations/0058_merge_20240514_1004.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.25 on 2024-05-14 10:04
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0057_merge_20240514_0825"),
+ ("payment", "0057_transactionevent_related_granted_refund"),
+ ]
+
+ operations = []
diff --git a/saleor/payment/migrations/tasks/__init__.py b/saleor/payment/migrations/tasks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/migrations/tasks/saleor3_19.py b/saleor/payment/migrations/tasks/saleor3_19.py
new file mode 100644
index 0000000000..336618aaeb
--- /dev/null
+++ b/saleor/payment/migrations/tasks/saleor3_19.py
@@ -0,0 +1,51 @@
+from django.db import transaction
+from django.db.models import Exists, OuterRef
+
+from ....celeryconf import app
+from ... import ChargeStatus
+from ...models import Payment
+
+# Batch size of size 3000 took about 0.2s and consume about 5MB memory usage
+PAYMENT_BATCH_SIZE = 3000
+
+
+def fix_invalid_atobarai_payments_task():
+ """Fix the invalid payemnts for atobarai gateway.
+
+ Some orders has inactive charged payments and active not charged payments.
+ The task will activate the charged payments and deactivate the not charged payments.
+ """
+ not_charged_active_payments = Payment.objects.filter(
+ is_active=True,
+ charge_status=ChargeStatus.NOT_CHARGED,
+ captured_amount=0,
+ gateway="saleor.payments.np-atobarai",
+ )
+ payments_to_activate_ids = list(
+ Payment.objects.filter(
+ Exists(not_charged_active_payments.filter(order_id=OuterRef("order_id"))),
+ is_active=False,
+ charge_status__in=[
+ ChargeStatus.FULLY_CHARGED,
+ ChargeStatus.PARTIALLY_CHARGED,
+ ],
+ captured_amount__gt=0,
+ gateway="saleor.payments.np-atobarai",
+ ).values_list("pk", flat=True)[:PAYMENT_BATCH_SIZE]
+ )
+ if payments_to_activate_ids:
+ payments_to_activate = Payment.objects.filter(pk__in=payments_to_activate_ids)
+
+ related_order_ids = payments_to_activate.values("order_id")
+ payments_to_deactivate = Payment.objects.filter(
+ order_id__in=related_order_ids, is_active=True
+ ).exclude(pk__in=payments_to_activate_ids)
+
+ with transaction.atomic():
+ qs = payments_to_deactivate | payments_to_activate
+ _payments = list(qs.select_for_update(of=(["self"])))
+ payments_to_deactivate.update(is_active=False)
+ payments_to_activate.update(is_active=True)
+
+ fix_invalid_atobarai_payments_task.delay()
diff --git a/saleor/settings.py b/saleor/settings.py
index 70ec6d5cc2..bf2dd8bd48 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -914,6 +914,11 @@ OAUTH_UPDATE_LAST_LOGIN_THRESHOLD = parse(
os.environ.get("OAUTH_UPDATE_LAST_LOGIN_THRESHOLD", "15 minutes")
)
+# Max lock time for checkout processing.
+# It prevents locking checkout when unhandled issue appears.
+CHECKOUT_COMPLETION_LOCK_TIME = parse(
+ os.environ.get("CHECKOUT_COMPLETION_LOCK_TIME", "3 minutes")
+)
# Default timeout (sec) for establishing a connection when performing external requests.
REQUESTS_CONN_EST_TIMEOUT = 2