Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle long message when reporting transaction event (#17049)
Iga Karbowiak04226e3d4559
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.pyindex 4f91d1ae44..3ff04687f1 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py@@ -21,7 +21,7 @@ from .....payment import TransactionEventTypefrom .....payment import models as payment_modelsfrom .....payment.error_codes import TransactionCreateErrorCodefrom .....payment.transaction_item_calculations import recalculate_transaction_amounts-from .....payment.utils import create_manual_adjustment_events+from .....payment.utils import create_manual_adjustment_events, truncate_messagefrom .....permission.enums import PaymentPermissionsfrom ....app.dataloaders import get_app_promisefrom ....core import ResolveInfo@@ -277,7 +277,7 @@ class TransactionCreate(BaseMutation):app_identifier = app.identifierreturn transaction.events.create(psp_reference=transaction_event_input.get("psp_reference"),- message=transaction_event_input.get("message", ""),+ message=truncate_message(transaction_event_input.get("message", "")),transaction=transaction,user=user if user and user.is_authenticated else None,app_identifier=app_identifier,diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.pyindex 4dfff6c1d6..58a0632871 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py@@ -26,6 +26,7 @@ from .....payment.utils import (create_failed_transaction_event,get_already_existing_event,get_transaction_event_amount,+ truncate_message,)from .....permission.auth_filters import AuthorizationFiltersfrom .....permission.enums import PaymentPermissions@@ -109,7 +110,12 @@ class TransactionEventReport(ModelMutation):"payment provider page with event details."))- message = graphene.String(description="The message related to the event.")+ message = graphene.String(+ description=(+ "The message related to the event. The maximum length is 512 "+ "characters; any text exceeding this limit will be truncated."+ )+ )available_actions = graphene.List(graphene.NonNull(TransactionActionEnum),description="List of all possible actions for the transaction",@@ -312,6 +318,7 @@ class TransactionEventReport(ModelMutation):psp_reference, transaction)+ message = truncate_message(message) if message is not None else ""transaction_event_data = {"psp_reference": psp_reference,"type": type,@@ -319,7 +326,7 @@ class TransactionEventReport(ModelMutation):"currency": transaction.currency,"created_at": time or timezone.now(),"external_url": external_url or "",- "message": message or "",+ "message": message,"transaction": transaction,"app_identifier": app_identifier,"app": app,diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.pyindex 50ff39bccb..81497dd6cc 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py@@ -2364,3 +2364,54 @@ def test_transaction_create_amount_with_lot_of_decimal_places(assert transaction.app == app_api_client.appassert transaction.user is Noneassert transaction.external_url == external_url+++def test_transaction_create_create_event_message_limit_exceeded(+ order_with_lines, permission_manage_payments, app_api_client+):+ # given+ name = "Credit Card"+ psp_reference = "PSP reference - 123"+ available_actions = [+ TransactionActionEnum.CHARGE.name,+ ]+ authorized_value = Decimal("10")+ transaction_reference = "transaction reference"+ transaction_msg = "m" * 513++ variables = {+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),+ "transaction": {+ "name": name,+ "pspReference": psp_reference,+ "availableActions": available_actions,+ "amountAuthorized": {+ "amount": authorized_value,+ "currency": "USD",+ },+ },+ "transaction_event": {+ "pspReference": transaction_reference,+ "message": transaction_msg,+ },+ }++ # when+ app_api_client.post_graphql(+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]+ )++ # then+ assert order_with_lines.events.count() == 1+ event = order_with_lines.events.first()++ assert event.type == OrderEvents.TRANSACTION_EVENT+ assert event.parameters == {+ "message": transaction_msg,+ "reference": transaction_reference,+ }++ transaction = order_with_lines.payment_transactions.first()+ event = transaction.events.last()+ assert event.message == transaction_msg[:509] + "..."+ assert event.psp_reference == transaction_referencediff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.pyindex b434667d33..b37eb3616b 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py@@ -3144,3 +3144,83 @@ def test_transaction_event_report_update_transaction_private_metadata(assert event.app == app_api_client.appassert event.user is Nonetransaction_item_metadata_updated_mock.assert_not_called()+++def test_transaction_event_report_message_limit_exceeded(+ transaction_item_generator,+ app_api_client,+ permission_manage_payments,+):+ # given+ transaction = transaction_item_generator(+ app=app_api_client.app, authorized_value=Decimal("10")+ )+ event_time = timezone.now()+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"+ message = "m" * 550+ psp_reference = "111-abc"+ amount = Decimal("11.00")+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,+ "amount": amount,+ "pspReference": psp_reference,+ "time": event_time.isoformat(),+ "externalUrl": external_url,+ "message": message,+ "availableActions": [TransactionActionEnum.REFUND.name],+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal!+ $pspReference: String!+ $time: DateTime+ $externalUrl: String+ $message: String+ $availableActions: [TransactionActionEnum!]!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ time: $time+ externalUrl: $externalUrl+ message: $message+ availableActions: $availableActions+ ) {+ ...TransactionEventData+ }+ }+ """+ )+ # when+ response = app_api_client.post_graphql(+ query, variables, permissions=[permission_manage_payments]+ )++ # then+ response = get_graphql_content(response)+ transaction_report_data = response["data"]["transactionEventReport"]+ assert transaction_report_data["alreadyProcessed"] is False++ event = TransactionEvent.objects.filter(+ type=TransactionEventType.CHARGE_SUCCESS+ ).first()+ assert event+ assert event.psp_reference == psp_reference+ assert event.type == TransactionEventTypeEnum.CHARGE_SUCCESS.value+ assert event.amount_value == amount+ assert event.currency == transaction.currency+ assert event.created_at == event_time+ assert event.external_url == external_url+ assert event.transaction == transaction+ assert event.app_identifier == app_api_client.app.identifier+ assert event.app == app_api_client.app+ assert event.user is None+ assert event.message == message[:509] + "..."diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex eb812f8a43..906b1170a7 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -107,6 +107,7 @@ def _assert_fields(charge_pending_value=Decimal(0),authorize_pending_value=Decimal(0),returned_data=None,+ expected_message=None,):assert not content["data"]["transactionInitialize"]["errors"]response_data = content["data"]["transactionInitialize"]@@ -170,6 +171,8 @@ def _assert_fields(assert response_event.amount_value == expected_amountassert response_event.include_in_calculationsassert response_event.psp_reference == expected_psp_reference+ if expected_message is not None:+ assert response_event.message == expected_messagemocked_initialize.assert_called_with(TransactionSessionData(@@ -2667,3 +2670,61 @@ def test_for_checkout_with_payments_error_raised(payment.refresh_from_db()assert payments[0].is_active is Trueassert payments[1].is_active is False++[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")+def test_for_checkout_too_long_message_in_response(+ mocked_initialize,+ user_api_client,+ checkout_with_prices,+ webhook_app,+ transaction_session_response,+ caplog,+):+ # given+ checkout = checkout_with_prices+ 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["message"] = "m" * 513+ 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)+ 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"],+ expected_message=expected_response["message"][:509] + "...",+ )+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL+ assert (+ "Value for field: message in response of transaction action webhook "+ "exceeds the character field limit. Message has been truncated."+ ) in [record.message for record in caplog.records]diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.pyindex f28fc0ae33..b9df03a90f 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py@@ -157,6 +157,7 @@ def _assert_fields(charge_pending_value=Decimal(0),authorize_pending_value=Decimal(0),returned_data=None,+ expected_message=None,):assert not content["data"]["transactionProcess"]["errors"]response_data = content["data"]["transactionProcess"]@@ -223,6 +224,8 @@ def _assert_fields()assert response_event.include_in_calculations is include_in_calculationsassert response_event.psp_reference == expected_psp_reference+ if expected_message is not None:+ assert response_event.message == expected_messagemocked_process.assert_called_with(TransactionSessionData(@@ -2237,3 +2240,68 @@ def test_for_checkout_with_payments_transaction_process_failure(payment.refresh_from_db()assert payments[0].is_active is Trueassert payments[1].is_active is False++[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")+def test_for_order_too_long_message_in_response(+ mocked_process,+ user_api_client,+ order_with_lines,+ webhook_app,+ transaction_session_response,+ transaction_item_generator,+ caplog,+):+ # given+ expected_amount = Decimal("10.00")++ order = order_with_lines+ expected_app_identifier = "webhook.app.identifier"+ webhook_app.identifier = expected_app_identifier+ webhook_app.save()++ 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"] = TransactionEventType.CHARGE_SUCCESS.upper()+ expected_response["pspReference"] = expected_psp_reference+ expected_response["message"] = "m" * 513+ del expected_response["data"]+ mocked_process.return_value = TransactionSessionResult(+ app_identifier=expected_app_identifier, response=expected_response+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "data": None,+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)++ # then+ content = get_graphql_content(response)+ _assert_fields(+ content=content,+ source_object=order,+ 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,+ returned_data=None,+ expected_message=expected_response["message"][:509] + "...",+ )+ assert (+ "Value for field: message in response of transaction action webhook "+ "exceeds the character field limit. Message has been truncated."+ ) in [record.message for record in caplog.records]diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.pyindex 9dbe8497e0..2ff3c0fc62 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py@@ -3302,3 +3302,44 @@ def test_transaction_update_amounts_with_lot_of_decimal_places(data = content["data"]["transactionUpdate"]["transaction"]assert str(data[response_field]["amount"]) == str(round(value, 2))assert getattr(transaction, db_field_name) == round(value, 2)+++def test_transaction_uodate_transaction_event_message_limit_exceeded(+ transaction_item_created_by_app,+ order_with_lines,+ permission_manage_payments,+ app_api_client,+):+ # given+ transaction = transaction_item_created_by_app+ transaction_reference = "transaction reference"+ transaction_msg = "m" * 513++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),+ "transaction_event": {+ "pspReference": transaction_reference,+ "message": transaction_msg,+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )+ # then+ event = order_with_lines.events.first()+ content = get_graphql_content(response)+ data = content["data"]["transactionUpdate"]++ assert not data["errors"]+ assert event.type == OrderEvents.TRANSACTION_EVENT+ assert event.parameters == {+ "message": transaction_msg,+ "reference": transaction_reference,+ }++ transaction = order_with_lines.payment_transactions.first()+ event = transaction.events.last()+ assert event.message == transaction_msg[:509] + "..."+ assert event.psp_reference == transaction_referencediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 7b98515bab..280c7660ee 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -15384,7 +15384,9 @@ type Mutation {"""The ID of the transaction. One of field id or token is required."""id: ID- """The message related to the event."""+ """+ The message related to the event. The maximum length is 512 characters; any text exceeding this limit will be truncated.+ """message: String"""PSP Reference of the event to report."""diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.pyindex 8e0e4ec87b..b4e71dec9a 100644--- a/saleor/payment/tests/test_utils.py+++ b/saleor/payment/tests/test_utils.py@@ -1761,6 +1761,64 @@ def test_create_event_from_request_and_webhook_pending_event_calculate_refundablassert checkout.automatically_refundable is True+def test_create_transaction_event_from_request_and_webhook_response_message_loo_long(+ transaction_item_generator, app, caplog+):+ # given+ transaction = transaction_item_generator()+ request_event = TransactionEvent.objects.create(+ type=TransactionEventType.CHARGE_REQUEST,+ amount_value=Decimal(11.00),+ currency="USD",+ transaction_id=transaction.id,+ )++ event_amount = 12.00+ event_type = TransactionEventType.CHARGE_FAILURE+ event_time = "2022-11-18T13:25:58.169685+00:00"+ event_url = "http://localhost:3000/event/ref123"+ event_message = "m" * 550++ expected_psp_reference = "psp:122:222"++ response_data = {+ "pspReference": expected_psp_reference,+ "amount": event_amount,+ "result": event_type.upper(),+ "time": event_time,+ "externalUrl": event_url,+ "message": event_message,+ "actions": ["CHARGE", "CHARGE", "CANCEL"],+ }++ # when+ event = create_transaction_event_from_request_and_webhook_response(+ request_event, app, response_data+ )++ # then+ transaction.refresh_from_db()+ assert len(transaction.available_actions) == 2+ assert set(transaction.available_actions) == {"charge", "cancel"}+ assert transaction.events.count() == 2+ request_event.refresh_from_db()+ assert request_event.psp_reference == expected_psp_reference+ assert request_event.include_in_calculations is True+ assert event+ assert event.psp_reference == expected_psp_reference+ assert event.amount_value == event_amount+ assert event.created_at == datetime.datetime.fromisoformat(event_time)+ assert event.external_url == event_url+ assert event.message == event_message[:509] + "..."+ assert event.type == event_type+ assert len(caplog.records) == 1+ assert caplog.records[0].message == (+ "Value for field: message in response of transaction action webhook "+ "exceeds the character field limit. Message has been truncated."+ )+ assert caplog.records[0].levelno == logging.WARNING++@pytest.mark.parametrize(("db_field_name", "value", "event_type"),[@@ -2514,6 +2572,47 @@ def test_create_transaction_event_updates_transaction_modified_at_for_failure(assert checkout.last_transaction_modified_at == calculation_time+def test_create_transaction_event_message_limit_exceeded(+ transaction_item_generator,+ transaction_session_response,+ webhook_app,+ plugins_manager,+ checkout,+ caplog,+):+ # given+ expected_amount = Decimal("15")+ message = "m" * 1000+ response = transaction_session_response.copy()+ response["amount"] = expected_amount+ response["message"] = message++ transaction = transaction_item_generator(checkout_id=checkout.pk)+ request_event = TransactionEvent.objects.create(+ transaction=transaction, include_in_calculations=False+ )++ # when+ create_transaction_event_for_transaction_session(+ request_event,+ webhook_app,+ manager=plugins_manager,+ transaction_webhook_response=response,+ )++ # then+ transaction.refresh_from_db()+ assert transaction.events.count() == 2+ event = transaction.events.last()+ assert event.message == message[:509] + "..."+ assert len(caplog.records) == 1+ assert caplog.records[0].message == (+ "Value for field: message in response of transaction action webhook "+ "exceeds the character field limit. Message has been truncated."+ )+ assert caplog.records[0].levelno == logging.WARNING++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 dc6a55f2c1..c9898d292e 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -879,6 +879,16 @@ def parse_transaction_event_data(logger.warning(missing_msg, "result")error_field_msg.append(missing_msg % "result")+ message = event_data.get("message", "")+ if len(message) > 512:+ message = truncate_message(message)+ field_limit_exceeded_msg = (+ "Value for field: %s in response of transaction action webhook "+ "exceeds the character field limit. Message has been truncated."+ )+ logger.warning(field_limit_exceeded_msg, "message")+ parsed_event_data["message"] = message+amount_data = event_data.get("amount")parse_transaction_event_amount(amount_data,@@ -904,7 +914,6 @@ def parse_transaction_event_data(parsed_event_data["time"] = timezone.now()parsed_event_data["external_url"] = event_data.get("externalUrl", "")- parsed_event_data["message"] = event_data.get("message", "")error_msg = str@@ -949,8 +958,7 @@ def parse_transaction_action_data(# error field msg can contain details of the value returned by payment app# which means that we need to confirm that we don't exceed the field limit.msg = "\n".join(error_field_msg)- if len(msg) >= 512:- msg = msg[:509] + "..."+ msg = truncate_message(msg)return None, msgrequest_event_type = parsed_event_data.get("type", request_type)@@ -971,6 +979,10 @@ def parse_transaction_action_data()+def truncate_message(message: str):+ return message[:509] + "..." if len(message) > 512 else message++def get_failed_transaction_event_type_for_request_event(request_event: TransactionEvent,):