Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Clear caching stored payment methods in transactions api (#18362) (#18373)
Iga Karbowiak0031b8d09a5a
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.pyindex a7c864cfb1..a7de339b0b 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,+ invalidate_cache_for_stored_payment_methods_if_needed,process_order_or_checkout_with_transaction,truncate_transaction_event_message,update_transaction_item_with_payment_method_details,@@ -371,6 +372,7 @@ class TransactionEventReport(DeprecatedModelMutation):transaction_event = cls.construct_instance(transaction_event, transaction_event_data)+ source_object = transaction.order or transaction.checkoutmetadata_collection = cls.create_metadata_from_graphql_input(transaction_metadata, error_field_name="metadata"@@ -474,6 +476,12 @@ class TransactionEventReport(DeprecatedModelMutation):if updated_fields:transaction.save(update_fields=updated_fields)+ app_identifier = app_identifier or transaction.app_identifier+ if app_identifier and source_object:+ invalidate_cache_for_stored_payment_methods_if_needed(+ transaction_event, source_object, app_identifier+ )+return cls(already_processed=already_processed,transaction=transaction,diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.pyindex c1a207bd6b..745792bb34 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py@@ -29,6 +29,9 @@ from .....payment.lock_objects import (from .....payment.models import TransactionEventfrom .....payment.transaction_item_calculations import recalculate_transaction_amountsfrom .....tests import race_condition+from .....webhook.event_types import WebhookEventSyncType+from .....webhook.models import Webhook+from .....webhook.transport.utils import generate_cache_key_for_webhookfrom ....core.enums import TransactionEventReportErrorCodefrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -4021,3 +4024,385 @@ def test_transaction_event_report_event_already_exists_updates_other_payment_mettransaction.refresh_from_db()assert transaction.payment_method_type == PaymentMethodType.OTHERassert transaction.payment_method_name == payment_method_name+++ "result",+ [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ],+)+@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_invalidate_stored_payment_methods_for_order(+ cache_delete_mock,+ result,+ customer_user,+ app_api_client,+ order_with_lines,+ permission_manage_payments,+ list_stored_payment_methods_app,+ transaction_item_generator,+):+ # given+ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ app = app_api_client.app+ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, order_id=order.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ channel = order.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ # cache key for transaction webhook+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ app.id,+ )++ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": result.upper(),+ "amount": expected_amount,+ "pspReference": expected_psp_reference,+ "availableActions": [TransactionActionEnum.REFUND.name],+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal!+ $pspReference: String!+ $availableActions: [TransactionActionEnum!]!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ availableActions: $availableActions+ ) {+ ...TransactionEventData+ }+ }+ """+ )++ # when+ response = app_api_client.post_graphql(query, variables)++ # then+ response = get_graphql_content(response)+ transaction_report_data = response["data"]["transactionEventReport"]+ assert transaction_report_data["transaction"]++ # ensure that only cache for result app identifier has been cleared+ cache_delete_mock.assert_called_once_with(cache_key)+++ "result",+ [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ],+)+@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_invalidate_stored_payment_methods_for_checkout(+ cache_delete_mock,+ result,+ customer_user,+ app_api_client,+ checkout_with_items,+ permission_manage_payments,+ list_stored_payment_methods_app,+ transaction_item_generator,+ plugins_manager,+):+ # given+ checkout = checkout_with_items+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ # Fetch checkout lines and info to recalculate checkout total prices+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)+ fetch_checkout_data(checkout_info, plugins_manager, lines)++ app = app_api_client.app+ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, checkout_id=checkout.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ channel = checkout.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ # cache key for transaction webhook+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ app.id,+ )++ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": result.upper(),+ "amount": expected_amount,+ "pspReference": expected_psp_reference,+ "availableActions": [TransactionActionEnum.REFUND.name],+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal!+ $pspReference: String!+ $availableActions: [TransactionActionEnum!]!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ availableActions: $availableActions+ ) {+ ...TransactionEventData+ }+ }+ """+ )++ # when+ response = app_api_client.post_graphql(query, variables)++ # then+ response = get_graphql_content(response)+ transaction_report_data = response["data"]["transactionEventReport"]+ assert transaction_report_data["transaction"]++ # ensure that only cache for result app identifier has been cleared+ cache_delete_mock.assert_called_once_with(cache_key)+++ "result",+ [+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ ],+)+@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_stored_payment_methods_not_invalidated_for_order(+ cache_delete_mock,+ result,+ customer_user,+ app_api_client,+ order_with_lines,+ permission_manage_payments,+ transaction_item_generator,+):+ # given+ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ app = app_api_client.app+ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, order_id=order.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": result.upper(),+ "amount": expected_amount,+ "pspReference": expected_psp_reference,+ "availableActions": [TransactionActionEnum.REFUND.name],+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal!+ $pspReference: String!+ $availableActions: [TransactionActionEnum!]!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ availableActions: $availableActions+ ) {+ ...TransactionEventData+ }+ }+ """+ )++ # when+ response = app_api_client.post_graphql(query, variables)++ # then+ response = get_graphql_content(response)+ transaction_report_data = response["data"]["transactionEventReport"]+ assert transaction_report_data["transaction"]++ # ensure that cache has not been cleared+ cache_delete_mock.assert_not_called()+++ "result",+ [+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ ],+)+@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_stored_payment_methods_not_invalidated_for_checkout(+ cache_delete_mock,+ result,+ customer_user,+ app_api_client,+ checkout_with_items,+ permission_manage_payments,+ transaction_item_generator,+ plugins_manager,+):+ # given+ checkout = checkout_with_items+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ # Fetch checkout lines and info to recalculate checkout total prices+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)+ fetch_checkout_data(checkout_info, plugins_manager, lines)++ app = app_api_client.app+ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, checkout_id=checkout.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": result.upper(),+ "amount": expected_amount,+ "pspReference": expected_psp_reference,+ "availableActions": [TransactionActionEnum.REFUND.name],+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal!+ $pspReference: String!+ $availableActions: [TransactionActionEnum!]!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ availableActions: $availableActions+ ) {+ ...TransactionEventData+ }+ }+ """+ )++ # when+ response = app_api_client.post_graphql(query, variables)++ # then+ response = get_graphql_content(response)+ transaction_report_data = response["data"]["transactionEventReport"]+ assert transaction_report_data["transaction"]++ # ensure that cache has not been cleared+ cache_delete_mock.assert_not_called()diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex 7c73ab79cd..65d99577b2 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -2,6 +2,7 @@ import datetimefrom decimal import Decimalfrom unittest import mock+import grapheneimport pytestfrom django.conf import settingsfrom django.test import override_settings@@ -31,6 +32,8 @@ from .....payment.lock_objects import (from .....payment.models import Payment, TransactionItemfrom .....tests import race_conditionfrom .....webhook.event_types import WebhookEventSyncType+from .....webhook.models import Webhook+from .....webhook.transport.utils import generate_cache_key_for_webhookfrom ....channel.enums import TransactionFlowStrategyEnumfrom ....core.enums import TransactionInitializeErrorCodefrom ....core.utils import to_global_id_or_none@@ -3174,3 +3177,309 @@ def test_transaction_initialize_checkout_completed_race_condition(assert order.charge_status == OrderChargeStatus.FULLassert order.authorize_status == OrderAuthorizeStatus.FULLassert order.total_charged.amount == checkout.total.gross.amount+++ "result",+ [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_invalidate_stored_payment_methods_for_order(+ mocked_initialize,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ list_stored_payment_methods_app,+):+ # given+ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ channel = order.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ # cache key for transaction webhook+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ webhook_app.id,+ )++ variables = {+ "action": None,+ "amount": expected_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 not content["data"]["transactionInitialize"]["errors"]+ response_data = content["data"]["transactionInitialize"]+ assert response_data["transaction"]++ # ensure that only cache for result app identifier has been cleared+ cache_delete_mock.assert_called_once_with(cache_key)+++ "result",+ [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_invalidate_stored_payment_methods_for_checkout(+ mocked_initialize,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ list_stored_payment_methods_app,+):+ # given+ checkout = checkout_with_prices+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ channel = checkout.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ # cache key for transaction webhook+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ webhook_app.id,+ )++ variables = {+ "action": None,+ "amount": expected_amount,+ "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)+ assert not content["data"]["transactionInitialize"]["errors"]+ response_data = content["data"]["transactionInitialize"]+ assert response_data["transaction"]++ # ensure that only cache for result app identifier has been cleared+ cache_delete_mock.assert_called_once_with(cache_key)+++ "result",+ [+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_stored_payment_methods_not_invalidated_for_order(+ mocked_initialize,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ variables = {+ "action": None,+ "amount": expected_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 not content["data"]["transactionInitialize"]["errors"]+ response_data = content["data"]["transactionInitialize"]+ assert response_data["transaction"]++ # ensure that cache has not been cleared+ cache_delete_mock.assert_not_called()+++ "result",+ [+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_invalidate_stored_payment_methods_not_invalidated_for_checkout(+ mocked_initialize,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+):+ # given+ checkout = checkout_with_prices+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ expected_amount = Decimal("10.00")+ expected_psp_reference = "ppp-123"+ expected_response = transaction_session_response.copy()+ expected_response["result"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_initialize.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ variables = {+ "action": None,+ "amount": expected_amount,+ "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)+ assert not content["data"]["transactionInitialize"]["errors"]+ response_data = content["data"]["transactionInitialize"]+ assert response_data["transaction"]++ # ensure that cache has not been cleared+ cache_delete_mock.assert_not_called()diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.pyindex 21c7ebee81..c4539dd785 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py@@ -31,6 +31,8 @@ from .....payment.lock_objects import (from .....payment.models import Payment, TransactionEventfrom .....tests import race_conditionfrom .....webhook.event_types import WebhookEventSyncType+from .....webhook.models import Webhook+from .....webhook.transport.utils import generate_cache_key_for_webhookfrom ....core.enums import TransactionProcessErrorCodefrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -2802,3 +2804,345 @@ def test_transaction_initialize_checkout_completed_race_condition(assert order.charge_status == OrderChargeStatus.FULLassert order.authorize_status == OrderAuthorizeStatus.FULLassert order.total_charged.amount == checkout.total.gross.amount+++ "result",+ [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_invalidate_stored_payment_methods_for_order(+ mocked_process,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ list_stored_payment_methods_app,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction_item = transaction_item_generator(order_id=order.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"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ channel = order.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ # cache key for transaction webhook+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ webhook_app.id,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["errors"]+ response_data = content["data"]["transactionProcess"]+ assert response_data["transaction"]++ # ensure that only cache for result app identifier has been cleared+ cache_delete_mock.assert_called_once_with(cache_key)+++ "result",+ [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_invalidate_stored_payment_methods_for_checkout(+ mocked_process,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ list_stored_payment_methods_app,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction_item = transaction_item_generator(+ checkout_id=checkout.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"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ channel = checkout.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ # cache key for transaction webhook+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ webhook_app.id,+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["errors"]+ response_data = content["data"]["transactionProcess"]+ assert response_data["transaction"]++ # ensure that only cache for result app identifier has been cleared+ cache_delete_mock.assert_called_once_with(cache_key)+++ "result",+ [+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_stored_payment_methods_not_invalidated_for_order(+ mocked_process,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction_item = transaction_item_generator(order_id=order.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"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["errors"]+ response_data = content["data"]["transactionProcess"]+ assert response_data["transaction"]++ # ensure that cache has not been cleared+ cache_delete_mock.assert_not_called()+++ "result",+ [+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.CHARGE_ACTION_REQUIRED,+ TransactionEventType.CHARGE_FAILURE,+ ],+)[email protected]("saleor.webhook.transport.list_stored_payment_methods.cache.delete")[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_stored_payment_methods_not_invalidated_for_checkout(+ mocked_process,+ cache_delete_mock,+ result,+ customer_user,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ permission_manage_payments,+ transaction_item_generator,+):+ # given+ expected_amount = Decimal("10.00")++ checkout = checkout_with_prices+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ webhook_app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=webhook_app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction_item = transaction_item_generator(+ checkout_id=checkout.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"] = result.upper()+ expected_response["pspReference"] = expected_psp_reference+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["transactionProcess"]["errors"]+ response_data = content["data"]["transactionProcess"]+ assert response_data["transaction"]++ # ensure that cache has not been cleared+ cache_delete_mock.assert_not_called()diff --git a/saleor/payment/tests/test_utils/test_utils.py b/saleor/payment/tests/test_utils/test_utils.pyindex 3c350b044f..b43cc28ceb 100644--- a/saleor/payment/tests/test_utils/test_utils.py+++ b/saleor/payment/tests/test_utils/test_utils.py@@ -3,6 +3,7 @@ import loggingfrom decimal import Decimalfrom unittest.mock import patch+import grapheneimport pytestfrom freezegun import freeze_time@@ -10,6 +11,9 @@ from ....checkout import CheckoutAuthorizeStatus, calculationsfrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....order import OrderChargeStatus, OrderGrantedRefundStatusfrom ....plugins.manager import get_plugins_manager+from ....webhook.event_types import WebhookEventSyncType+from ....webhook.models import Webhook+from ....webhook.transport.utils import generate_cache_key_for_webhookfrom ... import TransactionEventTypefrom ...interface import (PaymentLineData,@@ -1817,6 +1821,249 @@ def test_create_transaction_event_from_request_and_webhook_updates_modified_at(assert checkout.last_transaction_modified_at == calculation_time+@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_create_transaction_event_invalidate_stored_payment_methods_for_order(+ cache_delete_mock,+ customer_user,+ app,+ order_with_lines,+ transaction_item_generator,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, order_id=order.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=expected_amount,+ currency="USD",+ transaction_id=transaction.id,+ )+ channel = order.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ app.id,+ )++ response_data = {+ "pspReference": expected_psp_reference,+ "amount": expected_amount,+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),+ "actions": ["CHARGE", "REFUND"],+ }++ # when+ create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ cache_delete_mock.assert_called_once_with(cache_key)+++@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_create_transaction_event_invalidate_stored_payment_methods_for_checkout(+ cache_delete_mock,+ customer_user,+ app,+ checkout_with_items,+ transaction_item_generator,+ permission_manage_payments,+):+ # given+ checkout = checkout_with_items+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, checkout_id=checkout.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=expected_amount,+ currency="USD",+ transaction_id=transaction.id,+ )++ channel = checkout.channel+ expected_payload = {+ "user_id": graphene.Node.to_global_id("User", customer_user.pk),+ "channel_slug": channel.slug,+ }+ cache_key = generate_cache_key_for_webhook(+ expected_payload,+ webhook.target_url,+ WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ app.id,+ )++ response_data = {+ "pspReference": expected_psp_reference,+ "amount": expected_amount,+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),+ "actions": ["CHARGE", "REFUND"],+ }++ # when+ create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ cache_delete_mock.assert_called_once_with(cache_key)+++@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_create_transaction_event_stored_payment_methods_not_invalidated_for_order(+ cache_delete_mock,+ customer_user,+ app,+ order_with_lines,+ transaction_item_generator,+ permission_manage_payments,+):+ # given+ order = order_with_lines+ order.user = customer_user+ order.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, order_id=order.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=expected_amount,+ currency="USD",+ transaction_id=transaction.id,+ )++ response_data = {+ "pspReference": expected_psp_reference,+ "amount": expected_amount,+ "result": TransactionEventType.CHARGE_FAILURE.upper(),+ "actions": ["CHARGE", "REFUND"],+ }++ # when+ create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ cache_delete_mock.assert_not_called()+++@patch("saleor.webhook.transport.list_stored_payment_methods.cache.delete")+def test_create_transaction_event_stored_payment_methods_not_invalidated_for_checkout(+ cache_delete_mock,+ customer_user,+ app,+ checkout_with_items,+ transaction_item_generator,+ permission_manage_payments,+):+ # given+ checkout = checkout_with_items+ checkout.user = customer_user+ checkout.save(update_fields=["user_id"])++ expected_app_identifier = "webhook.app.identifier"+ app.identifier = expected_app_identifier+ app.save()++ app.permissions.add(permission_manage_payments)+ webhook = Webhook.objects.create(+ name="list_stored_payment_methods",+ app=app,+ target_url="http://localhost:8000/endpoint/",+ )+ webhook.events.create(+ event_type=WebhookEventSyncType.LIST_STORED_PAYMENT_METHODS,+ )++ transaction = transaction_item_generator(app=app, checkout_id=checkout.pk)+ expected_amount = Decimal("11.00")+ expected_psp_reference = "111-abc"++ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=expected_amount,+ currency="USD",+ transaction_id=transaction.id,+ )++ response_data = {+ "pspReference": expected_psp_reference,+ "amount": expected_amount,+ "result": TransactionEventType.CHARGE_FAILURE.upper(),+ "actions": ["CHARGE", "REFUND"],+ }++ # when+ create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ cache_delete_mock.assert_not_called()++def test_recalculate_refundable_for_checkout_with_request_refund(transaction_item_generator, checkout):diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex e3186f3b8d..d01cdb618d 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -44,6 +44,9 @@ from ..order.utils import (from ..plugins.manager import PluginsManager, get_plugins_managerfrom ..webhook.response_schemas import transaction as transaction_schemasfrom ..webhook.response_schemas.utils.helpers import parse_validation_error+from ..webhook.transport.list_stored_payment_methods import (+ invalidate_cache_for_stored_payment_methods,+)from . import (ChargeStatus,GatewayError,@@ -1641,6 +1644,11 @@ def create_transaction_event_from_request_and_webhook_response(transaction_amounts_for_checkout_updated(transaction_item, manager, app=app, user=None)+ source_object = transaction_item.checkout or transaction_item.order+ if event and source_object:+ invalidate_cache_for_stored_payment_methods_if_needed(+ event, source_object, app.identifier+ )return event@@ -1882,6 +1890,9 @@ def handle_transaction_initialize_session(transaction_webhook_response=response_data,manager=manager,)+ invalidate_cache_for_stored_payment_methods_if_needed(+ created_event, source_object, app.identifier+ )data_to_return = response_data.get("data") if response_data else Nonereturn created_event.transaction, created_event, data_to_return@@ -1918,10 +1929,38 @@ def handle_transaction_process_session(transaction_webhook_response=response_data,manager=manager,)+ invalidate_cache_for_stored_payment_methods_if_needed(+ created_event, source_object, app.identifier+ )data_to_return = response_data.get("data") if response_data else Nonereturn created_event, data_to_return+def invalidate_cache_for_stored_payment_methods_if_needed(+ event: TransactionEvent, source_object: Checkout | Order, app_identifier: str+):+ """Invalidate the cache for stored payment methods if needed.++ Invalidate LIST_STORED_PAYMENT_METHODS webhook cache in case+ a new payment method is stored during authorization/charge.+ """+ if (+ event.type+ in [+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ ]+ and source_object.user_id+ ):+ invalidate_cache_for_stored_payment_methods(+ user_id=source_object.user_id,+ channel_slug=source_object.channel.slug,+ app_identifier=app_identifier,+ )++def get_transaction_event_amount(event_type: str, psp_reference: str):"""Deduce the transaction event amount if possible.