Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Prevent performing both transaction and payment checkout process at the same tim (#16073)
Iga Karbowiak0770d15fbf7b
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 5fe7a3b07a..c619508ea0 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -1450,6 +1450,7 @@ def complete_checkout(metadata_list: Optional[list] = None,private_metadata_list: Optional[list] = None,) -> tuple[Optional[Order], bool, dict]:+ checkout = checkout_info.checkouttransactions = checkout_info.checkout.payment_transactions.all()force_update = checkout_info.checkout.tax_error is not None@@ -1465,20 +1466,26 @@ def complete_checkout(code=CheckoutErrorCode.TAX_ERROR.value,)- # When checkout is zero, we don't need any transaction to cover the checkout total.- # We check if checkout is zero, and we also check what flow for marking an order as- # paid is used. In case when we have TRANSACTION_FLOW we use transaction flow to- # finalize the checkout.+ active_payment = checkout.get_last_active_payment()+ is_checkout_fully_authorized = (+ checkout.authorize_status == CheckoutAuthorizeStatus.FULL+ )checkout_is_zero = checkout_info.checkout.total.gross.amount == Decimal(0)is_transaction_flow = (checkout_info.channel.order_mark_as_paid_strategy== MarkAsPaidStrategy.TRANSACTION_FLOW)+ # When checkout is zero, we don't need any transaction to cover the checkout total.+ # We check if checkout is zero, and we also check what flow for marking an order as+ # paid is used. In case when we have TRANSACTION_FLOW we use transaction flow to+ # finalize the checkout.+ # When checkout is not fully authorized and contains active payment, we use the+ # payment flow to finalize the checkout.if (- transactions+ is_checkout_fully_authorized+ or (transactions and not active_payment)or checkout_info.channel.allow_unpaid_orders- or checkout_is_zero- and is_transaction_flow+ or (checkout_is_zero and is_transaction_flow)):order = complete_checkout_with_transaction(manager=manager,diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 9537c2c358..ff7b80a3c3 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -12,6 +12,7 @@ from prices import TaxedMoneyfrom ...account import CustomerEventsfrom ...account.models import CustomerEventfrom ...channel import MarkAsPaidStrategy+from ...checkout import CheckoutAuthorizeStatusfrom ...core.exceptions import InsufficientStockfrom ...core.notify_events import NotifyEventTypefrom ...core.taxes import zero_money, zero_taxed_money@@ -118,7 +119,7 @@ def test_create_order_captured_payment_creates_expected_events(assert payment_captured_event.order is order# ensure a date was setassert payment_captured_event.date- # should not have any additional parameters+ # should have additional parametersassert "amount" in payment_captured_event.parameters.keys()assert "payment_id" in payment_captured_event.parameters.keys()assert "payment_gateway" in payment_captured_event.parameters.keys()@@ -132,8 +133,8 @@ def test_create_order_captured_payment_creates_expected_events(assert order_fully_paid_event.order is order# ensure a date was setassert order_fully_paid_event.date- # should not have any additional parameters- assert not order_fully_paid_event.parameters+ # should have payment_gateway in additional parameters+ assert "payment_gateway" in order_fully_paid_event.parametersexpected_order_payload = {"order": get_default_order_payload(order, checkout.redirect_url),@@ -266,7 +267,7 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(assert payment_captured_event.order is order# ensure a date was setassert payment_captured_event.date- # should not have any additional parameters+ # should have additional parametersassert "amount" in payment_captured_event.parameters.keys()assert "payment_id" in payment_captured_event.parameters.keys()assert "payment_gateway" in payment_captured_event.parameters.keys()@@ -280,8 +281,8 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(assert order_fully_paid_event.order is order# ensure a date was setassert order_fully_paid_event.date- # should not have any additional parameters- assert not order_fully_paid_event.parameters+ # should have payment_gateway in additional parameters+ assert "payment_gateway" in order_fully_paid_event.parametersexpected_order_payload = {"order": get_default_order_payload(order, checkout.redirect_url),@@ -2145,6 +2146,65 @@ def test_checkout_complete_pick_transaction_flow_when_checkout_total_zero()[email protected]("saleor.checkout.complete_checkout.complete_checkout_with_transaction")+def test_checkout_complete_pick_transaction_flow_not_authorized_no_active_payment(+ mocked_flow,+ order,+ checkout_ready_to_complete,+ customer_user,+ transaction_item_generator,+ payment,+):+ # given+ checkout = checkout_ready_to_complete+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.tracking_code = ""+ checkout.redirect_url = "https://www.example.com"++ # checkout is not fully authorized+ checkout.authorize_status = CheckoutAuthorizeStatus.PARTIAL++ # transaction item exists+ transaction_item_generator(checkout_id=checkout.pk)+ assert checkout.payment_transactions.exists()++ # there is no active payments+ payment.checkout = checkout+ payment.is_active = False+ payment.save(update_fields=["checkout", "is_active"])++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ transaction_item_generator(checkout_id=checkout.pk)+ mocked_flow.return_value = order, False, {}++ # when+ order, action_required, _ = complete_checkout(+ checkout_info=checkout_info,+ manager=manager,+ lines=lines,+ payment_data={},+ store_source=False,+ user=customer_user,+ app=None,+ )++ # then+ mocked_flow.assert_called_once_with(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ user=customer_user,+ app=None,+ redirect_url=None,+ metadata_list=None,+ private_metadata_list=None,+ )++@mock.patch("saleor.checkout.complete_checkout.complete_checkout_with_payment")def test_checkout_complete_pick_payment_flow(mocked_flow, order, checkout_ready_to_complete, customer_user@@ -2195,6 +2255,66 @@ def test_checkout_complete_pick_payment_flow()[email protected]("saleor.checkout.complete_checkout.complete_checkout_with_payment")+def test_checkout_complete_pick_payment_flow_not_authorized_active_payment(+ mocked_flow,+ order,+ checkout_ready_to_complete,+ customer_user,+ transaction_item_generator,+ payment,+):+ # given+ checkout = checkout_ready_to_complete+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.tracking_code = ""+ checkout.redirect_url = "https://www.example.com"++ # checkout is not fully authorized+ checkout.authorize_status = CheckoutAuthorizeStatus.PARTIAL++ # transaction item exists+ transaction_item_generator(checkout_id=checkout.pk)+ assert checkout.payment_transactions.exists()++ # there is no active payments+ payment.checkout = checkout+ payment.save(update_fields=["checkout"])++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ transaction_item_generator(checkout_id=checkout.pk)+ mocked_flow.return_value = order, False, {}++ # when+ order, action_required, _ = complete_checkout(+ checkout_info=checkout_info,+ manager=manager,+ lines=lines,+ payment_data={},+ store_source=False,+ user=customer_user,+ app=None,+ )++ # then+ mocked_flow.assert_called_once_with(+ manager=manager,+ checkout_pk=checkout.pk,+ payment_data={},+ store_source=False,+ user=customer_user,+ app=None,+ site_settings=None,+ redirect_url=None,+ metadata_list=None,+ private_metadata_list=None,+ )++@mock.patch("saleor.checkout.calculations.get_tax_calculation_strategy_for_checkout")@mock.patch("saleor.checkout.complete_checkout._create_order")@mock.patch("saleor.checkout.complete_checkout._process_payment")diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 82c697ef1e..52fbd285bc 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -982,7 +982,7 @@ def is_fully_paid(return total_paid >= checkout_total.amount-def cancel_active_payments(checkout: Checkout):+def cancel_active_payments(checkout: Checkout) -> None:checkout.payments.filter(is_active=True).update(is_active=False)diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.pyindex 269cbd4718..f0480ffe62 100644--- a/saleor/graphql/order/mutations/order_confirm.py+++ b/saleor/graphql/order/mutations/order_confirm.py@@ -87,6 +87,7 @@ class OrderConfirm(ModelMutation):authorized_payment,manager,site.settings,+ payment.gateway, # type: ignore))transaction.on_commit(diff --git a/saleor/graphql/order/tests/mutations/test_order_confirm.py b/saleor/graphql/order/tests/mutations/test_order_confirm.pyindex 166d575505..c67f81326f 100644--- a/saleor/graphql/order/tests/mutations/test_order_confirm.py+++ b/saleor/graphql/order/tests/mutations/test_order_confirm.py@@ -99,7 +99,12 @@ def test_order_confirm()order_info = fetch_order_info(order_unconfirmed)handle_fully_paid_order_mock.assert_called_once_with(- ANY, order_info, staff_api_client.user, None, site_settings+ ANY,+ order_info,+ staff_api_client.user,+ None,+ site_settings,+ payment_txn_preauth.gateway,)@@ -364,5 +369,10 @@ def test_order_confirm_by_app()order_info = fetch_order_info(order_unconfirmed)handle_fully_paid_order_mock.assert_called_once_with(- ANY, order_info, None, app_api_client.app, site_settings+ ANY,+ order_info,+ None,+ app_api_client.app,+ site_settings,+ payment_txn_preauth.gateway,)diff --git a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py b/saleor/graphql/payment/mutations/transaction/transaction_initialize.pyindex fce0e8285c..af38f84d4e 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py@@ -7,7 +7,10 @@ from django.core.exceptions import ValidationErrorfrom .....app.models import Appfrom .....channel.models import Channel+from .....checkout import models as checkout_models+from .....checkout.utils import cancel_active_paymentsfrom .....core.exceptions import PermissionDenied+from .....core.tracing import traced_atomic_transactionfrom .....payment import TransactionItemIdempotencyUniqueErrorfrom .....payment.interface import PaymentGatewayDatafrom .....payment.utils import handle_transaction_initialize_session@@ -165,6 +168,9 @@ class TransactionInitialize(TransactionSessionBase):TransactionInitializeErrorCode.NOT_FOUND.value,manager=manager,)+ if isinstance(source_object, checkout_models.Checkout):+ cls.validate_checkout(source_object)+idempotency_key = cls.clean_idempotency_key(idempotency_key)action = cls.clean_action(info, action, source_object.channel)customer_ip_address = clean_customer_ip_address(@@ -178,27 +184,50 @@ class TransactionInitialize(TransactionSessionBase):amount,)app = cls.clean_app_from_payment_gateway(payment_gateway_data)- try:- transaction, event, data = handle_transaction_initialize_session(- source_object=source_object,- payment_gateway_data=payment_gateway_data,- amount=amount,- action=action,- customer_ip_address=customer_ip_address,- app=app,- manager=manager,- idempotency_key=idempotency_key,+ with traced_atomic_transaction():+ if isinstance(source_object, checkout_models.Checkout):+ # Deactivate active payment objects to avoid processing checkout+ # with use of two different flows.+ cancel_active_payments(source_object)+ try:+ transaction, event, data = handle_transaction_initialize_session(+ source_object=source_object,+ payment_gateway_data=payment_gateway_data,+ amount=amount,+ action=action,+ customer_ip_address=customer_ip_address,+ app=app,+ manager=manager,+ idempotency_key=idempotency_key,+ )+ except TransactionItemIdempotencyUniqueError:+ raise ValidationError(+ {+ "idempotency_key": ValidationError(+ message=(+ "Different transaction with provided idempotency key "+ "already exists."+ ),+ code=TransactionInitializeErrorCode.UNIQUE.value,+ )+ }+ )+ return cls(transaction=transaction, transaction_event=event, data=data)++ @staticmethod+ def validate_checkout(checkout: checkout_models.Checkout) -> None:+ if checkout.is_checkout_locked():+ error_code = (+ TransactionInitializeErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.value)- except TransactionItemIdempotencyUniqueError:raise ValidationError({- "idempotency_key": ValidationError(- message=(- "Different transaction with provided idempotency key "- "already exists."- ),- code=TransactionInitializeErrorCode.UNIQUE.value,+ "id": ValidationError(+ "Transaction cannot be initialized - the checkout completion "+ "is currently in progress. Please wait until the process is "+ f"finished (max {settings.CHECKOUT_COMPLETION_LOCK_TIME} "+ "seconds).",+ code=error_code,)})- return cls(transaction=transaction, transaction_event=event, data=data)diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.pyindex d066365cf7..8300343973 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py@@ -1,6 +1,7 @@from typing import TYPE_CHECKING, Optional, Union, castimport graphene+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db.models import QuerySet@@ -8,6 +9,8 @@ from .....app.models import Appfrom .....channel import TransactionFlowStrategyfrom .....channel.models import Channelfrom .....checkout import models as checkout_models+from .....checkout.utils import cancel_active_payments+from .....core.tracing import traced_atomic_transactionfrom .....order import models as order_modelsfrom .....payment import TransactionEventTypefrom .....payment import models as payment_models@@ -196,6 +199,10 @@ class TransactionProcess(BaseMutation):)request_event = cls.get_request_event(events)source_object = cls.get_source_object(transaction_item)++ if isinstance(source_object, checkout_models.Checkout):+ cls.validate_checkout(source_object)+app = cls.clean_payment_app(transaction_item)app_identifier = app.identifieraction = cls.get_action(request_event, source_object.channel)@@ -206,18 +213,43 @@ class TransactionProcess(BaseMutation):)manager = get_plugin_manager_promise(info.context).get()- event, data = handle_transaction_process_session(- transaction_item=transaction_item,- source_object=source_object,- payment_gateway_data=PaymentGatewayData(- app_identifier=app_identifier, data=data- ),- app=app,- action=action,- customer_ip_address=customer_ip_address,- manager=manager,- request_event=request_event,- )++ with traced_atomic_transaction():+ if isinstance(source_object, checkout_models.Checkout):+ # Deactivate active payment objects to avoid processing checkout+ # with use of two different flows.+ cancel_active_payments(source_object)++ event, data = handle_transaction_process_session(+ transaction_item=transaction_item,+ source_object=source_object,+ payment_gateway_data=PaymentGatewayData(+ app_identifier=app_identifier, data=data+ ),+ app=app,+ action=action,+ customer_ip_address=customer_ip_address,+ manager=manager,+ request_event=request_event,+ )transaction_item.refresh_from_db()return cls(transaction=transaction_item, transaction_event=event, data=data)++ @staticmethod+ def validate_checkout(checkout: checkout_models.Checkout) -> None:+ if checkout.is_checkout_locked():+ error_code = (+ TransactionProcessErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.value+ )+ raise ValidationError(+ {+ "id": ValidationError(+ "Transaction cannot be processed - the checkout completion is "+ "currently in progress. Please wait until the process is "+ f"finished (max {settings.CHECKOUT_COMPLETION_LOCK_TIME} "+ "seconds).",+ code=error_code,+ )+ }+ )diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex 939bd038ab..e9bb13f1ff 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -20,7 +20,7 @@ from .....payment.interface import (TransactionSessionData,TransactionSessionResult,)-from .....payment.models import TransactionItem+from .....payment.models import Payment, TransactionItemfrom ....channel.enums import TransactionFlowStrategyEnumfrom ....core.enums import TransactionInitializeErrorCodefrom ....core.utils import to_global_id_or_none@@ -1997,3 +1997,122 @@ def test_updates_checkout_last_transaction_modified_at(assert (checkout.last_transaction_modified_at != previous_last_transaction_modified_at)++[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_for_locked_checkout(+ mocked_initialize,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+):+ # given+ checkout = checkout_with_prices+ checkout.completing_started_at = timezone.now()+ checkout.save(update_fields=["completing_started_at"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = "CHARGE_SUCCESS"+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ idempotency_key = "ABC"++ variables = {+ "action": None,+ "amount": expected_amount,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "idempotencyKey": idempotency_key,+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["transactionInitialize"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert (+ error["code"]+ == TransactionInitializeErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.name+ )+ assert error["field"] == "id"++[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_for_checkout_with_payments(+ mocked_initialize,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+):+ # given+ checkout = checkout_with_prices+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ # create payments+ payments = Payment.objects.bulk_create(+ [+ Payment(+ gateway="mirumee.payments.dummy", is_active=True, checkout=checkout+ ),+ Payment(+ gateway="mirumee.payments.dummy", is_active=False, checkout=checkout+ ),+ ]+ )++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = "CHARGE_SUCCESS"+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ idempotency_key = "ABC"++ variables = {+ "action": None,+ "amount": expected_amount,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {"id": expected_app_identifier, "data": None},+ "idempotencyKey": idempotency_key,+ }++ # 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=expected_amount,+ expected_psp_reference=expected_psp_reference,+ response_event_type=TransactionEventType.CHARGE_SUCCESS,+ app_identifier=webhook_app.identifier,+ mocked_initialize=mocked_initialize,+ charged_value=expected_amount,+ returned_data=expected_response["data"],+ )+ transaction = checkout.payment_transactions.last()+ assert transaction.idempotency_key == idempotency_key+ assert transaction.events.first().idempotency_key == idempotency_key+ for payment in payments:+ payment.refresh_from_db()+ assert payment.is_active is Falsediff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.pyindex aede05c3d4..1b2048bf73 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py@@ -5,6 +5,7 @@ from unittest import mockimport grapheneimport pytestimport pytz+from django.utils import timezonefrom freezegun import freeze_timefrom .....channel import TransactionFlowStrategy@@ -19,7 +20,7 @@ from .....payment.interface import (TransactionSessionData,TransactionSessionResult,)-from .....payment.models import TransactionEvent+from .....payment.models import Payment, TransactionEventfrom ....core.enums import TransactionProcessErrorCodefrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -1446,7 +1447,6 @@ def test_transaction_process_for_disabled_app(# thencontent = get_graphql_content(response)- content = get_graphql_content(response)data = content["data"]["transactionProcess"]assert (data["errors"][0]["code"]@@ -1527,3 +1527,140 @@ def test_updates_checkout_last_transaction_modified_at(assert (checkout.last_transaction_modified_at != previous_last_transaction_modified_at)++[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_for_locked_checkout(+ mocked_process,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ checkout.completing_started_at = timezone.now()+ checkout.save(update_fields=["completing_started_at"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["amount"] = expected_amount+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ expected_data = {"some": "json-data"}+ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": expected_data,+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["transactionProcess"]+ assert len(data["errors"]) == 1+ assert (+ data["errors"][0]["code"]+ == TransactionProcessErrorCode.CHECKOUT_COMPLETION_IN_PROGRESS.name+ )+ assert data["errors"][0]["field"] == "id"+ mocked_process.assert_not_called()++[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_for_checkout_with_payments(+ mocked_process,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ # create payments+ payments = Payment.objects.bulk_create(+ [+ Payment(+ gateway="mirumee.payments.dummy", is_active=True, checkout=checkout+ ),+ Payment(+ gateway="mirumee.payments.dummy", is_active=False, checkout=checkout+ ),+ ]+ )++ transaction_item = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, app=webhook_app+ )+ TransactionEvent.objects.create(+ transaction=transaction_item,+ amount_value=expected_amount,+ currency=transaction_item.currency,+ type=TransactionEventType.CHARGE_REQUEST,+ )++ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["amount"] = expected_amount+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )+ expected_data = {"some": "json-data"}+ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": expected_data,+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=expected_amount,+ expected_psp_reference=expected_psp_reference,+ response_event_type=TransactionEventType.CHARGE_SUCCESS,+ app_identifier=webhook_app.identifier,+ mocked_process=mocked_process,+ charged_value=expected_amount,+ data=expected_data,+ returned_data=expected_response["data"],+ )+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL+ for payment in payments:+ payment.refresh_from_db()+ assert payment.is_active is Falsediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8212d4f8b9..c93140d29a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -24955,6 +24955,7 @@ enum TransactionInitializeErrorCode @doc(category: "Payments") {INVALIDNOT_FOUNDUNIQUE+ CHECKOUT_COMPLETION_IN_PROGRESS}"""@@ -24997,6 +24998,7 @@ enum TransactionProcessErrorCode @doc(category: "Payments") {TRANSACTION_ALREADY_PROCESSEDMISSING_PAYMENT_APP_RELATIONMISSING_PAYMENT_APP+ CHECKOUT_COMPLETION_IN_PROGRESS}"""diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 697be8f7c3..ef24bea342 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -117,6 +117,7 @@ def order_created(payment=payment,manager=manager,site_settings=site_settings,+ gateway=payment.gateway if payment else None,)channel = order_info.channel@@ -147,11 +148,12 @@ def handle_fully_paid_order(user: Optional[User] = None,app: Optional["App"] = None,site_settings: Optional["SiteSettings"] = None,+ gateway: Optional[str] = None,):from ..giftcard.utils import fulfill_non_shippable_gift_cardsorder = order_info.order- events.order_fully_paid_event(order=order, user=user, app=app)+ events.order_fully_paid_event(order=order, user=user, app=app, gateway=gateway)if order_info.customer_email:send_payment_confirmation(order_info, manager)if utils.order_needs_automatic_fulfillment(order_info.lines_data):@@ -354,6 +356,7 @@ def order_charged(payment: Optional["Payment"],manager: "PluginsManager",site_settings: Optional["SiteSettings"] = None,+ gateway: Optional[str] = None,):order = order_info.orderif payment and amount is not None:@@ -362,7 +365,7 @@ def order_charged()call_event(manager.order_paid, order)if order.charge_status in [OrderChargeStatus.FULL, OrderChargeStatus.OVERCHARGED]:- handle_fully_paid_order(manager, order_info, user, app, site_settings)+ handle_fully_paid_order(manager, order_info, user, app, site_settings, gateway)else:call_event(manager.order_updated, order)diff --git a/saleor/order/events.py b/saleor/order/events.pyindex e2e3d5ce7c..857e258c08 100644--- a/saleor/order/events.py+++ b/saleor/order/events.py@@ -374,10 +374,21 @@ def order_manually_marked_as_paid_event(def order_fully_paid_event(- *, order: Order, user: Optional[User], app: Optional[App]+ *,+ order: Order,+ user: Optional[User],+ app: Optional[App],+ gateway: Optional[str] = None,) -> OrderEvent:+ parameters = {}+ if gateway:+ parameters = {"payment_gateway": gateway}return OrderEvent.objects.create(- order=order, type=OrderEvents.ORDER_FULLY_PAID, user=user, app=app+ order=order,+ type=OrderEvents.ORDER_FULLY_PAID,+ user=user,+ app=app,+ parameters=parameters,)diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex 65ed257220..fc8fdc4e2a 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -150,6 +150,25 @@ def test_handle_fully_paid_order_no_email(mock_send_payment_confirmation, order)assert not mock_send_payment_confirmation.called+@patch("saleor.order.actions.send_payment_confirmation")+def test_handle_fully_paid_order_with_gateway(mock_send_payment_confirmation, order):+ # given+ manager = get_plugins_manager(allow_replica=False)++ order.payments.add(Payment.objects.create())+ order_info = fetch_order_info(order)++ # when+ handle_fully_paid_order(manager, order_info, gateway="mirumee.payments.dummy")++ # then+ event_order_paid = order.events.get()+ assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID+ assert event_order_paid.parameters == {"payment_gateway": "mirumee.payments.dummy"}++ mock_send_payment_confirmation.assert_called_once_with(order_info, manager)++@patch("saleor.giftcard.utils.send_gift_card_notification")@patch("saleor.order.actions.send_payment_confirmation")def test_handle_fully_paid_order_gift_cards_created(diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.pyindex 856a8397d8..1e6045c248 100644--- a/saleor/payment/error_codes.py+++ b/saleor/payment/error_codes.py@@ -86,6 +86,7 @@ class TransactionInitializeErrorCode(Enum):INVALID = "invalid"NOT_FOUND = "not_found"UNIQUE = "unique"+ CHECKOUT_COMPLETION_IN_PROGRESS = "checkout_completion_in_progress"class TransactionProcessErrorCode(Enum):@@ -95,6 +96,7 @@ class TransactionProcessErrorCode(Enum):TRANSACTION_ALREADY_PROCESSED = "transaction_already_processed"MISSING_PAYMENT_APP_RELATION = "missing_payment_app_relation"MISSING_PAYMENT_APP = "missing_payment_app"+ CHECKOUT_COMPLETION_IN_PROGRESS = "checkout_completion_in_progress"class StoredPaymentMethodRequestDeleteErrorCode(Enum):diff --git a/saleor/tests/e2e/apps/utils/app_create.py b/saleor/tests/e2e/apps/utils/app_create.pyindex 7d58581fb9..17ae5b04cb 100644--- a/saleor/tests/e2e/apps/utils/app_create.py+++ b/saleor/tests/e2e/apps/utils/app_create.py@@ -12,6 +12,7 @@ mutation AppCreate($input: AppInput!) {app {idisActive+ identifier}}}diff --git a/saleor/tests/e2e/checkout/test_checkout_create_order_transactions_and_active_payment.py b/saleor/tests/e2e/checkout/test_checkout_create_order_transactions_and_active_payment.pynew file mode 100644index 0000000000..6a29b9ec09--- /dev/null+++ b/saleor/tests/e2e/checkout/test_checkout_create_order_transactions_and_active_payment.py@@ -0,0 +1,134 @@+import pytest++from ..apps.utils import add_app+from ..orders.utils import order_query+from ..product.utils.preparing_product import prepare_product+from ..shop.utils.preparing_shop import prepare_default_shop+from ..transactions.utils import transaction_initialize+from ..utils import assign_permissions+from .utils import (+ checkout_complete,+ checkout_create,+ checkout_delivery_method_update,+ checkout_dummy_payment_create,+)+++def test_complete_checkout_with_transaction_and_active_payment_CORE_1601(+ e2e_staff_api_client,+ e2e_not_logged_api_client,+ shop_permissions,+ permission_manage_product_types_and_attributes,+ permission_manage_apps,+ permission_manage_checkouts,+ permission_manage_orders,+ monkeypatch,+):+ # Before+ permissions = [+ *shop_permissions,+ permission_manage_product_types_and_attributes,+ permission_manage_apps,+ permission_manage_checkouts,+ permission_manage_orders,+ ]+ assign_permissions(e2e_staff_api_client, permissions)++ # create webhook app+ identifier = "webhook.app.identifier"+ app_input = {+ "name": "external_shipping",+ "identifier": identifier,+ "permissions": [+ "MANAGE_SHIPPING",+ "MANAGE_CHECKOUTS",+ "MANAGE_ORDERS",+ "MANAGE_PRODUCTS",+ "MANAGE_CHANNELS",+ ],+ }+ app_data = add_app(e2e_staff_api_client, app_input)+ app_identifier = app_data["app"]["identifier"]++ shop_data = prepare_default_shop(e2e_staff_api_client)+ channel_id = shop_data["channel"]["id"]+ channel_slug = shop_data["channel"]["slug"]+ warehouse_id = shop_data["warehouse"]["id"]+ shipping_method_id = shop_data["shipping_method"]["id"]++ variant_price = 10++ (+ _product_id,+ product_variant_id,+ product_variant_price,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ variant_price,+ )++ # Step 1 - Create checkout.+ lines = [+ {+ "variantId": product_variant_id,+ "quantity": 1,+ },+ ]+ checkout_data = checkout_create(+ e2e_not_logged_api_client,+ lines,+ channel_slug,+ email="[email protected]",+ set_default_billing_address=True,+ set_default_shipping_address=True,+ )+ checkout_id = checkout_data["id"]++ assert checkout_data["isShippingRequired"] is True+ assert checkout_data["deliveryMethod"] is None+ assert checkout_data["shippingMethod"] is None++ # Step 2 - Set shipping address and DeliveryMethod for checkout+ checkout_data = checkout_delivery_method_update(+ e2e_not_logged_api_client,+ checkout_id,+ shipping_method_id,+ )+ # Step 2 - Set DeliveryMethod for checkout.+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]+ subtotal_gross_amount = checkout_data["subtotalPrice"]["gross"]["amount"]++ # Step 3 - Initialize transaction+ transaction_initialize(+ monkeypatch,+ e2e_not_logged_api_client,+ checkout_id,+ total_gross_amount,+ app_identifier,+ )++ # Step 4 - Create payment for checkout+ checkout_dummy_payment_create(+ e2e_not_logged_api_client, checkout_id, total_gross_amount+ )++ # Step 5 - Complete checkout.+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)++ order_id = order_data["id"]++ order_line = order_data["lines"][0]+ assert order_data["status"] == "UNFULFILLED"+ assert order_data["total"]["gross"]["amount"] == total_gross_amount+ assert order_data["subtotal"]["gross"]["amount"] == subtotal_gross_amount+ assert order_line["undiscountedUnitPrice"]["gross"]["amount"] == float(+ product_variant_price+ )++ # Step 6gst - check if order has transactions and payments objects+ order_data = order_query(e2e_staff_api_client, order_id)+ assert order_data["transactions"]+ assert order_data["payments"]diff --git a/saleor/tests/e2e/checkout/test_checkout_create_order_transactions_and_inactive_payment.py b/saleor/tests/e2e/checkout/test_checkout_create_order_transactions_and_inactive_payment.pynew file mode 100644index 0000000000..022655d227--- /dev/null+++ b/saleor/tests/e2e/checkout/test_checkout_create_order_transactions_and_inactive_payment.py@@ -0,0 +1,140 @@+import pytest++from ..apps.utils import add_app+from ..orders.utils import order_query+from ..payment.utils import get_payment+from ..product.utils.preparing_product import prepare_product+from ..shop.utils.preparing_shop import prepare_default_shop+from ..transactions.utils import transaction_initialize+from ..utils import assign_permissions+from .utils import (+ checkout_complete,+ checkout_create,+ checkout_delivery_method_update,+ checkout_dummy_payment_create,+)+++def test_complete_checkout_with_transaction_and_inactive_payment_CORE_1602(+ e2e_staff_api_client,+ e2e_not_logged_api_client,+ shop_permissions,+ permission_manage_product_types_and_attributes,+ permission_manage_apps,+ permission_manage_checkouts,+ permission_manage_orders,+ monkeypatch,+):+ # Before+ permissions = [+ *shop_permissions,+ permission_manage_product_types_and_attributes,+ permission_manage_apps,+ permission_manage_checkouts,+ permission_manage_orders,+ ]+ assign_permissions(e2e_staff_api_client, permissions)++ # create webhook app+ identifier = "webhook.app.identifier"+ app_input = {+ "name": "external_shipping",+ "identifier": identifier,+ "permissions": [+ "MANAGE_SHIPPING",+ "MANAGE_CHECKOUTS",+ "MANAGE_ORDERS",+ "MANAGE_PRODUCTS",+ "MANAGE_CHANNELS",+ ],+ }+ app_data = add_app(e2e_staff_api_client, app_input)+ app_identifier = app_data["app"]["identifier"]++ shop_data = prepare_default_shop(e2e_staff_api_client)+ channel_id = shop_data["channel"]["id"]+ channel_slug = shop_data["channel"]["slug"]+ warehouse_id = shop_data["warehouse"]["id"]+ shipping_method_id = shop_data["shipping_method"]["id"]++ variant_price = 10++ (+ _product_id,+ product_variant_id,+ product_variant_price,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ variant_price,+ )++ # Step 1 - Create checkout.+ lines = [+ {+ "variantId": product_variant_id,+ "quantity": 1,+ },+ ]+ checkout_data = checkout_create(+ e2e_not_logged_api_client,+ lines,+ channel_slug,+ email="[email protected]",+ set_default_billing_address=True,+ set_default_shipping_address=True,+ )+ checkout_id = checkout_data["id"]++ assert checkout_data["isShippingRequired"] is True+ assert checkout_data["deliveryMethod"] is None+ assert checkout_data["shippingMethod"] is None++ # Step 2 - Set shipping address and DeliveryMethod for checkout+ checkout_data = checkout_delivery_method_update(+ e2e_not_logged_api_client,+ checkout_id,+ shipping_method_id,+ )+ # Step 2 - Set DeliveryMethod for checkout.+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]+ subtotal_gross_amount = checkout_data["subtotalPrice"]["gross"]["amount"]++ # Step 3 - Create payment for checkout+ payment_data = checkout_dummy_payment_create(+ e2e_not_logged_api_client, checkout_id, total_gross_amount+ )+ payment_id = payment_data["id"]++ # Step 4 - Initialize transaction - should deactivate payment+ transaction_initialize(+ monkeypatch,+ e2e_not_logged_api_client,+ checkout_id,+ total_gross_amount,+ app_identifier,+ )++ # Step 5 - Check if payment is inactive+ payment_data = get_payment(e2e_staff_api_client, payment_id)+ assert payment_data["isActive"] is False++ # Step 6 - Complete checkout.+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)++ order_id = order_data["id"]++ order_line = order_data["lines"][0]+ assert order_data["status"] == "UNFULFILLED"+ assert order_data["total"]["gross"]["amount"] == total_gross_amount+ assert order_data["subtotal"]["gross"]["amount"] == subtotal_gross_amount+ assert order_line["undiscountedUnitPrice"]["gross"]["amount"] == float(+ product_variant_price+ )++ # Step 7 - check if order has transactions and payments objects+ order_data = order_query(e2e_staff_api_client, order_id)+ assert order_data["transactions"]+ assert order_data["payments"]diff --git a/saleor/tests/e2e/payment/__init__.py b/saleor/tests/e2e/payment/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/tests/e2e/payment/utils/__init__.py b/saleor/tests/e2e/payment/utils/__init__.pynew file mode 100644index 0000000000..2210d8568a--- /dev/null+++ b/saleor/tests/e2e/payment/utils/__init__.py@@ -0,0 +1,3 @@+from .query_payment import get_payment++__all__ = ["get_payment"]diff --git a/saleor/tests/e2e/payment/utils/query_payment.py b/saleor/tests/e2e/payment/utils/query_payment.pynew file mode 100644index 0000000000..628766ba44--- /dev/null+++ b/saleor/tests/e2e/payment/utils/query_payment.py@@ -0,0 +1,25 @@+from ...utils import get_graphql_content++PAYMENT_QUERY = """+ query payment($id: ID!) {+ payment(id: $id) {+ id+ isActive+ checkout {+ token+ }+ }+ }+"""+++def get_payment(+ api_client,+ payment_id,+):+ variables = {"id": payment_id}++ response = api_client.post_graphql(PAYMENT_QUERY, variables)+ content = get_graphql_content(response)++ return content["data"]["payment"]diff --git a/saleor/tests/e2e/transactions/utils/__init__.py b/saleor/tests/e2e/transactions/utils/__init__.pyindex ffa031dd30..403fe276f4 100644--- a/saleor/tests/e2e/transactions/utils/__init__.py+++ b/saleor/tests/e2e/transactions/utils/__init__.py@@ -1,5 +1,7 @@from .transaction_create import create_transaction+from .transaction_initialize import transaction_initialize__all__ = ["create_transaction",+ "transaction_initialize",]diff --git a/saleor/tests/e2e/transactions/utils/transaction_initialize.py b/saleor/tests/e2e/transactions/utils/transaction_initialize.pynew file mode 100644index 0000000000..7981734d0f--- /dev/null+++ b/saleor/tests/e2e/transactions/utils/transaction_initialize.py@@ -0,0 +1,112 @@+from unittest import mock++from .....payment.interface import TransactionSessionResult+from ...utils import get_graphql_content++TRANSACTION_INITIALIZE_MUTATION = """+mutation TransactionInitialize(+ $action: TransactionFlowStrategyEnum,+ $amount: PositiveDecimal,+ $id: ID!,+ $paymentGateway: PaymentGatewayToInitialize!+ $customerIpAddress: String+ $idempotencyKey: String+) {+ transactionInitialize(+ action: $action+ amount: $amount+ id: $id+ paymentGateway: $paymentGateway+ customerIpAddress: $customerIpAddress+ idempotencyKey: $idempotencyKey+ ) {+ data+ transaction {+ id+ authorizedAmount {+ currency+ amount+ }+ chargedAmount {+ currency+ amount+ }+ chargePendingAmount {+ amount+ currency+ }+ authorizePendingAmount {+ amount+ currency+ }+ }+ transactionEvent {+ amount {+ currency+ amount+ }+ type+ createdBy {+ ... on App {+ id+ }+ }+ pspReference+ message+ externalUrl+ }+ errors{+ field+ message+ code+ }+ }+}+"""+++def transaction_initialize(+ monkeypatch,+ e2e_api_client,+ id,+ amount,+ app_identifier,+ action=None,+ customer_ip_address=None,+ idempotency_key="TEST",+):+ expected_response = {+ "pspReference": "psp-123",+ "data": {"some-json": "data"},+ "result": "CHARGE_SUCCESS",+ "amount": amount,+ "time": "2022-11-18T13:25:58.169685+00:00",+ "externalUrl": "http://127.0.0.1:9090/external-reference",+ "message": "Message related to the payment",+ }++ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.transaction_initialize_session",+ mock.Mock(+ return_value=TransactionSessionResult(+ app_identifier=app_identifier, response=expected_response+ )+ ),+ )++ variables = {+ "action": action,+ "amount": amount,+ "id": id,+ "paymentGateway": {"id": app_identifier, "data": None},+ "customerIpAddress": customer_ip_address,+ "idempotencyKey": idempotency_key,+ }++ response = e2e_api_client.post_graphql(TRANSACTION_INITIALIZE_MUTATION, variables)+ content = get_graphql_content(response)++ assert not content["data"]["transactionInitialize"]["errors"]+ data = content["data"]["transactionInitialize"]++ return data