Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `transactions` query and extend order transactions where filter with `pspReference` (#18760)
Iga Karbowiak4d333d041821
diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex 011649ac85..11c4001887 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -21,6 +21,7 @@ from ...product.models import ProductVariantfrom ...warehouse.models import Stock, Warehousefrom ..account.filters import AddressFilterInput, filter_addressfrom ..channel.filters import get_currency_from_filter_data+from ..core.descriptions import ADDED_IN_322from ..core.doc_category import DOC_CATEGORY_ORDERSfrom ..core.filters import (GlobalIDMultipleChoiceFilter,@@ -589,6 +590,9 @@ class TransactionFilterInput(BaseInputObjectType):payment_method_details = PaymentMethodDetailsFilterInput(description="Filter by payment method details used to pay for the order.",)+ psp_reference = StringFilterInput(+ description="Filter by PSP reference of transactions." + ADDED_IN_322,+ )metadata = MetadataFilterInput(description="Filter by metadata fields of transactions.")@@ -608,6 +612,10 @@ class TransactionFilterInput(BaseInputObjectType):return PaymentMethodDetailsFilterInput.filter_type(qs, _, filter_value)return qs.none()+ @staticmethod+ def filter_psp_reference(qs, _, value):+ return filter_where_by_value_field(qs, "psp_reference", value)+@staticmethoddef filter_metadata(qs, _, value):if value is None:@@ -680,8 +688,9 @@ def filter_where_transactions(qs, _, value):for input_data in value:metadata_value = input_data.get("metadata")payment_method_details_value = input_data.get("payment_method_details")+ psp_reference_value = input_data.get("psp_reference")- if not any([metadata_value, payment_method_details_value]):+ if not any([metadata_value, payment_method_details_value, psp_reference_value]):return qs.none()transaction_qs = None@@ -695,6 +704,12 @@ def filter_where_transactions(qs, _, value):_,metadata_value,)+ if psp_reference_value:+ transaction_qs = TransactionFilterInput.filter_psp_reference(+ transaction_qs or TransactionItem.objects.using(qs.db),+ _,+ psp_reference_value,+ )if transaction_qs is not None:lookup &= Q(Exists(transaction_qs.filter(order_id=OuterRef("id"))))diff --git a/saleor/graphql/order/tests/queries/test_order_with_where.py b/saleor/graphql/order/tests/queries/test_order_with_where.pyindex 6c19f74014..adc10ff472 100644--- a/saleor/graphql/order/tests/queries/test_order_with_where.py+++ b/saleor/graphql/order/tests/queries/test_order_with_where.py@@ -3253,6 +3253,133 @@ def test_orders_filter_by_transactions_with_mixed_conditions(assert numbers == {str(order_list[i].number) for i in expected_indexes}+ ("psp_reference_filter", "expected_indexes"),+ [+ ({"eq": "PSP-ref-1"}, [0]),+ ({"eq": "PSP-ref-2"}, [0]),+ ({"eq": "PSP-ref-3"}, [1]),+ ({"eq": "PSP-ref-4"}, [2]),+ ({"eq": "non-existent-ref"}, []),+ ({"oneOf": ["PSP-ref-1", "PSP-ref-3"]}, [0, 1]),+ ({"oneOf": ["PSP-ref-2", "PSP-ref-4"]}, [0, 2]),+ ({"oneOf": ["PSP-ref-1", "PSP-ref-2", "PSP-ref-3", "PSP-ref-4"]}, [0, 1, 2]),+ ({"oneOf": ["non-existent-ref"]}, []),+ ({"oneOf": []}, []),+ ({"eq": None}, []),+ (None, []),+ ],+)+def test_orders_filter_by_transaction_psp_reference(+ psp_reference_filter,+ expected_indexes,+ order_list,+ staff_api_client,+ permission_group_manage_orders,+ transaction_item_generator,+):+ # given+ transaction_item_generator(+ order_id=order_list[0].pk,+ charged_value=order_list[0].total.gross.amount,+ psp_reference="PSP-ref-1",+ )++ transaction_item_generator(+ order_id=order_list[0].pk,+ charged_value=order_list[0].total.gross.amount,+ psp_reference="PSP-ref-2",+ )++ transaction_item_generator(+ order_id=order_list[1].pk,+ charged_value=order_list[1].total.gross.amount,+ psp_reference="PSP-ref-3",+ )++ transaction_item_generator(+ order_id=order_list[2].pk,+ charged_value=order_list[2].total.gross.amount,+ psp_reference="PSP-ref-4",+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"where": {"transactions": [{"pspReference": psp_reference_filter}]}}++ # when+ response = staff_api_client.post_graphql(ORDERS_WHERE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ orders = content["data"]["orders"]["edges"]+ assert len(orders) == len(expected_indexes)+ numbers = {node["node"]["number"] for node in orders}+ assert numbers == {str(order_list[i].number) for i in expected_indexes}+++def test_orders_filter_by_transaction_psp_reference_payment_details_and_metadata(+ order_list,+ staff_api_client,+ permission_group_manage_orders,+ transaction_item_generator,+):+ # given+ transaction_item_generator(+ order_id=order_list[0].pk,+ charged_value=order_list[0].total.gross.amount,+ psp_reference="PSP-ref-1",+ payment_method_type="card",+ cc_brand="Visa",+ metadata={"foo": "bar"},+ )++ transaction_item_generator(+ order_id=order_list[0].pk,+ charged_value=order_list[0].total.gross.amount,+ psp_reference="PSP-ref-2",+ payment_method_type="other",+ metadata={"baz": "qux"},+ )++ transaction_item_generator(+ order_id=order_list[1].pk,+ charged_value=order_list[1].total.gross.amount,+ psp_reference="PSP-ref-3",+ payment_method_type="card",+ cc_brand="Mastercard",+ metadata={"foo": "bar"},+ )++ transaction_item_generator(+ order_id=order_list[2].pk,+ charged_value=order_list[2].total.gross.amount,+ psp_reference="PSP-ref-4",+ payment_method_type="card",+ cc_brand="Visa",+ metadata={},+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {+ "where": {+ "transactions": [+ {"pspReference": {"oneOf": ["PSP-ref-1", "PSP-ref-3", "PSP-ref-4"]}},+ {"paymentMethodDetails": {"card": {"brand": {"eq": "Visa"}}}},+ {"metadata": {"key": "foo"}},+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(ORDERS_WHERE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ orders = content["data"]["orders"]["edges"]+ assert len(orders) == 1+ assert orders[0]["node"]["number"] == str(order_list[0].number)++@pytest.mark.parametrize(("address_filter", "expected_indexes"),[diff --git a/saleor/graphql/payment/filters.py b/saleor/graphql/payment/filters.pyindex 1a8142297f..13cf770773 100644--- a/saleor/graphql/payment/filters.py+++ b/saleor/graphql/payment/filters.py@@ -1,7 +1,16 @@import django_filtersfrom ..core.doc_category import DOC_CATEGORY_PAYMENTS-from ..core.filters import FilterInputObjectType, GlobalIDMultipleChoiceFilter+from ..core.filters import (+ FilterInputObjectType,+ GlobalIDMultipleChoiceFilter,+ GlobalIDMultipleChoiceWhereFilter,+ OperationObjectTypeWhereFilter,+ WhereFilterSet,+)+from ..core.filters.where_input import StringFilterInput, WhereInputObjectType+from ..utils import resolve_global_ids_to_primary_keys+from ..utils.filters import filter_where_by_value_fieldfrom .types import Payment@@ -18,3 +27,40 @@ class PaymentFilterInput(FilterInputObjectType):class Meta:doc_category = DOC_CATEGORY_PAYMENTSfilterset_class = PaymentFilter+++def filter_transaction_by_ids(qs, _, value):+ """Filter TransactionItem by global IDs."""+ _, tokens = resolve_global_ids_to_primary_keys(value, "TransactionItem")+ return qs.filter(token__in=tokens)+++class TransactionWhere(WhereFilterSet):+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_transaction_by_ids)+ psp_reference = OperationObjectTypeWhereFilter(+ input_class=StringFilterInput,+ method="filter_psp_reference",+ help_text="Filter by PSP reference.",+ )+ app_identifier = OperationObjectTypeWhereFilter(+ input_class=StringFilterInput,+ method="filter_app_identifier",+ help_text="Filter by app identifier.",+ )++ @staticmethod+ def filter_psp_reference(qs, _, value):+ return filter_where_by_value_field(qs, "psp_reference", value)++ @staticmethod+ def filter_app_identifier(qs, _, value):+ return filter_where_by_value_field(qs, "app_identifier", value)++ class Meta:+ abstract = True+++class TransactionWhereInput(WhereInputObjectType):+ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS+ filterset_class = TransactionWherediff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.pyindex 38cd987c2d..389468a052 100644--- a/saleor/graphql/payment/resolvers.py+++ b/saleor/graphql/payment/resolvers.py@@ -1,6 +1,10 @@+from django.db.models import Q+from ...app import models as app_models+from ...checkout import models as checkout_modelsfrom ...order import models as order_modelsfrom ...payment import models+from ...permission.enums import OrderPermissionsfrom ..account.utils import get_user_accessible_channelsfrom ..core.context import get_database_connection_namefrom ..utils import get_user_or_app_from_context@@ -38,3 +42,32 @@ def resolve_transaction(info, id):.filter(**query_params).first())+++def resolve_transactions(info):+ connection_name = get_database_connection_name(info.context)+ requestor = get_user_or_app_from_context(info.context)+ transactions = models.TransactionItem.objects.using(connection_name).all()++ if isinstance(requestor, app_models.App):+ # App with MANAGE_ORDERS permission can see all transactions+ if requestor.has_perm(OrderPermissions.MANAGE_ORDERS):+ return transactions+ # Otherwise, app can only see transactions it created+ return transactions.filter(app_id=requestor.id)++ # Filter by accessible channels for user+ accessible_channels = get_user_accessible_channels(info, requestor)+ channel_ids = [channel.id for channel in accessible_channels]+ orders = order_models.Order.objects.using(connection_name).filter(+ channel_id__in=channel_ids+ )+ checkouts = checkout_models.Checkout.objects.using(connection_name).filter(+ channel_id__in=channel_ids+ )++ # Filter transactions by orders or checkouts in accessible channels+ return transactions.filter(+ Q(order_id__in=orders.values("id"))+ | Q(checkout_id__in=checkouts.values("token"))+ )diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.pyindex 5e03c42118..4c5d1ca175 100644--- a/saleor/graphql/payment/schema.py+++ b/saleor/graphql/payment/schema.py@@ -3,11 +3,12 @@ import graphenefrom ...permission.enums import OrderPermissions, PaymentPermissionsfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.descriptions import ADDED_IN_322from ..core.doc_category import DOC_CATEGORY_PAYMENTSfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.scalars import UUIDfrom ..core.utils import from_global_id_or_error-from .filters import PaymentFilterInput+from .filters import PaymentFilterInput, TransactionWhereInputfrom .mutations import (PaymentCapture,PaymentCheckBalance,@@ -27,12 +28,18 @@ from .mutations import (TransactionRequestRefundForGrantedRefund,TransactionUpdate,)-from .resolvers import resolve_payment_by_id, resolve_payments, resolve_transaction+from .resolvers import (+ resolve_payment_by_id,+ resolve_payments,+ resolve_transaction,+ resolve_transactions,+)from .types import (CardPaymentMethodDetails,OtherPaymentMethodDetails,Payment,PaymentCountableConnection,+ TransactionCountableConnection,TransactionItem,)@@ -84,6 +91,26 @@ class PaymentQueries(graphene.ObjectType):),permissions=[PaymentPermissions.HANDLE_PAYMENTS,+ OrderPermissions.MANAGE_ORDERS,+ ],+ doc_category=DOC_CATEGORY_PAYMENTS,+ )+ transactions = FilterConnectionField(+ TransactionCountableConnection,+ where=TransactionWhereInput(+ description="Where filtering options for transactions."+ ),+ description=(+ "List of transactions. "+ "For apps with `MANAGE_ORDERS` permission, returns all transactions. "+ "For apps with just `HANDLE_PAYMENTS` permission, "+ "returns only transactions created by that app. "+ "For staff users, returns transactions from orders and checkouts "+ "in channels they have access to." + ADDED_IN_322+ ),+ permissions=[+ PaymentPermissions.HANDLE_PAYMENTS,+ OrderPermissions.MANAGE_ORDERS,],doc_category=DOC_CATEGORY_PAYMENTS,)@@ -115,6 +142,14 @@ class PaymentQueries(graphene.ObjectType):)return resolve_transaction(info, id)+ @staticmethod+ def resolve_transactions(_root, info: ResolveInfo, **kwargs):+ qs = resolve_transactions(info)+ qs = filter_connection_queryset(+ qs, kwargs, allow_replica=info.context.allow_replica+ )+ return create_connection_slice(qs, info, kwargs, TransactionCountableConnection)+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.pyindex f69420df2f..79ccb32346 100644--- a/saleor/graphql/payment/tests/queries/test_transaction.py+++ b/saleor/graphql/payment/tests/queries/test_transaction.py@@ -506,6 +506,34 @@ def test_transaction_create_by_user_query_no_permission(assert_no_permission(response)+def test_transaction_by_user_with_manage_orders(+ user_api_client,+ transaction_item_created_by_app,+ permission_manage_orders,+ customer_user,+):+ # given+ user_api_client.user = customer_user+ user_api_client.user.user_permissions.add(permission_manage_orders)++ event = transaction_item_created_by_app.events.filter(+ type=TransactionEventType.CHARGE_SUCCESS+ ).get()++ variables = {+ "id": graphene.Node.to_global_id(+ "TransactionItem", transaction_item_created_by_app.token+ )+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_QUERY, variables)++ # then+ content = get_graphql_content(response)+ _assert_transaction_fields(content, transaction_item_created_by_app, event)++def test_query_transaction_by_invalid_id(staff_api_client, permission_manage_payments):# givenid = graphene.Node.to_global_id("Order", "e6cad766-c9df-4970-b77b-b8eb0e303fb6")diff --git a/saleor/graphql/payment/tests/queries/test_transactions.py b/saleor/graphql/payment/tests/queries/test_transactions.pynew file mode 100644index 0000000000..eefe7f89b6--- /dev/null+++ b/saleor/graphql/payment/tests/queries/test_transactions.py@@ -0,0 +1,242 @@+import pytest++from .....order.models import Order+from ....tests.utils import assert_no_permission, get_graphql_content+++def transactions_in_different_channels(+ order_list,+ checkout,+ channel_USD,+ channel_JPY,+ channel_PLN,+ transaction_item_generator,+):+ order_list[0].channel = channel_PLN+ order_list[1].channel = channel_JPY+ order_list[2].channel = channel_USD+ Order.objects.bulk_update(order_list, ["channel"])++ checkout.channel = channel_USD+ checkout.save(update_fields=["channel"])++ transaction_1 = transaction_item_generator(+ order_id=order_list[0].pk,+ psp_reference="PSP-PLN",+ currency="PLN",+ )+ transaction_2 = transaction_item_generator(+ order_id=order_list[1].pk,+ psp_reference="PSP-JPY",+ currency="JPY",+ )+ transaction_3 = transaction_item_generator(+ order_id=order_list[2].pk,+ psp_reference="PSP-USD",+ currency="USD",+ )+ transaction_4 = transaction_item_generator(+ checkout_id=checkout.pk,+ psp_reference="PSP-CHECKOUT-USD",+ currency="USD",+ )++ return [transaction_1, transaction_2, transaction_3, transaction_4]+++TRANSACTIONS_QUERY = """+ query Transactions($where: TransactionWhereInput){+ transactions(first: 10, where: $where) {+ edges {+ node {+ id+ pspReference+ }+ }+ }+ }+"""+++def test_transactions_query_no_permission(+ staff_api_client, transactions_in_different_channels+):+ # given+ variables = {}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ assert_no_permission(response)+++def test_transactions_query_by_app_with_manage_orders_returns_all(+ transactions_in_different_channels,+ app_api_client,+ permission_manage_orders,+):+ # given+ # App with MANAGE_ORDERS permission should see all transactions+ app_api_client.app.permissions.add(permission_manage_orders)+ variables = {}++ # when+ response = app_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == len(transactions_in_different_channels)+++def test_transactions_query_by_app_with_handle_payments_returns_only_own(+ order_with_lines,+ app_api_client,+ permission_manage_payments,+ transaction_item_generator,+):+ # given+ # App with just HANDLE_PAYMENTS should only see transactions it created+ app = app_api_client.app+ app.permissions.add(permission_manage_payments)++ # Transaction created by this app+ own_transaction = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP-OWN",+ currency="USD",+ app=app,+ )+ # Transaction created by another app (or no app)+ transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP-OTHER",+ currency="USD",+ app=None,+ )++ variables = {}++ # when+ response = app_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 1+ assert transactions[0]["node"]["pspReference"] == own_transaction.psp_reference+++def test_transactions_query_by_app_with_handle_payments_no_own_transactions(+ transactions_in_different_channels,+ app_api_client,+ permission_manage_payments,+):+ # given+ # App with just HANDLE_PAYMENTS sees nothing if it didn't create any transactions+ app_api_client.app.permissions.add(permission_manage_payments)+ variables = {}++ # when+ response = app_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ # None of the transactions_in_different_channels were created by this app+ assert len(transactions) == 0+++def test_transactions_query_by_app_with_both_permissions_returns_all(+ transactions_in_different_channels,+ app_api_client,+ permission_manage_payments,+ permission_manage_orders,+):+ # given+ # App with both MANAGE_ORDERS and HANDLE_PAYMENTS should see all transactions+ app_api_client.app.permissions.add(permission_manage_payments)+ app_api_client.app.permissions.add(permission_manage_orders)+ variables = {}++ # when+ response = app_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == len(transactions_in_different_channels)+++def test_transactions_query_with_manage_orders_permission(+ transactions_in_different_channels,+ staff_api_client,+ permission_group_manage_orders,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)+ variables = {}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == len(transactions_in_different_channels)+++def test_transactions_query_filtered_by_accessible_channels_for_user(+ transactions_in_different_channels,+ staff_api_client,+ permission_group_manage_orders,+ channel_USD,+):+ # given+ permission_group_manage_orders.restricted_access_to_channels = True+ permission_group_manage_orders.save(update_fields=["restricted_access_to_channels"])+ permission_group_manage_orders.channels.add(channel_USD)++ permission_group_manage_orders.user_set.add(staff_api_client.user)++ variables = {}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]++ # Should only see transactions from channel_USD+ assert len(transactions) == 2+ assert {node["node"]["pspReference"] for node in transactions} == {+ "PSP-USD",+ "PSP-CHECKOUT-USD",+ }+++def test_transactions_query_by_user_with_no_channel_access(+ transactions_in_different_channels,+ staff_api_client,+ permission_group_manage_orders,+ other_channel_USD,+):+ # given+ permission_group_manage_orders.channels.set([other_channel_USD])+ permission_group_manage_orders.restricted_access_to_channels = True+ permission_group_manage_orders.save(update_fields=["restricted_access_to_channels"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)++ variables = {}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 0diff --git a/saleor/graphql/payment/tests/queries/test_transactions_where.py b/saleor/graphql/payment/tests/queries/test_transactions_where.pynew file mode 100644index 0000000000..3e4f30e07f--- /dev/null+++ b/saleor/graphql/payment/tests/queries/test_transactions_where.py@@ -0,0 +1,295 @@+import graphene+import pytest++from .....payment.models import TransactionItem+from ....tests.utils import get_graphql_content++TRANSACTIONS_QUERY = """+ query Transactions($where: TransactionWhereInput){+ transactions(first: 10, where: $where) {+ edges {+ node {+ id+ pspReference+ }+ }+ }+ }+"""+++def test_transactions_query_filter_by_ids(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ transaction_item_generator,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ transaction_1 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref1",+ currency="USD",+ )+ transaction_2 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref2",+ currency="USD",+ )+ _transaction_3 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref3",+ currency="USD",+ )++ ids = [+ graphene.Node.to_global_id("TransactionItem", transaction_1.token),+ graphene.Node.to_global_id("TransactionItem", transaction_2.token),+ ]+ variables = {"where": {"ids": ids}}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 2+ returned_ids = {node["node"]["id"] for node in transactions}+ assert returned_ids == set(ids)++[email protected]("value", [None, []])+def test_transactions_query_filter_by_ids_empty_values(+ value, staff_api_client, permission_manage_payments, transaction_item_created_by_app+):+ # given+ variables = {"where": {"ids": value}}++ # when+ response = staff_api_client.post_graphql(+ TRANSACTIONS_QUERY, variables, permissions=(permission_manage_payments,)+ )++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 0+++ ("where", "expected_psp_refs"),+ [+ ({"eq": "PSP ref1"}, ["PSP ref1"]),+ ({"eq": "Non-existing"}, []),+ ({"eq": None}, []),+ ({"eq": ""}, []),+ ({"oneOf": ["PSP ref1", "PSP ref2"]}, ["PSP ref1", "PSP ref2"]),+ ({"oneOf": ["PSP ref1"]}, ["PSP ref1"]),+ ({"oneOf": ["Non-existing 1", "Non-existing 2"]}, []),+ ({"oneOf": []}, []),+ (None, []),+ ],+)+def test_transactions_query_filter_by_psp_reference(+ where,+ expected_psp_refs,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ transaction_item_generator,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)+ permission_group_manage_orders.channels.add(order_with_lines.channel)++ transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref1",+ currency="USD",+ )+ transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref2",+ currency="USD",+ )+ transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref3",+ currency="USD",+ )++ variables = {"where": {"pspReference": where}}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == len(expected_psp_refs)+ returned_psp_refs = {node["node"]["pspReference"] for node in transactions}+ assert returned_psp_refs == set(expected_psp_refs)+++def test_transactions_query_combined_filters(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ transaction_item_generator,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ transaction_1 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP-TARGET",+ currency="USD",+ )+ transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP-OTHER",+ currency="USD",+ )++ ids = [graphene.Node.to_global_id("TransactionItem", transaction_1.token)]+ variables = {+ "where": {+ "AND": [+ {"ids": ids},+ {"pspReference": {"eq": transaction_1.psp_reference}},+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 1+ assert transactions[0]["node"]["pspReference"] == transaction_1.psp_reference+++ ("where", "expected_app_identifiers"),+ [+ ({"eq": "app.identifier.1"}, ["app.identifier.1"]),+ ({"eq": "Non-existing"}, []),+ ({"eq": None}, []),+ ({"eq": ""}, []),+ (+ {"oneOf": ["app.identifier.1", "app.identifier.2"]},+ ["app.identifier.1", "app.identifier.2"],+ ),+ ({"oneOf": ["app.identifier.1"]}, ["app.identifier.1"]),+ ({"oneOf": ["Non-existing 1", "Non-existing 2"]}, []),+ ({"oneOf": []}, []),+ (None, []),+ ],+)+def test_transactions_query_filter_by_app_identifier(+ where,+ expected_app_identifiers,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ transaction_item_generator,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ app_identifier_1 = "app.identifier.1"+ app_identifier_2 = "app.identifier.2"+ app_identifier_3 = "app.identifier.3"++ transaction_1 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref1",+ currency="USD",+ )+ transaction_2 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref2",+ currency="USD",+ )+ transaction_3 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference="PSP ref3",+ currency="USD",+ )++ transaction_1.app_identifier = app_identifier_1+ transaction_2.app_identifier = app_identifier_2+ transaction_3.app_identifier = app_identifier_3+ TransactionItem.objects.bulk_update(+ [transaction_1, transaction_2, transaction_3], ["app_identifier"]+ )++ variables = {"where": {"appIdentifier": where}}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == len(expected_app_identifiers)+++def test_transactions_query_filter_by_app_identifier_combined_with_psp_reference(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ transaction_item_generator,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ target_app_identifier = "my.app.identifier"+ other_app_identifier = "other.app.identifier"+ target_psp_reference = "PSP-TARGET"+ other_psp_reference = "PSP-OTHER"++ target_transaction = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference=target_psp_reference,+ currency="USD",+ )+ transaction_2 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference=other_psp_reference,+ currency="USD",+ )+ transaction_3 = transaction_item_generator(+ order_id=order_with_lines.pk,+ psp_reference=target_psp_reference,+ currency="USD",+ )++ target_transaction.app_identifier = target_app_identifier+ transaction_2.app_identifier = target_app_identifier+ transaction_3.app_identifier = other_app_identifier+ TransactionItem.objects.bulk_update(+ [target_transaction, transaction_2, transaction_3], ["app_identifier"]+ )++ variables = {+ "where": {+ "AND": [+ {"appIdentifier": {"eq": target_app_identifier}},+ {"pspReference": {"eq": target_psp_reference}},+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 1+ assert transactions[0]["node"]["pspReference"] == target_transaction.psp_referencediff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex b6bb60d520..3c06162594 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -801,6 +801,12 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):return None+class TransactionCountableConnection(CountableConnection):+ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS+ node = TransactionItem++class GatewayConfigLine(BaseObjectType):field = graphene.String(required=True, description="Gateway config key.")value = graphene.String(description="Gateway config value for key.")diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1fa37520ac..f9a2cf7b87 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -661,7 +661,7 @@ type Query {"""Look up a transaction by ID.- Requires one of the following permissions: HANDLE_PAYMENTS.+ Requires one of the following permissions: HANDLE_PAYMENTS, MANAGE_ORDERS."""transaction("""@@ -675,6 +675,34 @@ type Query {token: UUID): TransactionItem @doc(category: "Payments")+ """+ List of transactions. For apps with `MANAGE_ORDERS` permission, returns all transactions. For apps with just `HANDLE_PAYMENTS` permission, returns only transactions created by that app. For staff users, returns transactions from orders and checkouts in channels they have access to.++ Added in Saleor 3.22.++ Requires one of the following permissions: HANDLE_PAYMENTS, MANAGE_ORDERS.+ """+ transactions(+ """Where filtering options for transactions."""+ where: TransactionWhereInput++ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): TransactionCountableConnection @doc(category: "Payments")+"""Look up a page by ID or slug."""page("""ID of the page."""@@ -13112,6 +13140,39 @@ input PaymentFilterInput @doc(category: "Payments") {checkouts: [ID!]}+type TransactionCountableConnection @doc(category: "Payments") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [TransactionCountableEdge!]!++ """A total count of items in the collection."""+ totalCount: Int+}++type TransactionCountableEdge @doc(category: "Payments") {+ """The item at the end of the edge."""+ node: TransactionItem!++ """A cursor for use in pagination."""+ cursor: String!+}++input TransactionWhereInput @doc(category: "Payments") {+ ids: [ID!]++ """Filter by PSP reference."""+ pspReference: StringFilterInput++ """Filter by app identifier."""+ appIdentifier: StringFilterInput++ """List of conditions that must be met."""+ AND: [TransactionWhereInput!]++ """A list of conditions of which at least one must be met."""+ OR: [TransactionWhereInput!]+}+type PageCountableConnection @doc(category: "Pages") {"""Pagination data for this connection."""pageInfo: PageInfo!@@ -13554,6 +13615,13 @@ input TransactionFilterInput @doc(category: "Orders") {"""Filter by payment method details used to pay for the order."""paymentMethodDetails: PaymentMethodDetailsFilterInput+ """+ Filter by PSP reference of transactions.++ Added in Saleor 3.22.+ """+ pspReference: StringFilterInput+"""Filter by metadata fields of transactions."""metadata: MetadataFilterInput}diff --git a/saleor/payment/migrations/0066_transactionitem_psp_reference_idx.py b/saleor/payment/migrations/0066_transactionitem_psp_reference_idx.pynew file mode 100644index 0000000000..f43759b7c9--- /dev/null+++ b/saleor/payment/migrations/0066_transactionitem_psp_reference_idx.py@@ -0,0 +1,26 @@+# Generated by Django 5.2.8 on 2026-02-06 08:33++import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("account", "0095_repopulate_user_number_of_orders"),+ ("app", "0034_alter_appextension_mount"),+ ("checkout", "0088_reapply_fix_shared_address_instances"),+ ("order", "0219_merge_20251212_0955"),+ ("payment", "0065_transactionevent_reason_reference"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="transactionitem",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["psp_reference"], name="psp_reference_idx"+ ),+ ),+ ]diff --git a/saleor/payment/migrations/0067_transactionitem_app_identifier_idx.py b/saleor/payment/migrations/0067_transactionitem_app_identifier_idx.pynew file mode 100644index 0000000000..319ec23eed--- /dev/null+++ b/saleor/payment/migrations/0067_transactionitem_app_identifier_idx.py@@ -0,0 +1,26 @@+# Generated by Django 5.2.8 on 2026-02-06 10:58++import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("account", "0095_repopulate_user_number_of_orders"),+ ("app", "0034_alter_appextension_mount"),+ ("checkout", "0088_reapply_fix_shared_address_instances"),+ ("order", "0219_merge_20251212_0955"),+ ("payment", "0066_transactionitem_psp_reference_idx"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="transactionitem",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["app_identifier"], name="app_identifier_idx"+ ),+ ),+ ]diff --git a/saleor/payment/migrations/0068_merge_20260206_1216.py b/saleor/payment/migrations/0068_merge_20260206_1216.pynew file mode 100644index 0000000000..d99b3b4562--- /dev/null+++ b/saleor/payment/migrations/0068_merge_20260206_1216.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.8 on 2026-02-06 11:16++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("payment", "0066_transactionitem_gift_card"),+ ("payment", "0067_transactionitem_app_identifier_idx"),+ ]++ operations = []diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 9cdbfcd4f1..00cc82cd5b 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -188,6 +188,8 @@ class TransactionItem(ModelWithMetadata):*ModelWithMetadata.Meta.indexes,BTreeIndex(fields=["payment_method_type"], name="payment_method_type_ids"),BTreeIndex(fields=["cc_brand"], name="cc_brand_idx"),+ BTreeIndex(fields=["psp_reference"], name="psp_reference_idx"),+ BTreeIndex(fields=["app_identifier"], name="app_identifier_idx"),]constraints = [models.UniqueConstraint(