Skip to content

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

Allow providing `metadata` in `TransactionEventReport` mutation (#16755)

Iga Karbowiak39443490a020
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 35f0afe3f4..3f93b2b149 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -1,4 +1,4 @@
-from typing import Optional, cast
+from typing import TYPE_CHECKING, Optional, cast
import graphene
from django.core.exceptions import ValidationError
@@ -9,6 +9,7 @@ from .....checkout.actions import transaction_amounts_for_checkout_updated
from .....core.exceptions import PermissionDenied
from .....core.prices import quantize_price
from .....core.tracing import traced_atomic_transaction
+from .....core.utils.events import call_event
from .....order import models as order_models
from .....order.actions import order_transaction_updated
from .....order.fetch import fetch_order_info
@@ -28,21 +29,33 @@ from .....payment.utils import (
)
from .....permission.auth_filters import AuthorizationFilters
from .....permission.enums import PaymentPermissions
+from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_313, ADDED_IN_314, PREVIEW_FEATURE
+from ....core.descriptions import (
+ ADDED_IN_313,
+ ADDED_IN_314,
+ ADDED_IN_317,
+ PREVIEW_FEATURE,
+)
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.enums import TransactionEventReportErrorCode
from ....core.mutations import ModelMutation
from ....core.scalars import UUID, DateTime, PositiveDecimal
+from ....core.types import NonNullList
from ....core.types import common as common_types
+from ....core.utils import WebhookEventInfo
from ....core.validators import validate_one_of_args_is_in_mutation
+from ....meta.inputs import MetadataInput
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import TransactionActionEnum, TransactionEventTypeEnum
from ...types import TransactionEvent, TransactionItem
from ...utils import check_if_requestor_has_access
from .utils import get_transaction_item
+if TYPE_CHECKING:
+ from .....plugins.manager import PluginsManager
+
class TransactionEventReport(ModelMutation):
already_processed = graphene.Boolean(
@@ -108,6 +121,21 @@ class TransactionEventReport(ModelMutation):
graphene.NonNull(TransactionActionEnum),
description="List of all possible actions for the transaction",
)
+ transaction_metadata = NonNullList(
+ MetadataInput,
+ description=(
+ "Fields required to update the transaction metadata." + ADDED_IN_317
+ ),
+ required=False,
+ )
+ transaction_private_metadata = NonNullList(
+ MetadataInput,
+ description=(
+ "Fields required to update the transaction private metadata."
+ + ADDED_IN_317
+ ),
+ required=False,
+ )
class Meta:
description = (
@@ -126,6 +154,30 @@ class TransactionEventReport(ModelMutation):
model = payment_models.TransactionEvent
object_type = TransactionEvent
auto_permission_message = False
+ support_meta_field = True
+ support_private_meta_field = True
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.TRANSACTION_ITEM_METADATA_UPDATED,
+ description=(
+ "Optionally called when transaction's metadata was updated."
+ ),
+ ),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
+ description=(
+ "Optionally called when the checkout charge status "
+ "changed to `FULL` or `OVERCHARGED`."
+ ),
+ ),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.ORDER_UPDATED,
+ description=(
+ "Optionally called when the transaction is related to the order "
+ "and the order was updated."
+ ),
+ ),
+ ]
@classmethod
def _update_mutation_arguments_and_fields(cls, arguments, fields):
@@ -134,10 +186,13 @@ class TransactionEventReport(ModelMutation):
@classmethod
def update_transaction(
cls,
+ manager: "PluginsManager",
transaction: payment_models.TransactionItem,
transaction_event: payment_models.TransactionEvent,
available_actions: Optional[list[str]] = None,
app: Optional["App"] = None,
+ metadata: Optional[list[dict]] = None,
+ private_metadata: Optional[list[dict]] = None,
):
fields_to_update = [
"authorized_value",
@@ -149,6 +204,8 @@ class TransactionEventReport(ModelMutation):
"refund_pending_value",
"cancel_pending_value",
"modified_at",
+ "metadata",
+ "private_metadata",
]
if (
@@ -176,6 +233,8 @@ class TransactionEventReport(ModelMutation):
fields_to_update.append("app")
fields_to_update.append("app_identifier")
transaction.save(update_fields=fields_to_update)
+ if metadata:
+ call_event(manager.transaction_item_metadata_updated, transaction)
@classmethod
def get_related_granted_refund(
@@ -235,6 +294,8 @@ class TransactionEventReport(ModelMutation):
external_url=None,
message=None,
available_actions=None,
+ transaction_metadata: Optional[list[dict]] = None,
+ transaction_private_metadata: Optional[list[dict]] = None,
):
validate_one_of_args_is_in_mutation("id", id, "token", token)
transaction = get_transaction_item(id, token)
@@ -286,6 +347,9 @@ class TransactionEventReport(ModelMutation):
transaction_event, transaction_event_data
)
+ cls.validate_and_update_metadata(
+ transaction, transaction_metadata, transaction_private_metadata
+ )
cls.clean_instance(info, transaction_event)
if available_actions is not None:
@@ -335,10 +399,13 @@ class TransactionEventReport(ModelMutation):
previous_charged_value = transaction.charged_value
previous_refunded_value = transaction.refunded_value
cls.update_transaction(
+ manager,
transaction,
transaction_event,
available_actions=available_actions,
app=app,
+ metadata=transaction_metadata,
+ private_metadata=transaction_private_metadata,
)
if transaction.order_id:
order = cast(order_models.Order, transaction.order)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index b1e34dc345..079ce65fa1 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -42,6 +42,14 @@ fragment TransactionEventData on TransactionEventReport {
id
}
}
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
}
transactionEvent {
id
@@ -2541,3 +2549,223 @@ def test_transaction_event_report_missing_amount_error_raised(
assert len(errors) == 1
assert errors[0]["field"] == "amount"
assert errors[0]["code"] == TransactionEventReportErrorCode.REQUIRED.name
+
+
+@patch("saleor.plugins.manager.PluginsManager.transaction_item_metadata_updated")
+def test_transaction_event_report_update_transaction_metadata(
+ transaction_item_metadata_updated_mock,
+ 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"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ metadata = {"key": "test key", "value": "test value"}
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "transactionMetadata": [metadata],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $transactionMetadata: [MetadataInput!]
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ transactionMetadata: $transactionMetadata
+ ) {
+ ...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
+
+ transaction_data = transaction_report_data["transaction"]
+ assert len(transaction_data["metadata"]) == 1
+ assert transaction_data["metadata"][0] == metadata
+
+ 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.transaction == transaction
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
+ transaction_item_metadata_updated_mock.assert_called_once_with(transaction)
+
+
+@patch("saleor.plugins.manager.PluginsManager.transaction_item_metadata_updated")
+def test_transaction_event_report_metadata_not_provided(
+ transaction_item_metadata_updated_mock,
+ 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"
+ 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,
+ "transactionMetadata": [],
+ "transactionPrivateMetadata": [],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $transactionMetadata: [MetadataInput!]
+ $transactionPrivateMetadata: [MetadataInput!]
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ transactionMetadata: $transactionMetadata
+ transactionPrivateMetadata: $transactionPrivateMetadata
+ ) {
+ ...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
+
+ transaction_data = transaction_report_data["transaction"]
+ assert len(transaction_data["metadata"]) == 0
+
+ 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.transaction == transaction
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
+ transaction_item_metadata_updated_mock.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.transaction_item_metadata_updated")
+def test_transaction_event_report_update_transaction_private_metadata(
+ transaction_item_metadata_updated_mock,
+ 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"
+ amount = Decimal("11.00")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ private_metadata = {"key": "test key", "value": "test value"}
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "transactionPrivateMetadata": [private_metadata],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $transactionPrivateMetadata: [MetadataInput!]
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ transactionPrivateMetadata: $transactionPrivateMetadata
+ ) {
+ ...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
+
+ transaction_data = transaction_report_data["transaction"]
+ assert len(transaction_data["privateMetadata"]) == 1
+ assert transaction_data["privateMetadata"][0] == private_metadata
+
+ 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.transaction == transaction
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
+ transaction_item_metadata_updated_mock.assert_not_called()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f8261304e1..c4ea3f08aa 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -17029,6 +17029,11 @@ type Mutation {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
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.
+
+ Triggers the following webhook events:
+ - TRANSACTION_ITEM_METADATA_UPDATED (async): Optionally called when transaction's metadata was updated.
+ - CHECKOUT_FULLY_PAID (async): Optionally called when the checkout charge status changed to `FULL` or `OVERCHARGED`.
+ - ORDER_UPDATED (async): Optionally called when the transaction is related to the order and the order was updated.
"""
transactionEventReport(
"""
@@ -17067,9 +17072,23 @@ type Mutation {
"""
token: UUID
+ """
+ Fields required to update the transaction metadata.
+
+ Added in Saleor 3.17.
+ """
+ transactionMetadata: [MetadataInput!]
+
+ """
+ Fields required to update the transaction private metadata.
+
+ Added in Saleor 3.17.
+ """
+ transactionPrivateMetadata: [MetadataInput!]
+
"""Current status of the event to report."""
type: TransactionEventTypeEnum!
- ): TransactionEventReport @doc(category: "Payments")
+ ): TransactionEventReport @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [TRANSACTION_ITEM_METADATA_UPDATED, CHECKOUT_FULLY_PAID, ORDER_UPDATED], syncEvents: [])
"""
Initializes a payment gateway session. It triggers the webhook `PAYMENT_GATEWAY_INITIALIZE_SESSION`, to the requested `paymentGateways`. If `paymentGateways` is not provided, the webhook will be send to all subscribed payment gateways. There is a limit of 100 transaction items per checkout / order.
@@ -24904,8 +24923,13 @@ Added in Saleor 3.13.
Note: this API is currently in Feature Preview and can be subject to changes at later point.
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.
+
+Triggers the following webhook events:
+- TRANSACTION_ITEM_METADATA_UPDATED (async): Optionally called when transaction's metadata was updated.
+- CHECKOUT_FULLY_PAID (async): Optionally called when the checkout charge status changed to `FULL` or `OVERCHARGED`.
+- ORDER_UPDATED (async): Optionally called when the transaction is related to the order and the order was updated.
"""
-type TransactionEventReport @doc(category: "Payments") {
+type TransactionEventReport @doc(category: "Payments") @webhookEventsInfo(asyncEvents: [TRANSACTION_ITEM_METADATA_UPDATED, CHECKOUT_FULLY_PAID, ORDER_UPDATED], syncEvents: []) {
"""Defines if the reported event hasn't been processed earlier."""
alreadyProcessed: Boolean