Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend transactions sorting and filtering (#18949)
Iga Karbowiak8116df6e0d92
diff --git a/AGENTS.md b/AGENTS.mdindex 2ab8821352..000864ad0c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,6 +30,7 @@- When asserting GraphQL errors, assert error message too- When asserting to Enum, import enum in a test file and use `assert error.code == MyEnum.SOME_ERROR.name` instead plain string comparison- Avoid assertion to plain values, if you already have references to existing value. For example, when you create entity in database and assert if entity is returned in response, compare response fields with entity fields, instead plain values.+- When building GraphQL query variables, use enum values instead of plain strings. For example: `{"field": TransactionSortField.CREATED_AT.name}` instead of `{"field": "CREATED_AT"}`- Do not write unnecessary prefix to test names. If file name is `test_my_mutation.py`, do not write `test_my_mutation_with_x_y` but `test_with_x_y`# Concurrency and Thread Safetydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex ecc91e65d2..c898e685db 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,9 @@ All notable, unreleased changes to this project will be documented in this file.- Added new scalar `NonNegativeInt` which allows integer values greater than or equal to zero.- Scalars `Minute`, `Hour` and `Day` now inherit from `NonNegativeInt`, which mean GraphQL disallows negative values for time units.- Removed `partial` field from the `Payment` GraphQL type.+- Added sorting and filtering support for `transactions` query:+ - sort by `CREATED_AT`, `MODIFIED_AT`;+ - filter by `createdAt`, `modifiedAt` date ranges and by transaction events (`type`, `createdAt`).- Added `PasswordLoginMode` setting to control password-based authentication. When set to `DISABLED`, all password authentication mutations (`tokenCreate`, `setPassword`, `passwordChange`, `requestPasswordReset`, `tokenRefresh`) return errors. When set to `CUSTOMERS_ONLY`, staff users who log in with a password are treated as customers without staffpermissions.- `staffDelete` mutation now always deletes the staff user. Previously, staff members with existing orders were only deactivated (`is_staff` set to `False`); now they are fully removed regardless of order history.diff --git a/saleor/graphql/payment/filters.py b/saleor/graphql/payment/filters.pyindex 13cf770773..cb91b2633e 100644--- a/saleor/graphql/payment/filters.py+++ b/saleor/graphql/payment/filters.py@@ -1,16 +1,29 @@import django_filters+import graphene+from django.db.models import Exists, OuterRef, Q+from ...payment.models import TransactionEvent+from ..core.descriptions import ADDED_IN_323from ..core.doc_category import DOC_CATEGORY_PAYMENTSfrom ..core.filters import (FilterInputObjectType,GlobalIDMultipleChoiceFilter,GlobalIDMultipleChoiceWhereFilter,+ ListObjectTypeWhereFilter,+ ObjectTypeWhereFilter,OperationObjectTypeWhereFilter,WhereFilterSet,)-from ..core.filters.where_input import StringFilterInput, WhereInputObjectType+from ..core.filters.where_input import (+ FilterInputDescriptions,+ StringFilterInput,+ WhereInputObjectType,+)+from ..core.types.base import BaseInputObjectType+from ..core.types.common import DateTimeRangeInputfrom ..utils import resolve_global_ids_to_primary_keys-from ..utils.filters import filter_where_by_value_field+from ..utils.filters import filter_where_by_range_field, filter_where_by_value_field+from .enums import TransactionEventTypeEnumfrom .types import Payment@@ -29,12 +42,74 @@ class PaymentFilterInput(FilterInputObjectType):filterset_class = PaymentFilter+class TransactionEventTypeEnumFilterInput(BaseInputObjectType):+ eq = TransactionEventTypeEnum(+ description=FilterInputDescriptions.EQ, required=False+ )+ one_of = graphene.List(+ graphene.NonNull(TransactionEventTypeEnum),+ description=FilterInputDescriptions.ONE_OF,+ required=False,+ )++ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS+++class TransactionEventFilterInput(BaseInputObjectType):+ created_at = DateTimeRangeInput(+ description="Filter transaction events by created at date." + ADDED_IN_323,+ )+ type = TransactionEventTypeEnumFilterInput(+ description="Filter transaction events by type." + ADDED_IN_323,+ )++ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS+ description = "Filter input for transaction events data." + ADDED_IN_323++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)+def filter_where_created_at_range(qs, _, value):+ return filter_where_by_range_field(qs, "created_at", value)+++def filter_where_modified_at_range(qs, _, value):+ return filter_where_by_range_field(qs, "modified_at", value)+++def filter_where_transaction_events(qs, _, value: list | None):+ if not value:+ return qs.none()++ lookup = Q()+ for input_data in value:+ if not {"created_at", "type"}.intersection(input_data.keys()):+ return qs.none()++ event_qs = None+ if filter_value := input_data.get("created_at"):+ event_qs = filter_where_by_range_field(+ TransactionEvent.objects.using(qs.db), "created_at", filter_value+ )+ if filter_value := input_data.get("type"):+ event_qs = filter_where_by_value_field(+ event_qs or TransactionEvent.objects.using(qs.db),+ "type",+ filter_value,+ )+ if event_qs is not None:+ lookup &= Q(Exists(event_qs.filter(transaction_id=OuterRef("id"))))+ if lookup:+ return qs.filter(lookup)+ return qs.none()++class TransactionWhere(WhereFilterSet):ids = GlobalIDMultipleChoiceWhereFilter(method=filter_transaction_by_ids)psp_reference = OperationObjectTypeWhereFilter(@@ -47,6 +122,27 @@ class TransactionWhere(WhereFilterSet):method="filter_app_identifier",help_text="Filter by app identifier.",)+ created_at = ObjectTypeWhereFilter(+ input_class=DateTimeRangeInput,+ method=filter_where_created_at_range,+ help_text="Filter transactions by created at date." + ADDED_IN_323,+ )+ modified_at = ObjectTypeWhereFilter(+ input_class=DateTimeRangeInput,+ method=filter_where_modified_at_range,+ help_text="Filter transactions by modified at date." + ADDED_IN_323,+ )+ events = ListObjectTypeWhereFilter(+ input_class=TransactionEventFilterInput,+ method=filter_where_transaction_events,+ help_text=(+ "Filter by transaction events. "+ "Each list item represents conditions that must be satisfied by a single "+ "event. The filter matches transactions that have related events "+ "meeting all specified groups of conditions."+ )+ + ADDED_IN_323,+ )@staticmethoddef filter_psp_reference(qs, _, value):diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.pyindex 89ead8bec3..5b7babc50d 100644--- a/saleor/graphql/payment/schema.py+++ b/saleor/graphql/payment/schema.py@@ -3,7 +3,7 @@ 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_322+from ..core.descriptions import ADDED_IN_322, ADDED_IN_323from ..core.doc_category import DOC_CATEGORY_PAYMENTSfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.scalars import UUID@@ -34,6 +34,7 @@ from .resolvers import (resolve_transaction,resolve_transactions,)+from .sorters import TransactionSortingInputfrom .types import (CardPaymentMethodDetails,GiftCardPaymentMethodDetails,@@ -102,6 +103,9 @@ class PaymentQueries(graphene.ObjectType):where=TransactionWhereInput(description="Where filtering options for transactions."),+ sort_by=TransactionSortingInput(+ description="Sort transactions." + ADDED_IN_323+ ),description=("List of transactions. ""For apps with `MANAGE_ORDERS` permission, returns all transactions. "diff --git a/saleor/graphql/payment/sorters.py b/saleor/graphql/payment/sorters.pynew file mode 100644index 0000000000..eb87c078f8--- /dev/null+++ b/saleor/graphql/payment/sorters.py@@ -0,0 +1,28 @@+from ..core.descriptions import ADDED_IN_323+from ..core.doc_category import DOC_CATEGORY_PAYMENTS+from ..core.types import BaseEnum, SortInputObjectType+++class TransactionSortField(BaseEnum):+ CREATED_AT = ["created_at", "pk"]+ MODIFIED_AT = ["modified_at", "pk"]++ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS++ @property+ def description(self):+ descriptions = {+ TransactionSortField.CREATED_AT.name: "creation date.", # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501+ TransactionSortField.MODIFIED_AT.name: "modification date.", # type: ignore[attr-defined] # graphene.Enum is not typed # noqa: E501+ }+ if self.name in descriptions:+ return f"Sort transactions by {descriptions[self.name]} {ADDED_IN_323}"+ raise ValueError(f"Unsupported enum value: {self.value}")+++class TransactionSortingInput(SortInputObjectType):+ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS+ sort_enum = TransactionSortField+ type_name = "transactions"diff --git a/saleor/graphql/payment/tests/queries/test_transactions_sorting.py b/saleor/graphql/payment/tests/queries/test_transactions_sorting.pynew file mode 100644index 0000000000..b6f25ac736--- /dev/null+++ b/saleor/graphql/payment/tests/queries/test_transactions_sorting.py@@ -0,0 +1,156 @@+from datetime import timedelta++import pytest+from django.utils import timezone++from .....payment.models import TransactionItem+from ....tests.utils import get_graphql_content+from ...sorters import TransactionSortField++TRANSACTIONS_SORT_QUERY = """+ query Transactions($sortBy: TransactionSortingInput){+ transactions(first: 10, sortBy: $sortBy) {+ edges {+ node {+ id+ pspReference+ }+ }+ }+ }+"""+++def transactions_with_different_dates(order_with_lines, transaction_item_generator):+ now = timezone.now()++ t_oldest = transaction_item_generator(+ order_id=order_with_lines.pk, psp_reference="OLDEST", currency="USD"+ )+ t_middle = transaction_item_generator(+ order_id=order_with_lines.pk, psp_reference="MIDDLE", currency="USD"+ )+ t_newest = transaction_item_generator(+ order_id=order_with_lines.pk, psp_reference="NEWEST", currency="USD"+ )++ oldest_date = now - timedelta(days=30)+ middle_date = now - timedelta(days=15)+ newest_date = now - timedelta(days=1)++ TransactionItem.objects.filter(pk=t_oldest.pk).update(+ created_at=oldest_date, modified_at=oldest_date+ )+ TransactionItem.objects.filter(pk=t_middle.pk).update(+ created_at=middle_date, modified_at=middle_date+ )+ TransactionItem.objects.filter(pk=t_newest.pk).update(+ created_at=newest_date, modified_at=newest_date+ )++ return t_oldest, t_middle, t_newest+++def test_sort_by_created_at_asc(+ staff_api_client,+ permission_group_manage_orders,+ transactions_with_different_dates,+):+ # given+ t_oldest, t_middle, t_newest = transactions_with_different_dates+ staff_api_client.user.groups.add(permission_group_manage_orders)+ variables = {+ "sortBy": {"field": TransactionSortField.CREATED_AT.name, "direction": "ASC"}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_SORT_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ psp_refs = [t["node"]["pspReference"] for t in transactions]+ assert psp_refs == [+ t_oldest.psp_reference,+ t_middle.psp_reference,+ t_newest.psp_reference,+ ]+++def test_sort_by_created_at_desc(+ staff_api_client,+ permission_group_manage_orders,+ transactions_with_different_dates,+):+ # given+ t_oldest, t_middle, t_newest = transactions_with_different_dates+ staff_api_client.user.groups.add(permission_group_manage_orders)+ variables = {+ "sortBy": {"field": TransactionSortField.CREATED_AT.name, "direction": "DESC"}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_SORT_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ psp_refs = [t["node"]["pspReference"] for t in transactions]+ assert psp_refs == [+ t_newest.psp_reference,+ t_middle.psp_reference,+ t_oldest.psp_reference,+ ]+++def test_sort_by_modified_at_asc(+ staff_api_client,+ permission_group_manage_orders,+ transactions_with_different_dates,+):+ # given+ t_oldest, t_middle, t_newest = transactions_with_different_dates+ staff_api_client.user.groups.add(permission_group_manage_orders)+ variables = {+ "sortBy": {"field": TransactionSortField.MODIFIED_AT.name, "direction": "ASC"}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_SORT_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ psp_refs = [t["node"]["pspReference"] for t in transactions]+ assert psp_refs == [+ t_oldest.psp_reference,+ t_middle.psp_reference,+ t_newest.psp_reference,+ ]+++def test_sort_by_modified_at_desc(+ staff_api_client,+ permission_group_manage_orders,+ transactions_with_different_dates,+):+ # given+ t_oldest, t_middle, t_newest = transactions_with_different_dates+ staff_api_client.user.groups.add(permission_group_manage_orders)+ variables = {+ "sortBy": {"field": TransactionSortField.MODIFIED_AT.name, "direction": "DESC"}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_SORT_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ psp_refs = [t["node"]["pspReference"] for t in transactions]+ assert psp_refs == [+ t_newest.psp_reference,+ t_middle.psp_reference,+ t_oldest.psp_reference,+ ]diff --git a/saleor/graphql/payment/tests/queries/test_transactions_where.py b/saleor/graphql/payment/tests/queries/test_transactions_where.pyindex 4ae116ff82..a4f528fbf2 100644--- a/saleor/graphql/payment/tests/queries/test_transactions_where.py+++ b/saleor/graphql/payment/tests/queries/test_transactions_where.py@@ -1,7 +1,11 @@+from datetime import timedelta+import grapheneimport pytest+from django.utils import timezone-from .....payment.models import TransactionItem+from .....payment import TransactionEventType+from .....payment.models import TransactionEvent, TransactionItemfrom ....tests.utils import get_graphql_contentTRANSACTIONS_QUERY = """@@ -359,3 +363,765 @@ def test_transactions_query_filter_respects_app_permissions(content = get_graphql_content(response)transactions = content["data"]["transactions"]["edges"]assert len(transactions) == 0+++def test_filter_by_created_at_gte_and_lte(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ transactions = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD-1", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD-2", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT-1", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT-2", currency="USD"+ ),+ ]+ )+ transactions[0].created_at = now - timedelta(days=30)+ transactions[1].created_at = now - timedelta(days=25)+ transactions[2].created_at = now - timedelta(days=5)+ transactions[3].created_at = now - timedelta(days=3)+ TransactionItem.objects.bulk_update(transactions, ["created_at"])++ variables = {+ "where": {+ "createdAt": {+ "gte": (now - timedelta(days=10)).isoformat(),+ "lte": now.isoformat(),+ }+ }+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ result = content["data"]["transactions"]["edges"]+ assert len(result) == 2+ returned_psp_refs = {t["node"]["pspReference"] for t in result}+ assert returned_psp_refs == {+ transactions[2].psp_reference,+ transactions[3].psp_reference,+ }+++def test_filter_by_created_at_gte(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ transactions = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT-1", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT-2", currency="USD"+ ),+ ]+ )+ transactions[0].created_at = now - timedelta(days=30)+ transactions[1].created_at = now - timedelta(days=5)+ transactions[2].created_at = now - timedelta(days=2)+ TransactionItem.objects.bulk_update(transactions, ["created_at"])++ variables = {+ "where": {"createdAt": {"gte": (now - timedelta(days=10)).isoformat()}}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ result = content["data"]["transactions"]["edges"]+ assert len(result) == 2+ returned_psp_refs = {t["node"]["pspReference"] for t in result}+ assert returned_psp_refs == {+ transactions[1].psp_reference,+ transactions[2].psp_reference,+ }+++def test_filter_by_created_at_lte(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ transactions = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD-1", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD-2", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT", currency="USD"+ ),+ ]+ )+ transactions[0].created_at = now - timedelta(days=30)+ transactions[1].created_at = now - timedelta(days=25)+ transactions[2].created_at = now - timedelta(days=5)+ TransactionItem.objects.bulk_update(transactions, ["created_at"])++ variables = {+ "where": {"createdAt": {"lte": (now - timedelta(days=20)).isoformat()}}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ result = content["data"]["transactions"]["edges"]+ assert len(result) == 2+ returned_psp_refs = {t["node"]["pspReference"] for t in result}+ assert returned_psp_refs == {+ transactions[0].psp_reference,+ transactions[1].psp_reference,+ }+++def test_filter_by_modified_at_gte_and_lte(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ transactions = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT-1", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT-2", currency="USD"+ ),+ ]+ )+ transactions[0].modified_at = now - timedelta(days=30)+ transactions[1].modified_at = now - timedelta(days=5)+ transactions[2].modified_at = now - timedelta(days=3)+ TransactionItem.objects.bulk_update(transactions, ["modified_at"])++ variables = {+ "where": {+ "modifiedAt": {+ "gte": (now - timedelta(days=10)).isoformat(),+ "lte": now.isoformat(),+ }+ }+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ result = content["data"]["transactions"]["edges"]+ assert len(result) == 2+ returned_psp_refs = {t["node"]["pspReference"] for t in result}+ assert returned_psp_refs == {+ transactions[1].psp_reference,+ transactions[2].psp_reference,+ }+++def test_filter_by_modified_at_gte(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ transactions = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT", currency="USD"+ ),+ ]+ )+ transactions[0].modified_at = now - timedelta(days=30)+ transactions[1].modified_at = now - timedelta(days=5)+ TransactionItem.objects.bulk_update(transactions, ["modified_at"])++ variables = {+ "where": {"modifiedAt": {"gte": (now - timedelta(days=10)).isoformat()}}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ result = content["data"]["transactions"]["edges"]+ assert len(result) == 1+ assert result[0]["node"]["pspReference"] == transactions[1].psp_reference+++def test_filter_by_modified_at_lte(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ transactions = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="OLD", currency="USD"+ ),+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="RECENT", currency="USD"+ ),+ ]+ )+ transactions[0].modified_at = now - timedelta(days=30)+ transactions[1].modified_at = now - timedelta(days=5)+ TransactionItem.objects.bulk_update(transactions, ["modified_at"])++ variables = {+ "where": {"modifiedAt": {"lte": (now - timedelta(days=20)).isoformat()}}+ }++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ result = content["data"]["transactions"]["edges"]+ assert len(result) == 1+ assert result[0]["node"]["pspReference"] == transactions[0].psp_reference+++def test_filter_by_created_at_combined_with_psp_reference(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ recent_date = now - timedelta(days=5)+ old_date = now - timedelta(days=30)++ transaction_target, transaction_wrong_date, transaction_wrong_psp = (+ TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="TARGET",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="TARGET",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="OTHER",+ currency="USD",+ ),+ ]+ )+ )++ transaction_target.created_at = recent_date+ transaction_wrong_date.created_at = old_date+ transaction_wrong_psp.created_at = recent_date+ TransactionItem.objects.bulk_update(+ [transaction_target, transaction_wrong_date, transaction_wrong_psp],+ ["created_at"],+ )++ variables = {+ "where": {+ "AND": [+ {"pspReference": {"eq": transaction_target.psp_reference}},+ {"createdAt": {"gte": (now - timedelta(days=10)).isoformat()}},+ ]+ }+ }++ # 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_target.psp_reference+++def test_filter_by_event_type_eq(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ txn_refund_1, txn_refund_2, txn_charge, txn_no_events = (+ TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="REFUNDED-1",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="REFUNDED-2",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="CHARGED",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="NO-EVENTS",+ currency="USD",+ ),+ ]+ )+ )++ TransactionEvent.objects.bulk_create(+ [+ TransactionEvent(+ transaction=txn_refund_1,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=10,+ currency="USD",+ ),+ TransactionEvent(+ transaction=txn_refund_2,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=20,+ currency="USD",+ ),+ TransactionEvent(+ transaction=txn_charge,+ type=TransactionEventType.CHARGE_SUCCESS,+ amount_value=30,+ currency="USD",+ ),+ ]+ )++ variables = {+ "where": {+ "events": [{"type": {"eq": TransactionEventType.REFUND_SUCCESS.upper()}}]+ }+ }++ # 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+ psp_refs = {t["node"]["pspReference"] for t in transactions}+ assert psp_refs == {txn_refund_1.psp_reference, txn_refund_2.psp_reference}+++def test_filter_by_event_type_one_of(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ (+ transaction_refund,+ transaction_charge,+ _transaction_cancel,+ _transaction_no_events,+ ) = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="REFUNDED",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="CHARGED",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="CANCELLED",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="NO-EVENTS",+ currency="USD",+ ),+ ]+ )++ TransactionEvent.objects.bulk_create(+ [+ TransactionEvent(+ transaction=transaction_refund,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=10,+ currency="USD",+ ),+ TransactionEvent(+ transaction=transaction_charge,+ type=TransactionEventType.CHARGE_SUCCESS,+ amount_value=20,+ currency="USD",+ ),+ TransactionEvent(+ transaction=_transaction_cancel,+ type=TransactionEventType.CANCEL_SUCCESS,+ amount_value=15,+ currency="USD",+ ),+ ]+ )++ variables = {+ "where": {+ "events": [+ {+ "type": {+ "oneOf": [+ TransactionEventType.REFUND_SUCCESS.upper(),+ TransactionEventType.CHARGE_SUCCESS.upper(),+ ]+ }+ }+ ]+ }+ }++ # 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+ psp_refs = {t["node"]["pspReference"] for t in transactions}+ assert psp_refs == {+ transaction_refund.psp_reference,+ transaction_charge.psp_reference,+ }+++def test_filter_by_event_created_at(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()++ txn_recent_1, txn_recent_2, txn_old = TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="RECENT-1",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="RECENT-2",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="OLD",+ currency="USD",+ ),+ ]+ )++ TransactionEvent.objects.bulk_create(+ [+ TransactionEvent(+ transaction=txn_recent_1,+ type=TransactionEventType.CHARGE_SUCCESS,+ amount_value=10,+ currency="USD",+ created_at=now - timedelta(days=5),+ ),+ TransactionEvent(+ transaction=txn_recent_2,+ type=TransactionEventType.CHARGE_SUCCESS,+ amount_value=20,+ currency="USD",+ created_at=now - timedelta(days=3),+ ),+ TransactionEvent(+ transaction=txn_old,+ type=TransactionEventType.CHARGE_SUCCESS,+ amount_value=10,+ currency="USD",+ created_at=now - timedelta(days=30),+ ),+ ]+ )++ variables = {+ "where": {+ "events": [{"createdAt": {"gte": (now - timedelta(days=10)).isoformat()}}]+ }+ }++ # 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+ psp_refs = {t["node"]["pspReference"] for t in transactions}+ assert psp_refs == {txn_recent_1.psp_reference, txn_recent_2.psp_reference}+++def test_filter_by_event_type_and_created_at(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ now = timezone.now()+ recent_date = now - timedelta(days=5)+ old_date = now - timedelta(days=30)++ txn_target_1, txn_target_2, txn_wrong_type, txn_wrong_date = (+ TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="TARGET-1",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="TARGET-2",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="WRONG-TYPE",+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="WRONG-DATE",+ currency="USD",+ ),+ ]+ )+ )++ TransactionEvent.objects.bulk_create(+ [+ TransactionEvent(+ transaction=txn_target_1,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=10,+ currency="USD",+ created_at=recent_date,+ ),+ TransactionEvent(+ transaction=txn_target_2,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=20,+ currency="USD",+ created_at=now - timedelta(days=3),+ ),+ TransactionEvent(+ transaction=txn_wrong_type,+ type=TransactionEventType.CHARGE_SUCCESS,+ amount_value=10,+ currency="USD",+ created_at=recent_date,+ ),+ TransactionEvent(+ transaction=txn_wrong_date,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=10,+ currency="USD",+ created_at=old_date,+ ),+ ]+ )++ variables = {+ "where": {+ "events": [+ {+ "type": {"eq": TransactionEventType.REFUND_SUCCESS.upper()},+ "createdAt": {"gte": (now - timedelta(days=10)).isoformat()},+ }+ ]+ }+ }++ # 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+ psp_refs = {t["node"]["pspReference"] for t in transactions}+ assert psp_refs == {txn_target_1.psp_reference, txn_target_2.psp_reference}++[email protected]("events_value", [[], None])+def test_filter_by_events_empty_returns_none(+ events_value,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk, psp_reference="PSP-1", currency="USD"+ ),+ ]+ )++ variables = {"where": {"events": events_value}}++ # when+ response = staff_api_client.post_graphql(TRANSACTIONS_QUERY, variables)++ # then+ content = get_graphql_content(response)+ transactions = content["data"]["transactions"]["edges"]+ assert len(transactions) == 0+++def test_filter_by_events_combined_with_psp_reference(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_orders)++ target_psp = "PSP-TARGET"++ transaction_target, _transaction_same_psp, transaction_same_event = (+ TransactionItem.objects.bulk_create(+ [+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference=target_psp,+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference=target_psp,+ currency="USD",+ ),+ TransactionItem(+ order_id=order_with_lines.pk,+ psp_reference="PSP-OTHER",+ currency="USD",+ ),+ ]+ )+ )++ TransactionEvent.objects.bulk_create(+ [+ TransactionEvent(+ transaction=transaction_target,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=10,+ currency="USD",+ ),+ TransactionEvent(+ transaction=transaction_same_event,+ type=TransactionEventType.REFUND_SUCCESS,+ amount_value=10,+ currency="USD",+ ),+ ]+ )++ variables = {+ "where": {+ "AND": [+ {"pspReference": {"eq": target_psp}},+ {+ "events": [+ {"type": {"eq": TransactionEventType.REFUND_SUCCESS.upper()}}+ ]+ },+ ]+ }+ }++ # 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_target.psp_referencediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 39e8dcadcf..4fd0cef849 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -686,6 +686,13 @@ type Query {"""Where filtering options for transactions."""where: TransactionWhereInput+ """+ Sort transactions.++ Added in Saleor 3.23.+ """+ sortBy: TransactionSortingInput+"""Return the elements in the list that come before the specified cursor."""before: String@@ -15570,6 +15577,27 @@ input TransactionWhereInput @doc(category: "Payments") {"""Filter by app identifier."""appIdentifier: StringFilterInput+ """+ Filter transactions by created at date.++ Added in Saleor 3.23.+ """+ createdAt: DateTimeRangeInput++ """+ Filter transactions by modified at date.++ Added in Saleor 3.23.+ """+ modifiedAt: DateTimeRangeInput++ """+ Filter by transaction events. Each list item represents conditions that must be satisfied by a single event. The filter matches transactions that have related events meeting all specified groups of conditions.++ Added in Saleor 3.23.+ """+ events: [TransactionEventFilterInput!]+"""List of conditions that must be met."""AND: [TransactionWhereInput!]@@ -15577,6 +15605,59 @@ input TransactionWhereInput @doc(category: "Payments") {OR: [TransactionWhereInput!]}+"""+Filter input for transaction events data.++Added in Saleor 3.23.+"""+input TransactionEventFilterInput @doc(category: "Payments") {+ """+ Filter transaction events by created at date.++ Added in Saleor 3.23.+ """+ createdAt: DateTimeRangeInput++ """+ Filter transaction events by type.++ Added in Saleor 3.23.+ """+ type: TransactionEventTypeEnumFilterInput+}++input TransactionEventTypeEnumFilterInput @doc(category: "Payments") {+ """The value equal to."""+ eq: TransactionEventTypeEnum++ """The value included in."""+ oneOf: [TransactionEventTypeEnum!]+}++input TransactionSortingInput @doc(category: "Payments") {+ """Specifies the direction in which to sort transactions."""+ direction: OrderDirection!++ """Sort transactions by the selected field."""+ field: TransactionSortField!+}++enum TransactionSortField @doc(category: "Payments") {+ """+ Sort transactions by creation date.++ Added in Saleor 3.23.+ """+ CREATED_AT++ """+ Sort transactions by modification date.++ Added in Saleor 3.23.+ """+ MODIFIED_AT+}+type PageCountableConnection @doc(category: "Pages") {"""Pagination data for this connection."""pageInfo: PageInfo!diff --git a/saleor/payment/migrations/0072_transaction_date_indexes.py b/saleor/payment/migrations/0072_transaction_date_indexes.pynew file mode 100644index 0000000000..7806009267--- /dev/null+++ b/saleor/payment/migrations/0072_transaction_date_indexes.py@@ -0,0 +1,36 @@+import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False+ dependencies = [+ ("payment", "0071_remove_legacy_adyen_plugin_fields_from_orm"),+ ]+ operations = [+ AddIndexConcurrently(+ model_name="transactionitem",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["created_at"], name="transaction_created_at_idx"+ ),+ ),+ AddIndexConcurrently(+ model_name="transactionitem",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["modified_at"], name="transaction_modified_at_idx"+ ),+ ),+ AddIndexConcurrently(+ model_name="transactionevent",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["created_at"], name="transactionevent_created_at_idx"+ ),+ ),+ AddIndexConcurrently(+ model_name="transactionevent",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["type"], name="transactionevent_type_idx"+ ),+ ),+ ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex c78acd8de1..ac7f0a1332 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -192,6 +192,8 @@ class TransactionItem(ModelWithMetadata):BTreeIndex(fields=["cc_brand"], name="cc_brand_idx"),BTreeIndex(fields=["psp_reference"], name="psp_reference_idx"),BTreeIndex(fields=["app_identifier"], name="app_identifier_idx"),+ BTreeIndex(fields=["created_at"], name="transaction_created_at_idx"),+ BTreeIndex(fields=["modified_at"], name="transaction_modified_at_idx"),]constraints = [models.UniqueConstraint(@@ -256,6 +258,10 @@ class TransactionEvent(models.Model):class Meta:ordering = ("pk",)+ indexes = [+ BTreeIndex(fields=["created_at"], name="transactionevent_created_at_idx"),+ BTreeIndex(fields=["type"], name="transactionevent_type_idx"),+ ]constraints = [models.UniqueConstraint(fields=["transaction_id", "idempotency_key"],