Skip to content

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

Fix race condition in TransactionInitialize mutation (#17962)

Filip Owczarek2765e105611f
diff --git a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
index cca3733b56..56cc5877dd 100644
--- a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
+++ b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
@@ -10,7 +10,7 @@ from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_order_lines(
mocked_refund,
staff_api_client,
@@ -71,7 +71,7 @@ def test_fulfillment_refund_products_order_lines(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_order_lines(
mocked_refund,
back_in_stock_webhook_mock,
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
index e18c0a506e..9fc391c323 100644
--- a/saleor/graphql/order/tests/deprecated/test_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -319,7 +319,7 @@ mutation OrderFulfillmentRefundProducts(
"""
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_order_lines_by_old_id(
mocked_refund,
staff_api_client,
@@ -428,7 +428,7 @@ mutation OrderFulfillmentReturnProducts(
"""
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_order_lines_by_old_line_id(
mocked_refund,
staff_api_client,
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
index c99d1a6b40..937f31988e 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
@@ -79,7 +79,7 @@ def test_fulfillment_refund_products_by_user_no_channel_access(
assert_no_permission(response)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_with_action_requested_by_app(
mocked_refund,
app_api_client,
@@ -126,7 +126,7 @@ def test_fulfillment_refund_products_with_action_requested_by_app(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
def test_fulfillment_refund_products_with_back_in_stock_webhook(
back_in_stock_webhook_trigger,
@@ -217,7 +217,7 @@ def test_fulfillment_refund_products_order_without_payment(
assert fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_amount_and_shipping_costs(
mocked_refund,
staff_api_client,
@@ -286,7 +286,7 @@ def test_fulfillment_refund_products_amount_costs_for_order_with_gift_card_lines
assert errors[0]["field"] == "amountToRefund"
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_refund_raising_payment_error(
mocked_refund,
staff_api_client,
@@ -320,7 +320,7 @@ def test_fulfillment_refund_products_refund_raising_payment_error(
assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_order_lines(
mocked_refund,
staff_api_client,
@@ -427,7 +427,7 @@ def test_fulfillment_refund_products_order_lines_quantity_bigger_than_unfulfille
assert refund_fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_fulfillment_lines(
mocked_refund,
staff_api_client,
@@ -484,7 +484,7 @@ def test_fulfillment_refund_products_fulfillment_lines(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_waiting_fulfillment_lines(
mocked_refund,
staff_api_client,
@@ -657,7 +657,7 @@ def test_fulfillment_refund_products_amount_bigger_than_captured_amount(
assert refund_fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(
mocked_refund,
staff_api_client,
@@ -715,7 +715,7 @@ def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_order_lines_include_shipping_costs(
mocked_refund,
staff_api_client,
@@ -767,7 +767,7 @@ def test_fulfillment_refund_products_order_lines_include_shipping_costs(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
mocked_refund,
staff_api_client,
@@ -827,7 +827,7 @@ def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_order_lines_custom_amount(
mocked_refund,
staff_api_client,
@@ -878,7 +878,7 @@ def test_fulfillment_refund_products_order_lines_custom_amount(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
mocked_refund,
warehouse,
@@ -984,7 +984,7 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
@patch("saleor.order.actions.order_refunded")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_refund_products_calls_order_refunded(
mocked_refund,
mocked_order_refunded,
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
index 87f06cd9bf..4d3f32cf5a 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
@@ -103,7 +103,7 @@ def test_fulfillment_return_products_by_user_no_channel_access(
assert_no_permission(response)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_by_app(
mocked_refund,
app_api_client,
@@ -173,7 +173,7 @@ def test_fulfillment_return_products_order_without_payment(
assert fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_amount_and_shipping_costs(
mocked_refund,
staff_api_client,
@@ -252,7 +252,7 @@ def test_fulfillment_return_products_amount_order_with_gift_card(
assert fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_refund_raising_payment_error(
mocked_refund,
staff_api_client,
@@ -286,7 +286,7 @@ def test_fulfillment_return_products_refund_raising_payment_error(
assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_order_lines(
mocked_refund,
staff_api_client,
@@ -520,7 +520,7 @@ def test_fulfillment_return_products_order_lines_quantity_bigger_than_unfulfille
assert return_fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_order_lines_custom_amount(
mocked_refund,
staff_api_client,
@@ -576,7 +576,7 @@ def test_fulfillment_return_products_order_lines_custom_amount(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_fulfillment_lines(
mocked_refund,
staff_api_client,
@@ -710,7 +710,7 @@ def test_fulfillment_return_products_fulfillment_lines(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_gift_card_fulfillment_line(
mocked_refund,
staff_api_client,
@@ -877,7 +877,7 @@ def test_fulfillment_return_products_lines_with_incorrect_status(
assert return_fulfillment is None
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_fulfillment_lines_include_shipping_costs(
mocked_refund,
staff_api_client,
@@ -938,7 +938,7 @@ def test_fulfillment_return_products_fulfillment_lines_include_shipping_costs(
)
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
mocked_refund,
warehouse,
@@ -1061,7 +1061,7 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.order.actions.order_refunded")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_and_replace_products_calls_order_refunded_and_webhooks(
mocked_refund,
mocked_order_refunded,
@@ -1151,7 +1151,7 @@ def test_fulfillment_return_and_replace_products_calls_order_refunded_and_webhoo
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.order.actions.order_refunded")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_fulfillment_return_products_calls_order_refunded_and_webhooks(
mocked_refund,
mocked_order_refunded,
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index 6f431cf499..a9e0d689f2 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -18,6 +18,7 @@ from .....payment.interface import PaymentMethodDetails
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
from .....payment.utils import (
create_manual_adjustment_events,
+ process_order_or_checkout_with_transaction,
truncate_transaction_event_message,
update_transaction_item_with_payment_method_details,
)
@@ -40,7 +41,6 @@ from .shared import (
get_payment_method_details,
validate_payment_method_details_input,
)
-from .utils import process_order_or_checkout_with_transaction
if TYPE_CHECKING:
pass
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 475d4bc73d..a7c864cfb1 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -25,6 +25,7 @@ from .....payment.utils import (
create_failed_transaction_event,
get_already_existing_event,
get_transaction_event_amount,
+ process_order_or_checkout_with_transaction,
truncate_transaction_event_message,
update_transaction_item_with_payment_method_details,
)
@@ -52,7 +53,7 @@ from .shared import (
get_payment_method_details,
validate_payment_method_details_input,
)
-from .utils import get_transaction_item, process_order_or_checkout_with_transaction
+from .utils import get_transaction_item
if TYPE_CHECKING:
from .....plugins.manager import PluginsManager
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_update.py b/saleor/graphql/payment/mutations/transaction/transaction_update.py
index fc99ddb106..1c06e15c35 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_update.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_update.py
@@ -18,6 +18,7 @@ from .....payment.transaction_item_calculations import (
)
from .....payment.utils import (
create_manual_adjustment_events,
+ process_order_or_checkout_with_transaction,
update_transaction_item_with_payment_method_details,
)
from .....permission.auth_filters import AuthorizationFilters
@@ -37,7 +38,7 @@ from .transaction_create import (
TransactionCreateInput,
TransactionEventInput,
)
-from .utils import get_transaction_item, process_order_or_checkout_with_transaction
+from .utils import get_transaction_item
if TYPE_CHECKING:
from .....account.models import User
@@ -254,8 +255,6 @@ class TransactionUpdate(TransactionCreate):
message=transaction_event.get("message", ""),
)
- # TransactionCreate.process_order_or_checkout_with_transaction is called to use same logic for processing
- # order or checkout as in a transaction mutation.
process_order_or_checkout_with_transaction(
instance,
manager,
diff --git a/saleor/graphql/payment/mutations/transaction/utils.py b/saleor/graphql/payment/mutations/transaction/utils.py
index 10184834ff..5fae2a209e 100644
--- a/saleor/graphql/payment/mutations/transaction/utils.py
+++ b/saleor/graphql/payment/mutations/transaction/utils.py
@@ -1,42 +1,15 @@
-from decimal import Decimal
-from typing import TYPE_CHECKING, cast
-from uuid import UUID
-
from django.core.exceptions import ValidationError
from django.core.validators import validate_ipv46_address
-from .....account.models import User
-from .....app.models import App
-from .....checkout.actions import (
- transaction_amounts_for_checkout_updated_without_price_recalculation,
-)
from .....core.exceptions import PermissionDenied
-from .....core.tracing import traced_atomic_transaction
from .....core.utils import get_client_ip
-from .....order import OrderStatus
-from .....order import models as order_models
-from .....order.actions import order_transaction_updated
-from .....order.fetch import fetch_order_info
-from .....order.search import update_order_search_vector
-from .....order.utils import (
- calculate_order_granted_refund_status,
- refresh_order_status,
- updates_amounts_for_order,
-)
from .....payment import models as payment_models
from .....payment.error_codes import TransactionUpdateErrorCode
-from .....payment.lock_objects import (
- get_checkout_and_transaction_item_locked_for_update,
- get_order_and_transaction_item_locked_for_update,
-)
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core.utils import from_global_id_or_error
from ...types import TransactionItem
-if TYPE_CHECKING:
- from .....plugins.manager import PluginsManager
-
def get_transaction_item(
id, token, error_field_name="id", qs=None
@@ -100,97 +73,3 @@ def clean_customer_ip_address(info, customer_ip_address: str | None, error_code:
}
) from e
return customer_ip_address
-
-
-def process_order_with_transaction(
- transaction: payment_models.TransactionItem,
- manager: "PluginsManager",
- user: User | None,
- app: App | None,
- previous_authorized_value: Decimal = Decimal(0),
- previous_charged_value: Decimal = Decimal(0),
- previous_refunded_value: Decimal = Decimal(0),
- related_granted_refund: order_models.OrderGrantedRefund | None = None,
-):
- order = None
- # This is executed after we ensure that the transaction is not a checkout
- # transaction, so we can safely cast the order_id to UUID.
- order_id = cast(UUID, transaction.order_id)
- with traced_atomic_transaction():
- order, transaction = get_order_and_transaction_item_locked_for_update(
- order_id, transaction.pk
- )
- update_fields = []
- updates_amounts_for_order(order, save=False)
- update_fields.extend(
- [
- "total_charged_amount",
- "charge_status",
- "total_authorized_amount",
- "authorize_status",
- ]
- )
- if (
- order.channel.automatically_confirm_all_new_orders
- and order.status == OrderStatus.UNCONFIRMED
- ):
- status_updated = refresh_order_status(order)
- if status_updated:
- update_fields.append("status")
- if update_fields:
- update_fields.append("updated_at")
- order.save(update_fields=update_fields)
-
- update_order_search_vector(order)
- order_info = fetch_order_info(order)
- order_transaction_updated(
- order_info=order_info,
- transaction_item=transaction,
- manager=manager,
- user=user,
- app=app,
- previous_authorized_value=previous_authorized_value,
- previous_charged_value=previous_charged_value,
- previous_refunded_value=previous_refunded_value,
- )
- if related_granted_refund:
- calculate_order_granted_refund_status(related_granted_refund)
-
-
-def process_order_or_checkout_with_transaction(
- transaction: payment_models.TransactionItem,
- manager: "PluginsManager",
- user: User | None,
- app: App | None,
- previous_authorized_value: Decimal = Decimal(0),
- previous_charged_value: Decimal = Decimal(0),
- previous_refunded_value: Decimal = Decimal(0),
- related_granted_refund: order_models.OrderGrantedRefund | None = None,
-):
- checkout_deleted = False
- if transaction.checkout_id:
- with traced_atomic_transaction():
- locked_checkout, transaction = (
- get_checkout_and_transaction_item_locked_for_update(
- transaction.checkout_id, transaction.pk
- )
- )
- if transaction.checkout_id and locked_checkout:
- transaction_amounts_for_checkout_updated_without_price_recalculation(
- transaction, locked_checkout, manager, user, app
- )
- else:
- checkout_deleted = True
- # If the checkout was deleted, we still want to update the order associated with the transaction.
-
- if transaction.order_id or checkout_deleted:
- process_order_with_transaction(
- transaction,
- manager,
- user,
- app,
- previous_authorized_value,
- previous_charged_value,
- previous_refunded_value,
- related_granted_refund=related_granted_refund,
- )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index d23d9aba80..2e6de6d11f 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -2796,7 +2796,7 @@ def test_transaction_create_with_invalid_other_payment_method_details(
# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
@pytest.mark.django_db(transaction=True)
@patch(
- "saleor.graphql.payment.mutations.transaction.utils.get_order_and_transaction_item_locked_for_update",
+ "saleor.payment.utils.get_order_and_transaction_item_locked_for_update",
wraps=get_order_and_transaction_item_locked_for_update,
)
def test_lock_order_during_updating_order_amounts(
@@ -2842,7 +2842,7 @@ def test_lock_order_during_updating_order_amounts(
# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
@pytest.mark.django_db(transaction=True)
@patch(
- "saleor.graphql.payment.mutations.transaction.utils.get_checkout_and_transaction_item_locked_for_update",
+ "saleor.payment.utils.get_checkout_and_transaction_item_locked_for_update",
wraps=get_checkout_and_transaction_item_locked_for_update,
)
def test_lock_checkout_during_updating_checkout_amounts(
@@ -2898,7 +2898,7 @@ def test_lock_checkout_during_updating_checkout_amounts(
)
-def test_transaction_create_create_checkout_completed_race_condition(
+def test_transaction_create_checkout_completed_race_condition(
app_api_client,
permission_manage_payments,
checkout_with_prices,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 816884e165..3b52700006 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -3341,7 +3341,7 @@ def test_transaction_event_report_empty_message(
@patch(
- "saleor.graphql.payment.mutations.transaction.utils.get_order_and_transaction_item_locked_for_update",
+ "saleor.payment.utils.get_order_and_transaction_item_locked_for_update",
wraps=get_order_and_transaction_item_locked_for_update,
)
def test_lock_order_during_updating_order_amounts(
@@ -3405,7 +3405,7 @@ def test_lock_order_during_updating_order_amounts(
@patch(
- "saleor.graphql.payment.mutations.transaction.utils.get_checkout_and_transaction_item_locked_for_update",
+ "saleor.payment.utils.get_checkout_and_transaction_item_locked_for_update",
wraps=get_checkout_and_transaction_item_locked_for_update,
)
def test_lock_checkout_during_updating_checkout_amounts(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 8626bc76d1..d1371076a3 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -11,10 +11,11 @@ from freezegun import freeze_time
from .....channel import TransactionFlowStrategy
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
+from .....checkout.complete_checkout import create_order_from_checkout
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....core.prices import quantize_price
-from .....order import OrderChargeStatus, OrderEvents, OrderStatus
+from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
from .....order.models import Order
from .....payment import TransactionEventType, TransactionItemIdempotencyUniqueError
from .....payment.interface import (
@@ -23,7 +24,12 @@ from .....payment.interface import (
TransactionSessionData,
TransactionSessionResult,
)
+from .....payment.lock_objects import (
+ get_checkout_and_transaction_item_locked_for_update,
+ get_order_and_transaction_item_locked_for_update,
+)
from .....payment.models import Payment, TransactionItem
+from .....tests import race_condition
from .....webhook.event_types import WebhookEventSyncType
from ....channel.enums import TransactionFlowStrategyEnum
from ....core.enums import TransactionInitializeErrorCode
@@ -2964,3 +2970,189 @@ def test_for_order_with_tax_app(
for call in mocked_send_webhook_request_sync.mock_calls:
delivery = call.args[0]
assert delivery.payload.get_payload()
+
+
+# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
[email protected]_db(transaction=True)
+ "saleor.payment.utils.get_order_and_transaction_item_locked_for_update",
+ wraps=get_order_and_transaction_item_locked_for_update,
+)
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_lock_order_during_updating_order_amounts(
+ mocked_initialize,
+ mocked_get_order_and_transaction_item_locked_for_update,
+ user_api_client,
+ unconfirmed_order_with_lines,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ order = unconfirmed_order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["amount"] = str(order.total_gross_amount)
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "amount": order.total_gross_amount,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=order.total_gross_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=order.total_gross_amount,
+ returned_data=expected_response["data"],
+ )
+
+ assert not order.is_fully_paid()
+ order.refresh_from_db()
+ assert order.is_fully_paid()
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == order.total_gross_amount
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+ transaction_pk = order.payment_transactions.get().pk
+ mocked_get_order_and_transaction_item_locked_for_update.assert_called_once_with(
+ order.pk, transaction_pk
+ )
+
+
+# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
[email protected]_db(transaction=True)
+ "saleor.payment.utils.get_checkout_and_transaction_item_locked_for_update",
+ wraps=get_checkout_and_transaction_item_locked_for_update,
+)
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_lock_checkout_during_updating_checkout_amounts(
+ mocked_initialize,
+ mocked_get_checkout_and_transaction_item_locked_for_update,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=checkout.total_gross_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=checkout.total_gross_amount,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ transaction_pk = checkout.payment_transactions.get().pk
+ mocked_get_checkout_and_transaction_item_locked_for_update.assert_called_once_with(
+ checkout.pk, transaction_pk
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_transaction_initialize_checkout_completed_race_condition(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ def complete_checkout(*args, **kwargs):
+ create_order_from_checkout(
+ checkout_info, plugins_manager, user=user_api_client.user, app=None
+ )
+
+ with race_condition.RunBefore(
+ "saleor.payment.utils.recalculate_transaction_amounts",
+ complete_checkout,
+ ):
+ user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ order = Order.objects.get(checkout_token=checkout.pk)
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+ assert order.total_charged.amount == checkout.total.gross.amount
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 8a9d09fc4f..dd8e393602 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -3760,7 +3760,7 @@ def test_transaction_update_with_invalid_other_payment_method_details(
# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
@pytest.mark.django_db(transaction=True)
@patch(
- "saleor.graphql.payment.mutations.transaction.utils.get_order_and_transaction_item_locked_for_update",
+ "saleor.payment.utils.get_order_and_transaction_item_locked_for_update",
wraps=get_order_and_transaction_item_locked_for_update,
)
def test_lock_order_during_updating_order_amounts(
@@ -3810,7 +3810,7 @@ def test_lock_order_during_updating_order_amounts(
# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
@pytest.mark.django_db(transaction=True)
@patch(
- "saleor.graphql.payment.mutations.transaction.utils.get_checkout_and_transaction_item_locked_for_update",
+ "saleor.payment.utils.get_checkout_and_transaction_item_locked_for_update",
wraps=get_checkout_and_transaction_item_locked_for_update,
)
def test_lock_checkout_during_updating_checkout_amounts(
@@ -3864,7 +3864,7 @@ def test_lock_checkout_during_updating_checkout_amounts(
)
-def test_transaction_create_create_checkout_completed_race_condition(
+def test_transaction_update_checkout_completed_race_condition(
app_api_client,
permission_manage_payments,
checkout_with_prices,
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index b8935fde43..13cd327380 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -29,11 +29,9 @@ from ..payment import (
PaymentError,
TransactionAction,
TransactionKind,
- gateway,
)
from ..payment.interface import RefundData
from ..payment.models import Payment, Transaction, TransactionItem
-from ..payment.utils import create_payment, create_transaction_for_order
from ..plugins.manager import PluginsManager
from ..shipping.models import ShippingMethodChannelListing
from ..warehouse.management import (
@@ -937,6 +935,9 @@ def mark_order_as_paid_with_transaction(
Allows to create a transaction for an order.
"""
with transaction.atomic():
+ # Circular imports
+ from ..payment.utils import create_transaction_for_order
+
create_transaction_for_order(
order=order,
user=request_user,
@@ -978,6 +979,9 @@ def mark_order_as_paid_with_payment(
# transaction ensures that webhooks are triggered when payments and transactions are
# properly created
with traced_atomic_transaction():
+ # Circular imports
+ from ..payment.utils import create_payment
+
payment = create_payment(
gateway=CustomPaymentChoices.MANUAL,
payment_token="",
@@ -2039,7 +2043,10 @@ def _process_refund(
amount += order.shipping_price_gross_amount
if amount and payment:
amount = min(payment.captured_amount, amount)
- gateway.refund(
+ # Circular imports
+ from ..payment.gateway import refund
+
+ refund(
payment,
manager,
amount=amount,
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
index 4bd419bb20..e572f3c835 100644
--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -14,7 +14,7 @@ from ..models import Fulfillment, FulfillmentLine
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_order_lines(
mocked_refund,
mocked_order_updated,
@@ -92,7 +92,7 @@ def test_create_return_fulfillment_only_order_lines(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_order_lines_with_refund(
mocked_refund,
mocked_order_updated,
@@ -172,7 +172,7 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
mocked_refund,
mocked_order_updated,
@@ -258,7 +258,7 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_order_lines_with_replace_request(
mocked_refund,
mocked_order_updated,
@@ -393,7 +393,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_fulfillment_lines(
mocked_refund,
mocked_order_updated,
@@ -444,7 +444,7 @@ def test_create_return_fulfillment_only_fulfillment_lines(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_fulfillment_lines_replace_order(
mocked_refund,
mocked_order_updated,
@@ -555,7 +555,7 @@ def test_create_return_fulfillment_only_fulfillment_lines_replace_order(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_with_lines_already_refunded(
mocked_refund,
mocked_order_updated,
@@ -668,7 +668,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_return_fulfillment_only_order_lines_with_old_ids(
mocked_refund,
mocked_order_updated,
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
index 9314a49f3b..2b36291450 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -12,7 +12,7 @@ from ..models import FulfillmentLine
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_refund_fulfillment_only_order_lines(
mocked_refund,
mocked_order_updated,
@@ -86,7 +86,7 @@ def test_create_refund_fulfillment_only_order_lines(
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_refund_fulfillment_included_shipping_costs(
mocked_refund,
mocked_order_updated,
@@ -152,7 +152,7 @@ def test_create_refund_fulfillment_included_shipping_costs(
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_refund_fulfillment_only_fulfillment_lines(
mocked_refund,
mocked_order_updated,
@@ -213,7 +213,7 @@ def test_create_refund_fulfillment_only_fulfillment_lines(
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
def test_create_refund_fulfillment_custom_amount(
mocked_refund,
mocked_order_updated,
diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.py
index 5578a32fad..6caf126f51 100644
--- a/saleor/payment/gateways/np_atobarai/tests/conftest.py
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -157,7 +157,7 @@ def create_refund(payment_dummy):
payment.captured_amount -= amount
payment.save(update_fields=["captured_amount"])
- with patch("saleor.order.actions.gateway.refund", side_effect=mocked_refund):
+ with patch("saleor.payment.gateway.refund", side_effect=mocked_refund):
return create_refund_fulfillment(
user=None,
app=None,
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_utils.py b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
index ecf9616704..3f1d49f5f0 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_utils.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
@@ -201,7 +201,7 @@ def test_create_refunded_lines_fulfillment_lines(fulfilled_order):
}
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
@pytest.mark.parametrize("previous_refund_shipping_costs", [True, False])
def test_create_refunded_lines_previously_refunded_order_lines(
_mocked_refund,
@@ -247,7 +247,7 @@ def test_create_refunded_lines_previously_refunded_order_lines(
assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}
-@patch("saleor.order.actions.gateway.refund")
+@patch("saleor.payment.gateway.refund")
@pytest.mark.parametrize("previous_refund_shipping_costs", [True, False])
def test_create_refunded_lines_previously_refunded_fulfillment_lines(
_mocked_refund,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 30bca3dad9..9b8e3ee42c 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -2,6 +2,7 @@ import json
import logging
from decimal import Decimal
from typing import Any, Optional, cast, get_args, overload
+from uuid import UUID
import graphene
from babel.numbers import get_currency_precision
@@ -19,6 +20,7 @@ from ..channel import TransactionFlowStrategy
from ..checkout import calculations
from ..checkout.actions import (
transaction_amounts_for_checkout_updated,
+ transaction_amounts_for_checkout_updated_without_price_recalculation,
update_last_transaction_modified_at_for_checkout,
)
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -28,11 +30,14 @@ from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..graphql.core.utils import str_to_enum
+from ..order import OrderStatus
+from ..order.actions import order_transaction_updated
from ..order.fetch import fetch_order_info
from ..order.models import Order, OrderGrantedRefund
from ..order.search import update_order_search_vector
from ..order.utils import (
calculate_order_granted_refund_status,
+ refresh_order_status,
update_order_authorize_data,
updates_amounts_for_order,
)
@@ -68,6 +73,10 @@ from .interface import (
TransactionSessionData,
TransactionSessionResponse,
)
+from .lock_objects import (
+ get_checkout_and_transaction_item_locked_for_update,
+ get_order_and_transaction_item_locked_for_update,
+)
from .models import Payment, Transaction, TransactionEvent, TransactionItem
from .transaction_item_calculations import recalculate_transaction_amounts
@@ -1305,6 +1314,100 @@ def update_transaction_item_with_payment_method_details(
return updated_fields
+def process_order_with_transaction(
+ transaction: TransactionItem,
+ manager: "PluginsManager",
+ user: Optional["User"],
+ app: Optional["App"],
+ previous_authorized_value: Decimal = Decimal(0),
+ previous_charged_value: Decimal = Decimal(0),
+ previous_refunded_value: Decimal = Decimal(0),
+ related_granted_refund: OrderGrantedRefund | None = None,
+):
+ order = None
+ # This is executed after we ensure that the transaction is not a checkout
+ # transaction, so we can safely cast the order_id to UUID.
+ order_id = cast(UUID, transaction.order_id)
+ with traced_atomic_transaction():
+ order, transaction = get_order_and_transaction_item_locked_for_update(
+ order_id, transaction.pk
+ )
+ update_fields = []
+ updates_amounts_for_order(order, save=False)
+ update_fields.extend(
+ [
+ "total_charged_amount",
+ "charge_status",
+ "total_authorized_amount",
+ "authorize_status",
+ ]
+ )
+ if (
+ order.channel.automatically_confirm_all_new_orders
+ and order.status == OrderStatus.UNCONFIRMED
+ ):
+ status_updated = refresh_order_status(order)
+ if status_updated:
+ update_fields.append("status")
+ if update_fields:
+ update_fields.append("updated_at")
+ order.save(update_fields=update_fields)
+
+ update_order_search_vector(order)
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction,
+ manager=manager,
+ user=user,
+ app=app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
+ )
+ if related_granted_refund:
+ calculate_order_granted_refund_status(related_granted_refund)
+
+
+def process_order_or_checkout_with_transaction(
+ transaction: TransactionItem,
+ manager: "PluginsManager",
+ user: Optional["User"],
+ app: Optional["App"],
+ previous_authorized_value: Decimal = Decimal(0),
+ previous_charged_value: Decimal = Decimal(0),
+ previous_refunded_value: Decimal = Decimal(0),
+ related_granted_refund: OrderGrantedRefund | None = None,
+):
+ checkout_deleted = False
+ if transaction.checkout_id:
+ with traced_atomic_transaction():
+ locked_checkout, transaction = (
+ get_checkout_and_transaction_item_locked_for_update(
+ transaction.checkout_id, transaction.pk
+ )
+ )
+ if transaction.checkout_id and locked_checkout:
+ transaction_amounts_for_checkout_updated_without_price_recalculation(
+ transaction, locked_checkout, manager, user, app
+ )
+ else:
+ checkout_deleted = True
+ # If the checkout was deleted, we still want to update the order associated with the transaction.
+
+ if transaction.order_id or checkout_deleted:
+ process_order_with_transaction(
+ transaction,
+ manager,
+ user,
+ app,
+ previous_authorized_value,
+ previous_charged_value,
+ previous_refunded_value,
+ related_granted_refund=related_granted_refund,
+ )
+
+
def create_transaction_event_for_transaction_session(
request_event: TransactionEvent,
app: App,
@@ -1407,27 +1510,17 @@ def create_transaction_event_for_transaction_session(
]
+ transaction_item_updated_fields
)
- if transaction_item.order_id:
- # circular import
- from ..order.actions import order_transaction_updated
-
- update_order_with_transaction_details(transaction_item)
- order = cast(Order, transaction_item.order)
- order_info = fetch_order_info(order)
- order_transaction_updated(
- order_info=order_info,
- transaction_item=transaction_item,
- manager=manager,
- user=None,
- app=app,
- previous_authorized_value=previous_authorized_value,
- previous_charged_value=previous_charged_value,
- previous_refunded_value=previous_refunded_value,
- )
- elif transaction_item.checkout_id:
- transaction_amounts_for_checkout_updated(
- transaction_item, manager, app=app, user=None
- )
+
+ process_order_or_checkout_with_transaction(
+ transaction_item,
+ manager,
+ None,
+ app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
+ )
+
elif event.psp_reference and transaction_item.psp_reference != event.psp_reference:
transaction_item.psp_reference = event.psp_reference
transaction_item.save(