Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make `amount` optional in `transactionEventReport` for `REFUND_REVERSE`, `CHARGEBACK`, `INFO`, and all `*_FAILURE` events (#16705)
Iga Karbowiake6198146186d
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.pyindex 7f58cafe86..35f0afe3f4 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py@@ -17,13 +17,14 @@ from .....order.utils import (calculate_order_granted_refund_status,updates_amounts_for_order,)-from .....payment import TransactionEventType+from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventTypefrom .....payment import models as payment_modelsfrom .....payment.transaction_item_calculations import recalculate_transaction_amountsfrom .....payment.utils import (authorization_success_already_exists,create_failed_transaction_event,get_already_existing_event,+ get_transaction_event_amount,)from .....permission.auth_filters import AuthorizationFiltersfrom .....permission.enums import PaymentPermissions@@ -81,7 +82,14 @@ class TransactionEventReport(ModelMutation):description="Current status of the event to report.",)amount = PositiveDecimal(- description="The amount of the event to report.", required=True+ description=(+ "The amount of the event to report. \n\nRequired for all `REQUEST`, "+ "`SUCCESS`, `ACTION_REQUIRED`, and `ADJUSTMENT` events. For other events, "+ "the amount will be calculated based on the previous events with "+ "the same pspReference. "+ "If not possible to calculate, the mutation will return an error."+ ),+ required=False,)time = DateTime(description=(@@ -184,6 +192,33 @@ class TransactionEventReport(ModelMutation):)return request_refund.related_granted_refund if request_refund else None+ @classmethod+ def clean_amount_value(+ cls, amount: Optional[float], event_type: str, psp_reference: str, currency: str+ ):+ if amount is None:+ if event_type not in OPTIONAL_AMOUNT_EVENTS:+ raise ValidationError(+ {+ "amount": ValidationError(+ f"The `amount` field is required for {event_type} event.",+ code=TransactionEventReportErrorCode.REQUIRED.value,+ )+ }+ )+ try:+ amount = get_transaction_event_amount(event_type, psp_reference)+ except ValueError as error:+ raise ValidationError(+ {+ "amount": ValidationError(+ str(error),+ code=TransactionEventReportErrorCode.REQUIRED.value,+ )+ },+ )+ return quantize_price(amount, currency)+@classmethoddef perform_mutation( # type: ignore[override]cls,@@ -193,7 +228,7 @@ class TransactionEventReport(ModelMutation):*,psp_reference,type,- amount,+ amount=None,token=None,id=None,time=None,@@ -217,7 +252,9 @@ class TransactionEventReport(ModelMutation):])- amount = quantize_price(amount, transaction.currency)+ amount = cls.clean_amount_value(+ amount, type, psp_reference, transaction.currency+ )app_identifier = Noneif app and app.identifier:app_identifier = app.identifierdiff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.pyindex f78e0d2caf..b1e34dc345 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py@@ -13,7 +13,7 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom .....checkout.calculations import fetch_checkout_datafrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....order import OrderGrantedRefundStatus, OrderStatus-from .....payment import TransactionEventType+from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventTypefrom .....payment.models import TransactionEventfrom .....payment.transaction_item_calculations import recalculate_transaction_amountsfrom ....core.enums import TransactionEventReportErrorCode@@ -2320,3 +2320,224 @@ def test_transaction_event_report_updates_granted_refund_status_when_needed(response = get_graphql_content(response)granted_refund.refresh_from_db()assert granted_refund.status == expected_status+++ "event_type", [event_type for event_type in OPTIONAL_AMOUNT_EVENTS]+)+def test_transaction_event_report_missing_amount(+ event_type,+ transaction_item_generator,+ transaction_events_generator,+ app_api_client,+ permission_manage_payments,+):+ # given+ transaction = transaction_item_generator(+ app=app_api_client.app, authorized_value=Decimal("10")+ )+ psp_reference = "111-abc"+ expected_amount = 10+ event_types = [+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_SUCCESS,+ TransactionEventType.REFUND_SUCCESS,+ ]+ transaction_events_generator(+ transaction=transaction,+ psp_references=[+ psp_reference,+ ]+ * len(event_types),+ types=event_types,+ amounts=[+ expected_amount,+ ]+ * len(event_types),+ )+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": event_type.upper(),+ "pspReference": psp_reference,+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $amount: PositiveDecimal+ $pspReference: String!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ amount: $amount+ pspReference: $pspReference+ ) {+ ...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 not transaction_report_data["errors"]+ assert transaction_report_data["alreadyProcessed"] is False++ event = TransactionEvent.objects.last()+ assert event+ assert event.psp_reference == psp_reference+ assert event.type == event_type+ expected_amount = (+ expected_amount if event_type != TransactionEventType.INFO else Decimal("0")+ )+ assert event.amount_value == expected_amount+ assert event.currency == transaction.currency+ 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+++ "event_type",+ [+ event_type+ for event_type in OPTIONAL_AMOUNT_EVENTS+ if event_type != TransactionEventType.INFO+ ],+)+def test_transaction_event_report_missing_amount_not_deduced_error_raised(+ event_type,+ transaction_item_generator,+ app_api_client,+ permission_manage_payments,+):+ # given+ transaction = transaction_item_generator(+ app=app_api_client.app, authorized_value=Decimal("10")+ )+ psp_reference = "111-abc"+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": event_type.upper(),+ "pspReference": psp_reference,+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $pspReference: String!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ pspReference: $pspReference+ ) {+ ...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 not transaction_report_data["transactionEvent"]+ errors = transaction_report_data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "amount"+ assert errors[0]["code"] == TransactionEventReportErrorCode.REQUIRED.name+++ "event_type",+ [+ event_type[0]+ for event_type in TransactionEventType.CHOICES+ if event_type[0] not in OPTIONAL_AMOUNT_EVENTS+ ],+)+def test_transaction_event_report_missing_amount_error_raised(+ event_type,+ transaction_item_generator,+ transaction_events_generator,+ app_api_client,+ permission_manage_payments,+):+ # given+ transaction = transaction_item_generator(+ app=app_api_client.app, authorized_value=Decimal("10")+ )+ psp_reference = "111-abc"+ amount = 10+ event_types = [+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.CHARGE_SUCCESS,+ TransactionEventType.REFUND_SUCCESS,+ ]+ transaction_events_generator(+ transaction=transaction,+ psp_references=[+ psp_reference,+ ]+ * len(event_types),+ types=event_types,+ amounts=[+ amount,+ ]+ * len(event_types),+ )++ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ variables = {+ "id": transaction_id,+ "type": event_type.upper(),+ "pspReference": psp_reference,+ }+ query = (+ MUTATION_DATA_FRAGMENT+ + """+ mutation TransactionEventReport(+ $id: ID+ $type: TransactionEventTypeEnum!+ $pspReference: String!+ ) {+ transactionEventReport(+ id: $id+ type: $type+ pspReference: $pspReference+ ) {+ ...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 not transaction_report_data["transactionEvent"]+ errors = transaction_report_data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "amount"+ assert errors[0]["code"] == TransactionEventReportErrorCode.REQUIRED.namediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4d7f734fd3..f8261304e1 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -17031,8 +17031,12 @@ type Mutation {Requires the following permissions: OWNER and HANDLE_PAYMENTS for apps, HANDLE_PAYMENTS for staff users. Staff user cannot update a transaction that is owned by the app."""transactionEventReport(- """The amount of the event to report."""- amount: PositiveDecimal!+ """+ The amount of the event to report.++ Required for all `REQUEST`, `SUCCESS`, `ACTION_REQUIRED`, and `ADJUSTMENT` events. For other events, the amount will be calculated based on the previous events with the same pspReference. If not possible to calculate, the mutation will return an error.+ """+ amount: PositiveDecimal"""List of all possible actions for the transaction"""availableActions: [TransactionActionEnum!]@@ -24934,6 +24938,7 @@ enum TransactionEventReportErrorCode @doc(category: "Payments") {NOT_FOUNDINCORRECT_DETAILSALREADY_EXISTS+ REQUIRED}"""diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex e03553a37f..8ae2233a27 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -263,6 +263,13 @@ OPTIONAL_PSP_REFERENCE_EVENTS = [TransactionEventType.CANCEL_FAILURE,]+OPTIONAL_AMOUNT_EVENTS = [+ *FAILED_TRANSACTION_EVENTS,+ TransactionEventType.REFUND_REVERSE,+ TransactionEventType.CHARGE_BACK,+ TransactionEventType.INFO,+]+class TokenizedPaymentFlow:"""Represents possible tokenized payment flows that can be used to process payment.diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.pyindex 1e6045c248..e8f2775498 100644--- a/saleor/payment/error_codes.py+++ b/saleor/payment/error_codes.py@@ -67,6 +67,7 @@ class TransactionEventReportErrorCode(Enum):NOT_FOUND = "not_found"INCORRECT_DETAILS = "incorrect_details"ALREADY_EXISTS = "already_exists"+ REQUIRED = "required"class PaymentGatewayConfigErrorCode(Enum):diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.pyindex 4ba3bc690e..5d9e56e468 100644--- a/saleor/payment/tests/test_utils.py+++ b/saleor/payment/tests/test_utils.py@@ -1,4 +1,4 @@-from datetime import datetime+from datetime import datetime, timedeltafrom decimal import Decimalfrom unittest.mock import patch@@ -27,6 +27,7 @@ from ..utils import (create_transaction_event_from_request_and_webhook_response,get_channel_slug_from_payment,get_correct_event_types_based_on_request_type,+ get_transaction_event_amount,parse_transaction_action_data,recalculate_refundable_for_checkout,try_void_or_refund_inactive_payment,@@ -2602,3 +2603,231 @@ def test_recalculate_refundable_for_checkout_update_missing_checkout(# thentransaction_item.refresh_from_db()assert transaction_item.last_refund_success is False+++ ("input_event_type", "event_type_to_create"),+ [+ (TransactionEventType.CHARGE_FAILURE, TransactionEventType.CHARGE_SUCCESS),+ (TransactionEventType.CHARGE_FAILURE, TransactionEventType.CHARGE_REQUEST),+ (+ TransactionEventType.CHARGE_FAILURE,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ ),+ (+ TransactionEventType.CHARGE_FAILURE,+ TransactionEventType.AUTHORIZATION_REQUEST,+ ),+ (+ TransactionEventType.CHARGE_FAILURE,+ TransactionEventType.AUTHORIZATION_FAILURE,+ ),+ (TransactionEventType.REFUND_FAILURE, TransactionEventType.REFUND_SUCCESS),+ (TransactionEventType.REFUND_FAILURE, TransactionEventType.REFUND_REQUEST),+ (TransactionEventType.REFUND_FAILURE, TransactionEventType.CHARGE_SUCCESS),+ (TransactionEventType.REFUND_FAILURE, TransactionEventType.CHARGE_REQUEST),+ (TransactionEventType.REFUND_FAILURE, TransactionEventType.CHARGE_FAILURE),+ (TransactionEventType.CANCEL_FAILURE, TransactionEventType.CANCEL_SUCCESS),+ (TransactionEventType.CANCEL_FAILURE, TransactionEventType.CANCEL_REQUEST),+ (+ TransactionEventType.CANCEL_FAILURE,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ ),+ (+ TransactionEventType.CANCEL_FAILURE,+ TransactionEventType.AUTHORIZATION_REQUEST,+ ),+ (+ TransactionEventType.CANCEL_FAILURE,+ TransactionEventType.AUTHORIZATION_FAILURE,+ ),+ (+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ ),+ (+ TransactionEventType.AUTHORIZATION_FAILURE,+ TransactionEventType.AUTHORIZATION_REQUEST,+ ),+ (TransactionEventType.REFUND_REVERSE, TransactionEventType.REFUND_SUCCESS),+ (TransactionEventType.CHARGE_BACK, TransactionEventType.CHARGE_SUCCESS),+ ],+)+def test_get_transaction_event_amount(+ input_event_type,+ event_type_to_create,+ transaction_events_generator,+ transaction_item,+):+ # given+ expected_amount = 10+ psp_reference = "xyz"+ transaction_events_generator(+ transaction=transaction_item,+ psp_references=[+ psp_reference,+ ],+ types=[+ event_type_to_create,+ ],+ amounts=[+ expected_amount,+ ],+ )++ # when+ amount = get_transaction_event_amount(input_event_type, psp_reference)++ # then+ assert amount == expected_amount+++def test_get_transaction_event_amount_match_the_newest_event(+ transaction_events_generator, transaction_item+):+ # given+ psp_reference = "xyz"+ event_types = [+ TransactionEventType.CHARGE_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_FAILURE,+ ]+ events = transaction_events_generator(+ transaction=transaction_item,+ psp_references=[+ psp_reference,+ ]+ * len(event_types),+ types=event_types,+ amounts=[10, 5, 4, 3, 2],+ )+ newest_event = events[-1]+ for event in events[:-1]:+ event.created_at = newest_event.created_at - timedelta(minutes=10)+ TransactionEvent.objects.bulk_update(events[:-1], ["created_at"])++ # when+ amount = get_transaction_event_amount(+ TransactionEventType.CHARGE_FAILURE, psp_reference+ )++ # then+ assert amount == newest_event.amount_value+++ ("input_event_type", "event_types_to_create"),+ [+ (TransactionEventType.CHARGE_FAILURE, [TransactionEventType.REFUND_FAILURE]),+ (TransactionEventType.CHARGE_FAILURE, []),+ (+ TransactionEventType.REFUND_FAILURE,+ [TransactionEventType.AUTHORIZATION_FAILURE],+ ),+ (TransactionEventType.REFUND_FAILURE, []),+ (TransactionEventType.CANCEL_FAILURE, [TransactionEventType.CHARGE_FAILURE]),+ (TransactionEventType.CANCEL_FAILURE, []),+ (+ TransactionEventType.AUTHORIZATION_FAILURE,+ [TransactionEventType.CHARGE_SUCCESS],+ ),+ (TransactionEventType.AUTHORIZATION_FAILURE, []),+ (TransactionEventType.REFUND_REVERSE, [TransactionEventType.REFUND_FAILURE]),+ (TransactionEventType.REFUND_REVERSE, []),+ (TransactionEventType.CHARGE_BACK, [TransactionEventType.CHARGE_FAILURE]),+ (TransactionEventType.CHARGE_BACK, []),+ ],+)+def test_get_transaction_event_amount_missing_matching_event(+ input_event_type,+ event_types_to_create,+ transaction_events_generator,+ transaction_item,+):+ # given+ amount = 10+ psp_reference = "xyz"+ if event_types_to_create:+ transaction_events_generator(+ transaction=transaction_item,+ psp_references=[+ psp_reference,+ ],+ types=event_types_to_create,+ amounts=[+ amount,+ ],+ )++ # when & then+ with pytest.raises(+ ValueError, match=f"Unable to deduce the amount for {input_event_type} event."+ ):+ get_transaction_event_amount(input_event_type, psp_reference)+++def test_get_transaction_event_amount_missing_matching_event_different_psp_reference(+ transaction_events_generator, transaction_item+):+ # given+ psp_reference = "xyz"+ transaction_events_generator(+ transaction=transaction_item,+ psp_references=[+ "123",+ ],+ types=[TransactionEventType.CHARGE_SUCCESS],+ amounts=[10],+ )+ event_type = TransactionEventType.CHARGE_FAILURE++ # when & then+ with pytest.raises(+ ValueError, match=f"Unable to deduce the amount for {event_type} event."+ ):+ get_transaction_event_amount(event_type, psp_reference)+++def test_get_transaction_event_amount_invalid_event_type(+ transaction_events_generator, transaction_item+):+ # given+ psp_reference = "xyz"+ transaction_events_generator(+ transaction=transaction_item,+ psp_references=[+ psp_reference,+ ],+ types=[TransactionEventType.CHARGE_FAILURE],+ amounts=[10],+ )+ event_type = TransactionEventType.CHARGE_SUCCESS++ # when & then+ with pytest.raises(+ ValueError, match=f"Unable to deduce the amount for {event_type} event."+ ):+ get_transaction_event_amount(event_type, psp_reference)+++def test_get_transaction_event_amount_for_info_event_type(+ transaction_events_generator, transaction_item+):+ # given+ psp_reference = "xyz"+ transaction_events_generator(+ transaction=transaction_item,+ psp_references=[+ "123",+ ],+ types=[TransactionEventType.CHARGE_SUCCESS],+ amounts=[10],+ )++ # when+ amount = get_transaction_event_amount(TransactionEventType.INFO, psp_reference)++ # then+ assert amount == 0diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 0396f744e0..47e3455255 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -1666,3 +1666,60 @@ def handle_transaction_process_session()data_to_return = response_data.get("data") if response_data else Nonereturn created_event, data_to_return+++def get_transaction_event_amount(event_type: str, psp_reference: str):+ """Deduce the transaction event amount if possible.++ - In case of missing amount for event INFO, use 0+ - In case of missing amount for *_FAILURE the amount is taken from *_SUCCESS or+ *_REQUEST event with the same pspReference.+ - In case of REFUND_REVERSE, the amount is taken from REFUND_SUCCESS with the same+ pspReference.+ - In case of CHARGEBACK the amount is taken from CHARGE_SUCCESS with the same+ pspReference.+ - If the specific event for the pspReference doesn't exist, the exception is raised.+ """+ if event_type == TransactionEventType.INFO:+ return Decimal(0)++ event_type_map = {+ TransactionEventType.CHARGE_FAILURE: [+ TransactionEventType.CHARGE_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_FAILURE,+ ],+ TransactionEventType.REFUND_FAILURE: [+ TransactionEventType.REFUND_SUCCESS,+ TransactionEventType.REFUND_REQUEST,+ TransactionEventType.CHARGE_SUCCESS,+ TransactionEventType.CHARGE_REQUEST,+ TransactionEventType.CHARGE_FAILURE,+ ],+ TransactionEventType.CANCEL_FAILURE: [+ TransactionEventType.CANCEL_SUCCESS,+ TransactionEventType.CANCEL_REQUEST,+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.AUTHORIZATION_REQUEST,+ TransactionEventType.AUTHORIZATION_FAILURE,+ ],+ TransactionEventType.AUTHORIZATION_FAILURE: [+ TransactionEventType.AUTHORIZATION_SUCCESS,+ TransactionEventType.AUTHORIZATION_REQUEST,+ ],+ TransactionEventType.REFUND_REVERSE: [TransactionEventType.REFUND_SUCCESS],+ TransactionEventType.CHARGE_BACK: [TransactionEventType.CHARGE_SUCCESS],+ }+ allowed_event_types = event_type_map.get(event_type, [])+ matched_event = (+ TransactionEvent.objects.filter(+ psp_reference=psp_reference, type__in=allowed_event_types+ )+ .order_by("-created_at")+ .first()+ )+ if matched_event is None:+ raise ValueError(f"Unable to deduce the amount for {event_type} event.")+ return matched_event.amount_value