Skip to content

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

Add query for transaction item and extend transaction item type with order (#10154)

Iga Karbowiakb19423a86e9f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd21a3f575..4716a01277 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Add `VoucherFilter.ids` filter - #10157 by @Jakubkuc
- Allow values of different attributes to share the same slug - #10138 by @IKarbowiak
+- Add query for transaction item and extend transaction item type with order - #10154 by @IKarbowiak
- Fix inconsistent beat scheduling and compatibility with db scheduler - #10185 by @NyanKiyoshi<br/>
This fixes the following bugs:
- `tick()` could decide to never schedule anything else than `send-sale-toggle-notifications` if `send-sale-toggle-notifications` doesn't return `is_due = False` (stuck forever until beat restart or a `is_due = True`)
diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.py
index e853e4fc34..fe9a29cc97 100644
--- a/saleor/graphql/payment/resolvers.py
+++ b/saleor/graphql/payment/resolvers.py
@@ -7,3 +7,7 @@ def resolve_payment_by_id(id):
def resolve_payments(info):
return models.Payment.objects.all()
+
+
+def resolve_transaction(id):
+ return models.TransactionItem.objects.filter(id=id).first()
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index 33a3649b5a..fd1f8288cc 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -1,7 +1,8 @@
import graphene
-from ...core.permissions import OrderPermissions
+from ...core.permissions import OrderPermissions, PaymentPermissions
from ..core.connection import create_connection_slice, filter_connection_queryset
+from ..core.descriptions import ADDED_IN_36, PREVIEW_FEATURE
from ..core.fields import FilterConnectionField, PermissionsField
from ..core.utils import from_global_id_or_error
from .filters import PaymentFilterInput
@@ -15,8 +16,8 @@ from .mutations import (
TransactionRequestAction,
TransactionUpdate,
)
-from .resolvers import resolve_payment_by_id, resolve_payments
-from .types import Payment, PaymentCountableConnection
+from .resolvers import resolve_payment_by_id, resolve_payments, resolve_transaction
+from .types import Payment, PaymentCountableConnection, TransactionItem
class PaymentQueries(graphene.ObjectType):
@@ -38,6 +39,16 @@ class PaymentQueries(graphene.ObjectType):
OrderPermissions.MANAGE_ORDERS,
],
)
+ transaction = PermissionsField(
+ 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
+ ),
+ permissions=[
+ PaymentPermissions.HANDLE_PAYMENTS,
+ ],
+ )
@staticmethod
def resolve_payment(_root, _info, **data):
@@ -50,6 +61,11 @@ class PaymentQueries(graphene.ObjectType):
qs = filter_connection_queryset(qs, kwargs)
return create_connection_slice(qs, info, kwargs, PaymentCountableConnection)
+ @staticmethod
+ def resolve_transaction(_root, info, **kwargs):
+ _, id = from_global_id_or_error(kwargs["id"], TransactionItem)
+ return resolve_transaction(id)
+
class PaymentMutations(graphene.ObjectType):
payment_capture = PaymentCapture.Field()
diff --git a/saleor/graphql/payment/tests/queries/test_transaction.py b/saleor/graphql/payment/tests/queries/test_transaction.py
new file mode 100644
index 0000000000..49385b8f64
--- /dev/null
+++ b/saleor/graphql/payment/tests/queries/test_transaction.py
@@ -0,0 +1,141 @@
+import graphene
+
+from .....payment.models import TransactionEvent
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+TRANSACTION_QUERY = """
+ query transaction($id: ID!){
+ transaction(id: $id) {
+ id
+ createdAt
+ actions
+ authorizedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ chargedAmount{
+ currency
+ amount
+ }
+ events{
+ id
+ }
+ status
+ type
+ reference
+ order {
+ id
+ }
+ }
+ }
+"""
+
+
+def _assert_transaction_fields(content, transaction_item, event):
+ data = content["data"]["transaction"]
+ assert data["createdAt"] == transaction_item.created_at.isoformat()
+ assert data["actions"] == [
+ action.upper() for action in transaction_item.available_actions
+ ]
+ assert (
+ data["authorizedAmount"]["amount"] == transaction_item.amount_authorized.amount
+ )
+ assert data["refundedAmount"]["amount"] == transaction_item.amount_refunded.amount
+ assert data["voidedAmount"]["amount"] == transaction_item.amount_voided.amount
+ assert data["chargedAmount"]["amount"] == transaction_item.amount_charged.amount
+ assert len(data["events"]) == 1
+ assert data["events"][0]["id"] == graphene.Node.to_global_id(
+ "TransactionEvent", event.id
+ )
+ assert data["status"] == transaction_item.status
+ assert data["type"] == transaction_item.type
+ if transaction_item.order_id:
+ assert data["order"]["id"] == graphene.Node.to_global_id(
+ "Order", transaction_item.order.id
+ )
+ else:
+ assert data["order"] is None
+
+
+def test_transaction_query_by_app(
+ app_api_client, transaction_item, permission_manage_payments
+):
+ # given
+ event = TransactionEvent.objects.create(transaction=transaction_item)
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields(content, transaction_item, event)
+
+
+def test_transaction_query_no_order(
+ app_api_client, transaction_item, permission_manage_payments
+):
+ # given
+ transaction_item.order = None
+ transaction_item.save(update_fields=["order"])
+
+ event = TransactionEvent.objects.create(transaction=transaction_item)
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields(content, transaction_item, event)
+
+
+def test_transaction_query_by_staff(
+ staff_api_client, transaction_item, permission_manage_payments
+):
+ # given
+ event = TransactionEvent.objects.create(transaction=transaction_item)
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields(content, transaction_item, event)
+
+
+def test_transaction_query_no_permission(app_api_client, transaction_item):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
+ }
+
+ # when
+ response = app_api_client.post_graphql(TRANSACTION_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 7c63a44d2c..702c246eca 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -7,12 +7,13 @@ from ...core.tracing import traced_resolver
from ...payment import models
from ..checkout.dataloaders import CheckoutByTokenLoader
from ..core.connection import CountableConnection
-from ..core.descriptions import ADDED_IN_31, ADDED_IN_34, PREVIEW_FEATURE
+from ..core.descriptions import ADDED_IN_31, ADDED_IN_34, ADDED_IN_36, PREVIEW_FEATURE
from ..core.fields import JSONString, PermissionsField
from ..core.types import ModelObjectType, Money, NonNullList
from ..meta.permissions import public_payment_permissions
from ..meta.resolvers import resolve_metadata
from ..meta.types import MetadataItem, ObjectWithMetadata
+from ..order.dataloaders import OrderByIdLoader
from ..utils import get_user_or_app_from_context
from .dataloaders import (
TransactionByPaymentIdLoader,
@@ -287,6 +288,10 @@ class TransactionItem(ModelObjectType):
status = graphene.String(description="Status of transaction.", required=True)
type = graphene.String(description="Type of transaction.", required=True)
reference = graphene.String(description="Reference of transaction.", required=True)
+ order = graphene.Field(
+ "saleor.graphql.order.types.Order",
+ description="The related order." + ADDED_IN_36,
+ )
events = NonNullList(
TransactionEvent, required=True, description="List of all transaction's events."
)
@@ -318,6 +323,12 @@ class TransactionItem(ModelObjectType):
def resolve_refunded_amount(root: models.TransactionItem, _info):
return root.amount_refunded
+ @staticmethod
+ def resolve_order(root: models.TransactionItem, info):
+ if not root.order_id:
+ return
+ return OrderByIdLoader(info.context).load(root.order_id)
+
@staticmethod
def resolve_events(root: models.TransactionItem, info):
return TransactionEventByTransactionIdLoader(info.context).load(root.id)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a180f1ea6f..b412bb9474 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -450,6 +450,20 @@ type Query {
last: Int
): PaymentCountableConnection
+ """
+ Look up a transaction by ID.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: HANDLE_PAYMENTS.
+ """
+ transaction(
+ """ID of a transaction."""
+ id: ID!
+ ): TransactionItem
+
"""Look up a page by ID or slug."""
page(
"""ID of the page."""
@@ -8072,6 +8086,13 @@ type TransactionItem implements Node & ObjectWithMetadata {
"""Reference of transaction."""
reference: String!
+ """
+ The related order.
+
+ Added in Saleor 3.6.
+ """
+ order: Order
+
"""List of all transaction's events."""
events: [TransactionEvent!]!
}
@@ -8090,63 +8111,6 @@ enum TransactionActionEnum {
VOID
}
-"""Represents transaction's event."""
-type TransactionEvent implements Node {
- """The ID of the object."""
- id: ID!
- createdAt: DateTime!
-
- """Status of transaction's event."""
- status: TransactionStatus!
-
- """Reference of transaction's event."""
- reference: String!
-
- """Name of the transaction's event."""
- name: String
-}
-
-"""An enumeration."""
-enum TransactionStatus {
- PENDING
- SUCCESS
- FAILURE
-}
-
-type GiftCardCountableConnection {
- """Pagination data for this connection."""
- pageInfo: PageInfo!
- edges: [GiftCardCountableEdge!]!
-
- """A total count of items in the collection."""
- totalCount: Int
-}
-
-type GiftCardCountableEdge {
- """The item at the end of the edge."""
- node: GiftCard!
-
- """A cursor for use in pagination."""
- cursor: String!
-}
-
-type OrderCountableConnection {
- """Pagination data for this connection."""
- pageInfo: PageInfo!
- edges: [OrderCountableEdge!]!
-
- """A total count of items in the collection."""
- totalCount: Int
-}
-
-type OrderCountableEdge {
- """The item at the end of the edge."""
- node: Order!
-
- """A cursor for use in pagination."""
- cursor: String!
-}
-
"""Represents an order in the shop."""
type Order implements Node & ObjectWithMetadata {
id: ID!
@@ -9115,6 +9079,13 @@ type OrderEventDiscountObject {
oldAmount: Money
}
+"""An enumeration."""
+enum TransactionStatus {
+ PENDING
+ SUCCESS
+ FAILURE
+}
+
"""Contains all details related to the applied discount to the order."""
type OrderDiscount implements Node {
id: ID!
@@ -9212,6 +9183,56 @@ enum AddressTypeEnum {
SHIPPING
}
+"""Represents transaction's event."""
+type TransactionEvent implements Node {
+ """The ID of the object."""
+ id: ID!
+ createdAt: DateTime!
+
+ """Status of transaction's event."""
+ status: TransactionStatus!
+
+ """Reference of transaction's event."""
+ reference: String!
+
+ """Name of the transaction's event."""
+ name: String
+}
+
+type GiftCardCountableConnection {
+ """Pagination data for this connection."""
+ pageInfo: PageInfo!
+ edges: [GiftCardCountableEdge!]!
+
+ """A total count of items in the collection."""
+ totalCount: Int
+}
+
+type GiftCardCountableEdge {
+ """The item at the end of the edge."""
+ node: GiftCard!
+
+ """A cursor for use in pagination."""
+ cursor: String!
+}
+
+type OrderCountableConnection {
+ """Pagination data for this connection."""
+ pageInfo: PageInfo!
+ edges: [OrderCountableEdge!]!
+
+ """A total count of items in the collection."""
+ totalCount: Int
+}
+
+type OrderCountableEdge {
+ """The item at the end of the edge."""
+ node: Order!
+
+ """A cursor for use in pagination."""
+ cursor: String!
+}
+
type UserPermission {
"""Internal code for permission."""
code: PermissionEnum!
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py
index d69ca4f761..320372f760 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py
@@ -42,6 +42,9 @@ subscription{
status
type
reference
+ order {
+ id
+ }
}
action{
actionType
@@ -107,6 +110,7 @@ def test_transaction_refund_action_request(
"status": "Captured",
"type": "Credit card",
"reference": "PSP ref",
+ "order": {"id": graphene.Node.to_global_id("Order", order.id)},
},
"action": {
"actionType": "REFUND",
@@ -169,6 +173,7 @@ def test_transaction_charge_action_request(
"status": "Authorized",
"type": "Credit card",
"reference": "PSP ref",
+ "order": {"id": graphene.Node.to_global_id("Order", order.id)},
},
"action": {
"actionType": "CHARGE",
@@ -230,6 +235,7 @@ def test_transaction_void_action_request(
"status": "Captured",
"type": "Credit card",
"reference": "PSP ref",
+ "order": {"id": graphene.Node.to_global_id("Order", order.id)},
},
"action": {"actionType": "VOID", "amount": None},
}
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index f8cbfc8775..8985b206cc 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -81,7 +81,7 @@ from ..order.utils import recalculate_order
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
from ..payment.interface import AddressData, GatewayConfig, GatewayResponse, PaymentData
-from ..payment.models import Payment
+from ..payment.models import Payment, TransactionItem
from ..plugins.manager import get_plugins_manager
from ..plugins.models import PluginConfiguration
from ..plugins.vatlayer.plugin import VatlayerPlugin
@@ -5026,6 +5026,19 @@ def payment_dummy_credit_card(db, order_with_lines):
)
+def transaction_item(order):
+ return TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ charged_value=Decimal("10"),
+ )
+
+
@pytest.fixture
def digital_content(category, media_root, warehouse, channel_USD) -> DigitalContent:
product_type = ProductType.objects.create(