Skip to content

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

Add missing `actions` field to transaction's webhook resonses (#12845)

Maciej Korycinski0023d106a7f6
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index e0f12671ca..4e17e8335b 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -40,6 +40,7 @@ class TransactionRequestEventResponse:
@dataclass
class TransactionRequestResponse:
psp_reference: Optional[str]
+ available_actions: Optional[List[str]] = None
event: Optional["TransactionRequestEventResponse"] = None
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index d12f4a1360..f5b9cca7e6 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1440,3 +1440,89 @@ def test_create_transaction_event_for_transaction_session_call_webhook_for_fully
flush_post_commit_hooks()
mock_order_fully_paid.assert_called_once_with(order_with_lines)
mock_order_updated.assert_called_once_with(order_with_lines)
+
+
+ "response_result,",
+ [
+ (TransactionEventType.AUTHORIZATION_REQUEST),
+ (TransactionEventType.AUTHORIZATION_SUCCESS),
+ (TransactionEventType.CHARGE_REQUEST),
+ (TransactionEventType.CHARGE_SUCCESS),
+ ],
+)
+def test_create_transaction_event_for_transaction_session_success_sets_actions(
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ response["actions"] = ["CANCEL", "CHARGE", "REFUND"]
+
+ transaction = transaction_item_generator()
+ 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 set(transaction.available_actions) == set(["refund", "charge", "cancel"])
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+)
+def test_create_transaction_event_for_transaction_session_failure_doesnt_set_actions(
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ response["actions"] = ["CANCEL", "CHARGE", "REFUND"]
+ transaction = transaction_item_generator(available_actions=["charge"])
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ amount_value=expected_amount,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ # 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.available_actions == ["charge"]
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index b8bedaf9a3..a0c4a9dfb4 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -31,6 +31,7 @@ from . import (
GatewayError,
PaymentError,
StorePaymentMethod,
+ TransactionAction,
TransactionEventType,
TransactionKind,
)
@@ -823,6 +824,18 @@ def parse_transaction_action_data(
logger.error(msg)
return None, msg
+ available_actions = response_data.get("actions", None)
+ if available_actions is not None:
+ possible_actions = {
+ str_to_enum(event_action): event_action
+ for event_action, _ in TransactionAction.CHOICES
+ }
+ available_actions = [
+ possible_actions[action]
+ for action in available_actions
+ if action in possible_actions
+ ]
+
parsed_event_data: dict = {}
error_field_msg: list[str] = []
parse_transaction_event_data(
@@ -845,6 +858,7 @@ def parse_transaction_action_data(
return (
TransactionRequestResponse(
psp_reference=psp_reference,
+ available_actions=available_actions,
event=TransactionRequestEventResponse(**parsed_event_data)
if parsed_event_data
else None,
@@ -1090,12 +1104,14 @@ def create_transaction_event_for_transaction_session(
request_event.amount_value = response_event.amount
request_event.psp_reference = response_event.psp_reference
request_event.include_in_calculations = True
+ request_event.app = app
request_event_update_fields.extend(
[
"type",
"amount_value",
"psp_reference",
"include_in_calculations",
+ "app",
]
)
event = request_event
@@ -1127,6 +1143,10 @@ def create_transaction_event_for_transaction_session(
previous_refunded_value = transaction_item.refunded_value
transaction_item.psp_reference = event.psp_reference
+ available_actions = transaction_request_response.available_actions
+ if available_actions is not None:
+ transaction_item.available_actions = available_actions
+
recalculate_transaction_amounts(transaction_item, save=False)
transaction_item.save(
update_fields=[
@@ -1139,6 +1159,7 @@ def create_transaction_event_for_transaction_session(
"refund_pending_value",
"cancel_pending_value",
"psp_reference",
+ "available_actions",
]
)
if transaction_item.order_id:
@@ -1193,7 +1214,24 @@ def create_transaction_event_from_request_and_webhook_response(
previous_authorized_value = transaction_item.authorized_value
previous_charged_value = transaction_item.charged_value
previous_refunded_value = transaction_item.refunded_value
- recalculate_transaction_amounts(transaction_item)
+ recalculate_transaction_amounts(transaction_item, save=False)
+ available_actions = transaction_request_response.available_actions
+ if available_actions is not None:
+ transaction_item.available_actions = available_actions
+
+ transaction_item.save(
+ update_fields=[
+ "available_actions",
+ "authorized_value",
+ "charged_value",
+ "refunded_value",
+ "canceled_value",
+ "authorize_pending_value",
+ "charge_pending_value",
+ "refund_pending_value",
+ "cancel_pending_value",
+ ]
+ )
if transaction_item.order_id:
# circular import
diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.py
index f9b96a41f9..dec621347f 100644
--- a/saleor/plugins/webhook/tests/test_tasks.py
+++ b/saleor/plugins/webhook/tests/test_tasks.py
@@ -703,6 +703,97 @@ def test_handle_transaction_request_task_calls_recalculation_of_amounts(
handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
# then
- mocked_recalculation.assert_called_once_with(transaction)
+ mocked_recalculation.assert_called_once_with(transaction, save=False)
transaction.refresh_from_db()
assert transaction.charged_value == event_amount
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_available_actions(
+ mocked_post_request,
+ transaction_item_generator,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_psp_reference = "psp:123:111"
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_SUCCESS
+
+ response_payload = {
+ "pspReference": request_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "actions": ["CHARGE", "REFUND", "CANCEL", "VOID", "INCORRECT_EVENT"],
+ }
+ mocked_webhook_response.text = json.dumps(response_payload)
+ mocked_webhook_response.content = json.dumps(response_payload)
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ request_event = transaction.events.create(type=TransactionEventType.CHARGE_REQUEST)
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=request_event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert TransactionEvent.objects.all().count() == 2
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST
+ ).count()
+ == 1
+ )
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).count()
+ == 1
+ )
+ success_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).first()
+ assert success_event
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == request_psp_reference
+ assert success_event.psp_reference == request_psp_reference
+ assert success_event.amount_value == event_amount
+
+ transaction.refresh_from_db()
+ assert set(transaction.available_actions) == set(
+ ["charge", "refund", "cancel", "void"]
+ )
+
+ mocked_post_request.assert_called_once_with(
+ target_url, data=payload.encode("utf-8"), headers=mock.ANY, timeout=mock.ANY
+ )