Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Filter order by payment method details (#17843)
Maciej Korycinskid1e6e0e2bbbc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 48d784d39a..aa9b9b1452 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,7 @@ All notable, unreleased changes to this project will be documented in this file.- Filter by order by associated lines metadata.- Filter by the product type of related order lines.- Filter by associated event type and date+ - Filter by associated payment method name and type- Extend the `Page` type with an `attribute` field. Adds support for querying a specific attribute on a page by `slug`, returning the matching attribute and its assigned values, or null if no match is found.- Enhanced order search options. Orders can now be searched using:- The order's IDdiff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex 8ff95fd2f8..3f11ee7363 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -14,7 +14,8 @@ from ...giftcard.models import GiftCardEventfrom ...invoice.models import Invoicefrom ...order.models import Fulfillment, Order, OrderEvent, OrderLinefrom ...order.search import search_orders-from ...payment import ChargeStatus+from ...payment import ChargeStatus, PaymentMethodType+from ...payment.models import TransactionItemfrom ...product.models import ProductVariantfrom ..channel.filters import get_currency_from_filter_datafrom ..core.doc_category import DOC_CATEGORY_ORDERS@@ -48,7 +49,7 @@ from ..core.types import ()from ..core.utils import from_global_id_or_errorfrom ..discount.filters import DiscountedObjectWhere-from ..payment.enums import PaymentChargeStatusEnum+from ..payment.enums import PaymentChargeStatusEnum, PaymentMethodTypeEnumfrom ..utils import resolve_global_ids_to_primary_keysfrom ..utils.filters import (filter_by_ids,@@ -456,6 +457,75 @@ class OrderEventFilterInput(BaseInputObjectType):description = "Filter input for order events data."+class PaymentMethodTypeEnumFilterInput(BaseInputObjectType):+ eq = PaymentMethodTypeEnum(description=FilterInputDescriptions.EQ, required=False)+ one_of = NonNullList(+ PaymentMethodTypeEnum,+ description=FilterInputDescriptions.ONE_OF,+ required=False,+ )+++class PaymentMethodDetailsCardFilterInput(BaseInputObjectType):+ brand = StringFilterInput(+ description="Filter by payment method brand used to pay for the order.",+ )+++class PaymentMethodDetailsFilterInput(BaseInputObjectType):+ type = PaymentMethodTypeEnumFilterInput(+ description="Filter by payment method type used to pay for the order.",+ )+ card = PaymentMethodDetailsCardFilterInput(+ description="Filter by card details used to pay for the order. Skips `type` filter if provided.",+ )++ @staticmethod+ def filter_card(qs, _, value):+ if value is None:+ return qs.none()+ transaction_query = TransactionItem.objects.using(qs.db).filter(+ payment_method_type=PaymentMethodType.CARD+ )+ if brand_filter_value := value.get("brand"):+ transactions = filter_where_by_value_field(+ transaction_query, "cc_brand", brand_filter_value+ )+ return qs.filter(Exists(transactions.filter(order_id=OuterRef("id"))))++ @staticmethod+ def filter_type(qs, _, value):+ if value is None:+ return qs.none()+ transactions = filter_where_by_value_field(+ TransactionItem.objects.using(qs.db),+ "payment_method_type",+ value,+ )+ return qs.filter(Exists(transactions.filter(order_id=OuterRef("id"))))+++class TransactionFilterInput(BaseInputObjectType):+ payment_method_details = PaymentMethodDetailsFilterInput(+ description="Filter by payment method details used to pay for the order.",+ )++ class Meta:+ doc_category = DOC_CATEGORY_ORDERS+ description = "Filter input for transactions."++ @staticmethod+ def filter_payment_method_details(qs, _, value):+ if value is None:+ return qs.none()++ if filter_value := value.get("card"):+ return PaymentMethodDetailsFilterInput.filter_card(qs, _, filter_value)+ if filter_value := value.get("type"):+ return PaymentMethodDetailsFilterInput.filter_type(qs, _, filter_value)+ return qs.none()++class OrderWhere(MetadataWhereBase):ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Order"))number = OperationObjectTypeWhereFilter(@@ -562,6 +632,11 @@ class OrderWhere(MetadataWhereBase):method="filter_lines_count",help_text="Filter by number of lines in the order.",)+ transactions = ObjectTypeWhereFilter(+ input_class=TransactionFilterInput,+ method="filter_transactions",+ help_text="Filter by transaction data associated with the order.",+ )total_gross = ObjectTypeWhereFilter(input_class=PriceFilterInput,method="filter_total_gross",@@ -695,6 +770,16 @@ class OrderWhere(MetadataWhereBase):def filter_lines_count(qs, _, value):return filter_where_by_numeric_field(qs, "lines_count", value)+ @staticmethod+ def filter_transactions(qs, _, value):+ if value is None:+ return qs.none()+ if filter_value := value.get("payment_method_details"):+ return TransactionFilterInput.filter_payment_method_details(+ qs, _, filter_value+ )+ return qs.none()+@staticmethoddef filter_total_gross(qs, _, value):return filter_where_by_price_field(qs, "total_gross_amount", value)diff --git a/saleor/graphql/order/tests/queries/test_order_with_where.py b/saleor/graphql/order/tests/queries/test_order_with_where.pyindex b80e224ea2..54faddb9c2 100644--- a/saleor/graphql/order/tests/queries/test_order_with_where.py+++ b/saleor/graphql/order/tests/queries/test_order_with_where.py@@ -2372,3 +2372,143 @@ def test_orders_filter_by_order_events(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}+++ ("where", "indexes"),+ [+ (+ {+ "paymentMethodDetails": {+ "type": {"eq": "CARD"},+ }+ },+ [0, 2],+ ),+ (+ {+ "paymentMethodDetails": {+ "type": {"eq": "OTHER"},+ }+ },+ [1],+ ),+ (+ {+ "paymentMethodDetails": {+ "card": {+ "brand": {"eq": "Brand"},+ }+ }+ },+ [0],+ ),+ (+ {+ "paymentMethodDetails": {+ "card": {+ "brand": {"eq": "Brand4"},+ }+ }+ },+ [2],+ ),+ (+ {+ "paymentMethodDetails": {+ "card": {+ "brand": {"eq": "Brand2"},+ }+ }+ },+ [0],+ ),+ (+ {+ "paymentMethodDetails": {+ "type": {"oneOf": ["CARD", "OTHER"]},+ }+ },+ [0, 1, 2],+ ),+ (+ {+ "paymentMethodDetails": {+ "card": {+ "brand": {"oneOf": ["Brand2", "Brand4"]},+ }+ }+ },+ [0, 2],+ ),+ ],+)+def test_orders_filter_by_transaction_payment_details(+ where,+ indexes,+ order_list,+ staff_api_client,+ permission_group_manage_orders,+ transaction_item_generator,+):+ # given+ # first_transaction+ transaction_item_generator(+ order_id=order_list[0].pk,+ charged_value=order_list[0].total.gross.amount,+ payment_method_type="card",+ payment_method_name="Credit card",+ cc_brand="Brand",+ cc_first_digits="1234",+ cc_last_digits="5678",+ cc_exp_month=12,+ cc_exp_year=2025,+ )++ # second_transaction+ transaction_item_generator(+ order_id=order_list[0].pk,+ charged_value=order_list[0].total.gross.amount,+ payment_method_type="card",+ payment_method_name="Second Credit card",+ cc_brand="Brand2",+ cc_first_digits="1234",+ cc_last_digits="5678",+ cc_exp_month=12,+ cc_exp_year=2025,+ )++ # third_transaction+ transaction_item_generator(+ order_id=order_list[1].pk,+ charged_value=order_list[1].total.gross.amount,+ payment_method_type="other",+ payment_method_name="Third payment method",+ cc_brand=None,+ cc_first_digits=None,+ cc_last_digits=None,+ cc_exp_month=None,+ cc_exp_year=None,+ )++ # fourth_transaction+ transaction_item_generator(+ order_id=order_list[2].pk,+ charged_value=order_list[2].total.gross.amount,+ payment_method_type="card",+ payment_method_name="Fourth Credit card",+ cc_brand="Brand4",+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"where": {"transactions": where}}++ # 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(indexes)+ numbers = {node["node"]["number"] for node in orders}+ assert numbers == {str(order_list[index].number) for index in indexes}diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.pyindex f151dff959..6ea0ead977 100644--- a/saleor/graphql/payment/enums.py+++ b/saleor/graphql/payment/enums.py@@ -2,6 +2,7 @@ import graphenefrom ...payment import (ChargeStatus,+ PaymentMethodType,StorePaymentMethod,TokenizedPaymentFlow,TransactionAction,@@ -35,6 +36,13 @@ TransactionEventTypeEnum = to_enum()TransactionEventTypeEnum.doc_category = DOC_CATEGORY_PAYMENTS+PaymentMethodTypeEnum = to_enum(+ PaymentMethodType,+ type_name="PaymentMethodTypeEnum",+ description=PaymentMethodType.__doc__,+)+PaymentMethodTypeEnum.doc_category = DOC_CATEGORY_PAYMENTS+class OrderAction(BaseEnum):CAPTURE = "CAPTURE"diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3cec75b4da..3abcdb5331 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -13091,6 +13091,9 @@ input OrderWhereInput @doc(category: "Orders") {"""Filter by number of lines in the order."""linesCount: IntFilterInput+ """Filter by transaction data associated with the order."""+ transactions: TransactionFilterInput+"""Filter by total gross amount of the order."""totalGross: PriceFilterInput@@ -13188,6 +13191,47 @@ input LinesFilterInput @doc(category: "Orders") {metadata: MetadataFilterInput}+"""Filter input for transactions."""+input TransactionFilterInput @doc(category: "Orders") {+ """Filter by payment method details used to pay for the order."""+ paymentMethodDetails: PaymentMethodDetailsFilterInput+}++input PaymentMethodDetailsFilterInput {+ """Filter by payment method type used to pay for the order."""+ type: PaymentMethodTypeEnumFilterInput++ """+ Filter by card details used to pay for the order. Skips `type` filter if provided.+ """+ card: PaymentMethodDetailsCardFilterInput+}++input PaymentMethodTypeEnumFilterInput {+ """The value equal to."""+ eq: PaymentMethodTypeEnum++ """The value included in."""+ oneOf: [PaymentMethodTypeEnum!]+}++"""+Represents possible payment method types.++ The following types are possible:+ CARD - represents a card payment method.+ OTHER - represents any payment method that is not a card payment.+"""+enum PaymentMethodTypeEnum @doc(category: "Payments") {+ CARD+ OTHER+}++input PaymentMethodDetailsCardFilterInput {+ """Filter by payment method brand used to pay for the order."""+ brand: StringFilterInput+}+input PriceFilterInput {"""The currency of the price to filter by."""currency: Stringdiff --git a/saleor/payment/migrations/0063_transactionitem_payment_method_type_ids_and_more.py b/saleor/payment/migrations/0063_transactionitem_payment_method_type_ids_and_more.pynew file mode 100644index 0000000000..178db88130--- /dev/null+++ b/saleor/payment/migrations/0063_transactionitem_payment_method_type_ids_and_more.py@@ -0,0 +1,30 @@+# Generated by Django 5.2.1 on 2025-06-18 08:13++from django.contrib.postgres.indexes import BTreeIndex+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("account", "0087_alter_address_metadata_and_more"),+ ("app", "0031_alter_appextension_mount_alter_appextension_target"),+ ("checkout", "0080_merge_20250527_1210"),+ ("order", "0210_populated_order_line_product_type_id"),+ ("payment", "0062_transactionitem_cc_brand_and_more"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="transactionitem",+ index=BTreeIndex(+ fields=["payment_method_type"], name="payment_method_type_ids"+ ),+ ),+ AddIndexConcurrently(+ model_name="transactionitem",+ index=BTreeIndex(fields=["cc_brand"], name="cc_brand_idx"),+ ),+ ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 3eb6c120d5..10a0a66ade 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -4,7 +4,7 @@ from uuid import uuid4from django.conf import settingsfrom django.contrib.postgres.fields import ArrayField-from django.contrib.postgres.indexes import GinIndex+from django.contrib.postgres.indexes import BTreeIndex, GinIndexfrom django.core.serializers.json import DjangoJSONEncoderfrom django.core.validators import MaxValueValidator, MinValueValidatorfrom django.db import models@@ -180,6 +180,8 @@ class TransactionItem(ModelWithMetadata):ordering = ("pk",)indexes = [*ModelWithMetadata.Meta.indexes,+ BTreeIndex(fields=["payment_method_type"], name="payment_method_type_ids"),+ BTreeIndex(fields=["cc_brand"], name="cc_brand_idx"),]constraints = [models.UniqueConstraint(diff --git a/saleor/payment/tests/fixtures/transaction_item.py b/saleor/payment/tests/fixtures/transaction_item.pyindex bf4e7558c4..07cfaa942a 100644--- a/saleor/payment/tests/fixtures/transaction_item.py+++ b/saleor/payment/tests/fixtures/transaction_item.py@@ -25,6 +25,13 @@ def transaction_item_generator():canceled_value=Decimal(0),use_old_id=False,last_refund_success=True,+ payment_method_type=None,+ payment_method_name=None,+ cc_brand=None,+ cc_first_digits=None,+ cc_last_digits=None,+ cc_exp_month=None,+ cc_exp_year=None,):if available_actions is None:available_actions = []@@ -42,6 +49,13 @@ def transaction_item_generator():user=user,use_old_id=use_old_id,last_refund_success=last_refund_success,+ payment_method_type=payment_method_type,+ payment_method_name=payment_method_name,+ cc_brand=cc_brand,+ cc_first_digits=cc_first_digits,+ cc_last_digits=cc_last_digits,+ cc_exp_month=cc_exp_month,+ cc_exp_year=cc_exp_year,)create_manual_adjustment_events(transaction=transaction,