Skip to content

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

Add token field as optional argument to transaction mutations and query (#15368)

Tomasz Szymańskid4b01c936798
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 63815869db..84234dcb90 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -25,12 +25,13 @@ from .....permission.auth_filters import AuthorizationFilters
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_313, PREVIEW_FEATURE
+from ....core.descriptions import ADDED_IN_313, ADDED_IN_314, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.enums import TransactionEventReportErrorCode
from ....core.mutations import ModelMutation
-from ....core.scalars import PositiveDecimal
+from ....core.scalars import UUID, PositiveDecimal
from ....core.types import common as common_types
+from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import TransactionActionEnum, TransactionEventTypeEnum
from ...types import TransactionEvent, TransactionItem
@@ -55,8 +56,17 @@ class TransactionEventReport(ModelMutation):
class Arguments:
id = graphene.ID(
- description="The ID of the transaction.",
- required=True,
+ description=(
+ "The ID of the transaction. One of field id or token is required."
+ ),
+ required=False,
+ )
+ token = UUID(
+ description=(
+ "The token of the transaction. One of field id or token is required."
+ )
+ + ADDED_IN_314,
+ required=False,
)
psp_reference = graphene.String(
description="PSP Reference of the event to report.", required=True
@@ -162,21 +172,22 @@ class TransactionEventReport(ModelMutation):
info: ResolveInfo,
/,
*,
- id,
psp_reference,
type,
amount,
+ token=None,
+ id=None,
time=None,
external_url=None,
message=None,
available_actions=None,
):
+ validate_one_of_args_is_in_mutation("id", id, "token", token)
+ transaction = get_transaction_item(id, token)
user = info.context.user
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
- transaction = get_transaction_item(id)
-
if not check_if_requestor_has_access(
transaction=transaction, user=user, app=app
):
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.py
index 9cfd9cf59e..ed7f01c0f2 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py
@@ -17,14 +17,20 @@ from .....payment.utils import (
get_final_session_statuses,
handle_transaction_process_session,
)
-from ....core.descriptions import ADDED_IN_313, ADDED_IN_316, PREVIEW_FEATURE
+from ....core.descriptions import (
+ ADDED_IN_313,
+ ADDED_IN_314,
+ ADDED_IN_316,
+ PREVIEW_FEATURE,
+)
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.mutations import BaseMutation
-from ....core.scalars import JSON
+from ....core.scalars import JSON, UUID
from ....core.types import common as common_types
+from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import TransactionEvent, TransactionItem
-from .utils import clean_customer_ip_address
+from .utils import clean_customer_ip_address, get_transaction_item
if TYPE_CHECKING:
pass
@@ -44,8 +50,19 @@ class TransactionProcess(BaseMutation):
class Arguments:
id = graphene.ID(
- description="The ID of the transaction to process.",
- required=True,
+ description=(
+ "The ID of the transaction to process. "
+ "One of field id or token is required."
+ ),
+ required=False,
+ )
+ token = UUID(
+ description=(
+ "The token of the transaction to process. "
+ "One of field id or token is required."
+ )
+ + ADDED_IN_314,
+ required=False,
)
data = graphene.Argument(
JSON, description="The data that will be passed to the payment gateway."
@@ -165,11 +182,11 @@ class TransactionProcess(BaseMutation):
return app
@classmethod
- def perform_mutation(cls, root, info, *, id, data=None, customer_ip_address=None):
- transaction_item = cls.get_node_or_error(
- info, id, only_type="TransactionItem", field="token"
- )
- transaction_item = cast(payment_models.TransactionItem, transaction_item)
+ def perform_mutation(
+ cls, root, info, *, token=None, id=None, data=None, customer_ip_address=None
+ ):
+ validate_one_of_args_is_in_mutation("id", id, "token", token)
+ transaction_item = get_transaction_item(id, token)
events = transaction_item.events.all()
if processed_event := cls.get_already_processed_event(events):
return cls(
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index ddf56d9bc0..6a1dfd89d6 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -18,11 +18,12 @@ from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....checkout.types import Checkout
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_34, PREVIEW_FEATURE
+from ....core.descriptions import ADDED_IN_34, ADDED_IN_314, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.mutations import BaseMutation
-from ....core.scalars import PositiveDecimal
+from ....core.scalars import UUID, PositiveDecimal
from ....core.types import common as common_types
+from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import TransactionActionEnum
from ...types import TransactionItem
@@ -37,8 +38,17 @@ class TransactionRequestAction(BaseMutation):
class Arguments:
id = graphene.ID(
- description="The ID of the transaction.",
- required=True,
+ description=(
+ "The ID of the transaction. One of field id or token is required."
+ ),
+ required=False,
+ )
+ token = UUID(
+ description=(
+ "The token of the transaction. One of field id or token is required."
+ )
+ + ADDED_IN_314,
+ required=False,
)
action_type = graphene.Argument(
TransactionActionEnum,
@@ -132,10 +142,12 @@ class TransactionRequestAction(BaseMutation):
@classmethod
def perform_mutation(cls, root, info: ResolveInfo, /, **data):
- id = data["id"]
+ id = data.get("id")
+ token = data.get("token")
action_type = data["action_type"]
action_value = data.get("amount")
- transaction = get_transaction_item(id)
+ validate_one_of_args_is_in_mutation("id", id, "token", token)
+ transaction = get_transaction_item(id, token)
if transaction.order_id:
order = cast(Order, transaction.order)
channel = order.channel
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
index cbf2bfad56..03bee9e662 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
@@ -12,11 +12,13 @@ from .....payment.gateway import request_refund_action
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_315, PREVIEW_FEATURE
+from ....core.descriptions import ADDED_IN_314, ADDED_IN_315, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.enums import TransactionRequestRefundForGrantedRefundErrorCode
from ....core.mutations import BaseMutation
+from ....core.scalars import UUID
from ....core.types import common as common_types
+from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import TransactionItem
from .utils import get_transaction_item
@@ -30,8 +32,17 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
class Arguments:
id = graphene.ID(
- description="The ID of the transaction.",
- required=True,
+ description=(
+ "The ID of the transaction. One of field id or token is required."
+ ),
+ required=False,
+ )
+ token = UUID(
+ description=(
+ "The token of the transaction. One of field id or token is required."
+ )
+ + ADDED_IN_314,
+ required=False,
)
granted_refund_id = graphene.ID(
required=True,
@@ -50,9 +61,9 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
@classmethod
def clean_input(
- cls, info, transaction_id: str, granted_refund_id: str
+ cls, info, transaction_id: str, token: UUID, granted_refund_id: str
) -> tuple[payment_models.TransactionItem, order_models.OrderGrantedRefund]:
- transaction_item = get_transaction_item(transaction_id)
+ transaction_item = get_transaction_item(transaction_id, token)
granted_refund = cls.get_node_or_error(
info,
granted_refund_id,
@@ -83,9 +94,12 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, root, info: ResolveInfo, /, id, granted_refund_id
+ cls, root, info: ResolveInfo, /, granted_refund_id, token=None, id=None
):
- transaction_item, granted_refund = cls.clean_input(info, id, granted_refund_id)
+ validate_one_of_args_is_in_mutation("id", id, "token", token)
+ transaction_item, granted_refund = cls.clean_input(
+ info, id, token, granted_refund_id
+ )
order = granted_refund.order
channel = order.channel
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_update.py b/saleor/graphql/payment/mutations/transaction/transaction_update.py
index 60f88924b1..3f3b2e6b06 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_update.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_update.py
@@ -24,9 +24,11 @@ from .....permission.auth_filters import AuthorizationFilters
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_34, PREVIEW_FEATURE
+from ....core.descriptions import ADDED_IN_34, ADDED_IN_314, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
+from ....core.scalars import UUID
from ....core.types import common as common_types
+from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import TransactionItem
from ...utils import check_if_requestor_has_access
@@ -51,8 +53,17 @@ class TransactionUpdate(TransactionCreate):
class Arguments:
id = graphene.ID(
- description="The ID of the transaction.",
- required=True,
+ description=(
+ "The ID of the transaction. One of field id or token is required."
+ ),
+ required=False,
+ )
+ token = UUID(
+ description=(
+ "The token of the transaction. One of field id or token is required."
+ )
+ + ADDED_IN_314,
+ required=False,
)
transaction = TransactionUpdateInput(
description="Input data required to create a new transaction object.",
@@ -174,19 +185,21 @@ class TransactionUpdate(TransactionCreate):
transaction_data["app_identifier"] = app.identifier
@classmethod
- def perform_mutation( # type: ignore[override]
+ def perform_mutation(
cls,
_root,
info: ResolveInfo,
/,
*,
- id: str,
+ token=None,
+ id=None,
transaction=None,
transaction_event=None,
):
- app = get_app_promise(info.context).get()
+ validate_one_of_args_is_in_mutation("id", id, "token", token)
+ instance = get_transaction_item(id, token)
user = info.context.user
- instance = get_transaction_item(id)
+ app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
cls.check_can_update(
diff --git a/saleor/graphql/payment/mutations/transaction/utils.py b/saleor/graphql/payment/mutations/transaction/utils.py
index adc5078e95..6be73f2caa 100644
--- a/saleor/graphql/payment/mutations/transaction/utils.py
+++ b/saleor/graphql/payment/mutations/transaction/utils.py
@@ -16,16 +16,19 @@ if TYPE_CHECKING:
pass
-def get_transaction_item(id: str) -> payment_models.TransactionItem:
- """Get transaction based on global ID.
+def get_transaction_item(id, token) -> payment_models.TransactionItem:
+ """Get transaction based on token or global ID.
The transactions created before 3.13 were using the `id` field as a graphql ID.
From 3.13, the `token` is used as a graphql ID. All transactionItems created
before 3.13 will use an `int` id as an identification.
"""
- _, db_id = from_global_id_or_error(
- global_id=id, only_type=TransactionItem, raise_error=True
- )
+ if token:
+ db_id = str(token)
+ else:
+ _, db_id = from_global_id_or_error(
+ global_id=id, only_type=TransactionItem, raise_error=True
+ )
if db_id.isdigit():
query_params = {"id": db_id, "use_old_id": True}
else:
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index eedde49fc8..fe43ac8d69 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -6,6 +6,7 @@ from ..core.connection import create_connection_slice, filter_connection_queryse
from ..core.descriptions import ADDED_IN_36, PREVIEW_FEATURE
from ..core.doc_category import DOC_CATEGORY_PAYMENTS
from ..core.fields import FilterConnectionField, PermissionsField
+from ..core.scalars import UUID
from ..core.utils import from_global_id_or_error
from .filters import PaymentFilterInput
from .mutations import (
@@ -56,7 +57,20 @@ class PaymentQueries(graphene.ObjectType):
TransactionItem,
description="Look up a transaction by ID." + ADDED_IN_36 + PREVIEW_FEATURE,
id=graphene.Argument(
- graphene.ID, description="ID of a transaction.", required=True
+ graphene.ID,
+ description=(
+ "ID of a transaction. Either it or token is required "
+ "to fetch the transaction data."
+ ),
+ required=False,
+ ),
+ token=graphene.Argument(
+ UUID,
+ description=(
+ "Token of a transaction. Either it or ID is required "
+ "to fetch the transaction data."
+ ),
+ required=False,
),
permissions=[
PaymentPermissions.HANDLE_PAYMENTS,
@@ -77,9 +91,14 @@ class PaymentQueries(graphene.ObjectType):
@staticmethod
def resolve_transaction(_root, info: ResolveInfo, **kwargs):
- _, id = from_global_id_or_error(kwargs["id"], TransactionItem)
- if not id:
+ id = kwargs.get("id")
+ token = kwargs.get("token")
+ if id is None and token is None:
return None
+ # If token is provided we ignore the id input.
+ if token:
+ return resolve_transaction(info, str(token))
+ _, id = from_global_id_or_error(id, TransactionItem) # type: ignore[arg-type]
return resolve_transaction(info, id)
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 4df49549d4..cd26d26e77 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -99,7 +99,7 @@ def test_transaction_event_report_by_app(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -149,6 +149,84 @@ def test_transaction_event_report_by_app(
assert event.user is None
+def test_transaction_event_report_by_app_via_token(
+ 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 = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ variables = {
+ "token": transaction.token,
+ "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(
+ $token: UUID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ token: $token
+ 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
+
+
def test_transaction_event_report_by_user(
staff_api_client, permission_manage_payments, staff_user, transaction_item_generator
):
@@ -177,7 +255,7 @@ def test_transaction_event_report_by_user(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -250,7 +328,7 @@ def test_transaction_event_report_by_another_user(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -316,7 +394,7 @@ def test_transaction_event_report_no_permission(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -368,7 +446,7 @@ def test_transaction_event_report_called_by_non_app_owner(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -410,7 +488,7 @@ def test_transaction_event_report_called_by_non_user_owner(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -469,7 +547,7 @@ def test_transaction_event_report_event_already_exists(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -704,7 +782,7 @@ def test_transaction_event_report_incorrect_amount_for_already_existing(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -784,7 +862,7 @@ def test_transaction_event_report_calls_amount_recalculations(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -847,7 +925,7 @@ def test_transaction_event_updates_order_total_charged(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -903,7 +981,7 @@ def test_transaction_event_updates_order_total_authorized(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -959,7 +1037,7 @@ def test_transaction_event_updates_search_vector(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1020,7 +1098,7 @@ def test_transaction_event_report_authorize_event_already_exists(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1097,7 +1175,7 @@ def test_transaction_event_updates_checkout_payment_statuses(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1159,7 +1237,7 @@ def test_transaction_event_updates_checkout_last_transaction_modified_at(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1223,7 +1301,7 @@ def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1287,7 +1365,7 @@ def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amount
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1345,7 +1423,7 @@ def test_transaction_event_report_with_info_event(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1419,7 +1497,7 @@ def test_transaction_event_report_accepts_old_id_for_old_transaction(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1500,7 +1578,7 @@ def test_transaction_event_report_doesnt_accept_old_id_for_new_transaction(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1567,7 +1645,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_paid(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1623,7 +1701,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_partially_pai
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1678,7 +1756,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_partially_aut
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1733,7 +1811,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_authori
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1790,7 +1868,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_refunde
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1847,7 +1925,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_partially_ref
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1904,7 +1982,7 @@ def test_transaction_event_report_by_app_assign_app_owner(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
@@ -1977,7 +2055,7 @@ def test_transaction_event_report_assign_transaction_psp_reference_if_missing(
MUTATION_DATA_FRAGMENT
+ """
mutation TransactionEventReport(
- $id: ID!
+ $id: ID
$type: TransactionEventTypeEnum!
$amount: PositiveDecimal!
$pspReference: String!
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index abdf213982..aede05c3d4 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -26,7 +26,7 @@ from ....tests.utils import assert_no_permission, get_graphql_content
TRANSACTION_PROCESS = """
mutation TransactionProcess(
- $id: ID!,
+ $id: ID
$data: JSON
$customerIpAddress: String
@@ -81,6 +81,61 @@ mutation TransactionProcess(
}
"""
+TRANSACTION_PROCESS_BY_TOKEN = """
+mutation TransactionProcess(
+ $token: UUID
+ $data: JSON
+) {
+ transactionProcess(
+ token: $token
+ data: $data
+ ) {
+ data
+ transaction {
+ id
+ token
+ authorizedAmount {
+ currency
+ amount
+ }
+ chargedAmount {
+ currency
+ amount
+ }
+ chargePendingAmount {
+ amount
+ currency
+ }
+ authorizePendingAmount {
+ amount
+ currency
+ }
+ }
+ transactionEvent {
+ id
+ amount {
+ currency
+ amount
+ }
+ type
+ createdBy {
+ ... on App {
+ id
+ }
+ }
+ pspReference
+ message
+ externalUrl
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
def _assert_fields(
content,
@@ -364,6 +419,72 @@ def test_for_checkout_with_data(
assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_for_checkout_with_data_via_token(
+ mocked_process,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout_with_prices.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
+ mocked_process.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+ expected_data = {"some": "json-data"}
+ variables = {
+ "token": transaction_item.token,
+ "data": expected_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS_BY_TOKEN, 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_process=mocked_process,
+ charged_value=expected_amount,
+ data=expected_data,
+ returned_data=expected_response["data"],
+ )
+ assert content["data"]["transactionProcess"]["transaction"]["token"] == str(
+ transaction_item.token
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")
def test_for_order_with_data(
mocked_process,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index e961cc490a..9939fc4ee9 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -16,8 +16,8 @@ from ...enums import TransactionActionEnum
MUTATION_TRANSACTION_REQUEST_ACTION = """
mutation TransactionRequestAction(
- $id: ID!,
- $action_type: TransactionActionEnum!,
+ $id: ID
+ $action_type: TransactionActionEnum!
$amount: PositiveDecimal
){
transactionRequestAction(
@@ -53,6 +53,45 @@ mutation TransactionRequestAction(
}
"""
+MUTATION_TRANSACTION_REQUEST_ACTION_BY_TOKEN = """
+mutation TransactionRequestAction(
+ $token: UUID
+ $action_type: TransactionActionEnum!
+ $amount: PositiveDecimal
+ ){
+ transactionRequestAction(
+ token: $token,
+ actionType: $action_type,
+ amount: $amount
+ ){
+ transaction{
+ id
+ actions
+ pspReference
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ chargedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
def test_transaction_request_action_missing_permission(
app_api_client, order_with_lines, permission_manage_orders
@@ -231,6 +270,89 @@ def test_transaction_request_charge_for_order(
)
+ ("charge_amount", "expected_called_charge_amount"),
+ [
+ (Decimal("8.00"), Decimal("8.00")),
+ (None, Decimal("10.00")),
+ (Decimal("100"), Decimal("10.00")),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_transaction_request_charge_for_order_via_token(
+ mocked_payment_action_request,
+ mocked_is_active,
+ charge_amount,
+ expected_called_charge_amount,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ app,
+):
+ # given
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ )
+ mocked_is_active.return_value = False
+
+ transaction = TransactionItem.objects.create(
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "cancel"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+
+ variables = {
+ "token": transaction.token,
+ "action_type": TransactionActionEnum.CHARGE.name,
+ "amount": charge_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION_BY_TOKEN,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST,
+ ).first()
+
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=expected_called_charge_amount,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == expected_called_charge_amount
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=expected_called_charge_amount,
+ )
+
+
@pytest.mark.parametrize(
("refund_amount", "expected_called_refund_amount"),
[
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
index 39133b340c..9b9d4c263d 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
@@ -12,7 +12,7 @@ from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND = """
-mutation TransactionRequestRefundForGrantedRefund($id: ID!, $grantedRefundID: ID!) {
+mutation TransactionRequestRefundForGrantedRefund($id: ID, $grantedRefundID: ID!) {
transactionRequestRefundForGrantedRefund(id: $id, grantedRefundId: $grantedRefundID) {
transaction {
id
@@ -32,6 +32,29 @@ mutation TransactionRequestRefundForGrantedRefund($id: ID!, $grantedRefundID: ID
}
"""
+TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND_BY_TOKEN = """
+mutation TransactionRequestRefundForGrantedRefund($token: UUID, $grantedRefundID: ID!) {
+ transactionRequestRefundForGrantedRefund(
+ token: $token, grantedRefundId: $grantedRefundID
+ ) {
+ transaction {
+ id
+ events {
+ type
+ amount {
+ amount
+ }
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
def test_missing_permission_for_app(
app_api_client,
@@ -313,6 +336,70 @@ def test_triggers_refund_request_for_app(
)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_triggers_refund_request_for_app_via_token(
+ mocked_payment_action_request,
+ mocked_is_active,
+ app_api_client,
+ order_with_lines,
+ permission_manage_payments,
+ transaction_item_generator,
+ app,
+):
+ # given
+ app.permissions.set([permission_manage_payments])
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ charged_value=order_with_lines.total_gross.amount,
+ app=app,
+ )
+ expected_refund_amount = Decimal("10.00")
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=expected_refund_amount
+ )
+
+ variables = {
+ "token": transaction_item.token,
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND_BY_TOKEN,
+ variables,
+ )
+
+ get_graphql_content(response)
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction_item,
+ action_type=TransactionAction.REFUND,
+ action_value=expected_refund_amount,
+ event=request_event,
+ transaction_app_owner=app,
+ granted_refund=granted_refund,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction_item,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_refund_amount,
+ )
+
+
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
def test_triggers_refund_request_for_staff_user(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 67a551fe79..0fa383e945 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -21,8 +21,8 @@ TEST_SERVER_DOMAIN = "testserver.com"
MUTATION_TRANSACTION_UPDATE = """
mutation TransactionUpdate(
- $id: ID!,
- $transaction_event: TransactionEventInput,
+ $id: ID
+ $transaction_event: TransactionEventInput
$transaction: TransactionUpdateInput
){
transactionUpdate(
@@ -100,6 +100,87 @@ mutation TransactionUpdate(
}
"""
+MUTATION_TRANSACTION_UPDATE_BY_TOKEN = """
+mutation TransactionUpdate(
+ $token: UUID
+ $transaction_event: TransactionEventInput
+ $transaction: TransactionUpdateInput
+ ){
+ transactionUpdate(
+ token: $token,
+ transactionEvent: $transaction_event,
+ transaction: $transaction
+ ){
+ transaction{
+ id
+ actions
+ pspReference
+ name
+ message
+ modifiedAt
+ createdAt
+ externalUrl
+ authorizedAmount{
+ amount
+ currency
+ }
+ canceledAmount{
+ currency
+ amount
+ }
+ chargedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ privateMetadata{
+ key
+ value
+ }
+ metadata{
+ key
+ value
+ }
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
+ events{
+ pspReference
+ message
+ createdAt
+ externalUrl
+ amount{
+ amount
+ currency
+ }
+ type
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
def test_only_owner_can_update_its_transaction_by_app(
transaction_item_created_by_app,
@@ -275,6 +356,35 @@ def test_transaction_update_name_by_app(
assert transaction.name == name
+def test_transaction_update_name_by_app_via_token(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+ name = "New credit card"
+
+ variables = {
+ "token": transaction.token,
+ "transaction": {
+ "name": name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE_BY_TOKEN,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["name"] == name
+ assert transaction.name == name
+
+
def test_transaction_update_message_by_app(
transaction_item_created_by_app, permission_manage_payments, app_api_client
):
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 01987931d5..2583f0f922 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -26,6 +26,7 @@ from ..core.descriptions import (
from ..core.doc_category import DOC_CATEGORY_PAYMENTS
from ..core.fields import JSONString, PermissionsField
from ..core.scalars import JSON
+from ..core.scalars import UUID as UUIDScalar
from ..core.tracing import traced_resolver
from ..core.types import BaseObjectType, ModelObjectType, Money, NonNullList
from ..meta.permissions import public_payment_permissions
@@ -408,6 +409,9 @@ class TransactionEvent(ModelObjectType[models.TransactionEvent]):
class TransactionItem(ModelObjectType[models.TransactionItem]):
+ token = graphene.Field(
+ UUIDScalar, description="The transaction token." + ADDED_IN_314, required=True
+ )
created_at = graphene.DateTime(
required=True,
description="Date and time at which payment transaction was created.",
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f8f9b3f425..eb3738ade8 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -683,8 +683,15 @@ type Query {
Requires one of the following permissions: HANDLE_PAYMENTS.
"""
transaction(
- """ID of a transaction."""
- id: ID!
+ """
+ ID of a transaction. Either it or token is required to fetch the transaction data.
+ """
+ id: ID
+
+ """
+ Token of a transaction. Either it or ID is required to fetch the transaction data.
+ """
+ token: UUID
): TransactionItem @doc(category: "Payments")
"""Look up a page by ID or slug."""
@@ -11260,6 +11267,13 @@ type TransactionItem implements Node & ObjectWithMetadata @doc(category: "Paymen
"""
metafields(keys: [String!]): Metadata
+ """
+ The transaction token.
+
+ Added in Saleor 3.14.
+ """
+ token: UUID!
+
"""Date and time at which payment transaction was created."""
createdAt: DateTime!
@@ -16542,8 +16556,15 @@ 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.
"""
transactionUpdate(
- """The ID of the transaction."""
- id: ID!
+ """The ID of the transaction. One of field id or token is required."""
+ id: ID
+
+ """
+ The token of the transaction. One of field id or token is required.
+
+ Added in Saleor 3.14.
+ """
+ token: UUID
"""Input data required to create a new transaction object."""
transaction: TransactionUpdateInput
@@ -16570,8 +16591,15 @@ type Mutation {
"""
amount: PositiveDecimal
- """The ID of the transaction."""
- id: ID!
+ """The ID of the transaction. One of field id or token is required."""
+ id: ID
+
+ """
+ The token of the transaction. One of field id or token is required.
+
+ Added in Saleor 3.14.
+ """
+ token: UUID
): TransactionRequestAction @doc(category: "Payments")
"""
@@ -16587,8 +16615,15 @@ type Mutation {
"""The ID of the granted refund."""
grantedRefundId: ID!
- """The ID of the transaction."""
- id: ID!
+ """The ID of the transaction. One of field id or token is required."""
+ id: ID
+
+ """
+ The token of the transaction. One of field id or token is required.
+
+ Added in Saleor 3.14.
+ """
+ token: UUID
): TransactionRequestRefundForGrantedRefund @doc(category: "Payments")
"""
@@ -16612,8 +16647,8 @@ type Mutation {
"""
externalUrl: String
- """The ID of the transaction."""
- id: ID!
+ """The ID of the transaction. One of field id or token is required."""
+ id: ID
"""The message related to the event."""
message: String
@@ -16626,6 +16661,13 @@ type Mutation {
"""
time: DateTime
+ """
+ The token of the transaction. One of field id or token is required.
+
+ Added in Saleor 3.14.
+ """
+ token: UUID
+
"""Current status of the event to report."""
type: TransactionEventTypeEnum!
): TransactionEventReport @doc(category: "Payments")
@@ -16707,8 +16749,17 @@ type Mutation {
"""The data that will be passed to the payment gateway."""
data: JSON
- """The ID of the transaction to process."""
- id: ID!
+ """
+ The ID of the transaction to process. One of field id or token is required.
+ """
+ id: ID
+
+ """
+ The token of the transaction to process. One of field id or token is required.
+
+ Added in Saleor 3.14.
+ """
+ token: UUID
): TransactionProcess @doc(category: "Payments")
"""