Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend `CustomerWhereFilter` with new options (#17856)
Iga Karbowiak102fd5112684
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a963725f9..48d784d39a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,10 @@ All notable, unreleased changes to this project will be documented in this file.- You can now filter and search customers using the new `where` and `search` fields on the `customers` query.- Use `where` to define complex conditions with `AND`/`OR` logic and operators like `eq`, `oneOf`, `range`.- Use `search` to perform full-text search across relevant fields.+ - Introduced new filtering options for customers:+ - Filter by email address.+ - Filter by active status (`isActive`).+ - Filter by phone numbers associated with user addresses.### Webhooks- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.diff --git a/saleor/account/migrations/0089_user_user_email_idx.py b/saleor/account/migrations/0089_user_user_email_idx.pynew file mode 100644index 0000000000..aa1d670a00--- /dev/null+++ b/saleor/account/migrations/0089_user_user_email_idx.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.1 on 2025-06-23 11:17++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", "0088_user_user_date_joined_idx"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="user",+ index=BTreeIndex(fields=["email"], name="user_email_idx"),+ ),+ ]diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 7e5c09740e..c3f9cec087 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -237,6 +237,10 @@ class User(fields=["date_joined"],name="user_date_joined_idx",),+ BTreeIndex(+ fields=["email"],+ name="user_email_idx",+ ),]def __init__(self, *args, **kwargs):diff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.pyindex a9d4a2ad6d..d00455b3c6 100644--- a/saleor/graphql/account/filters.py+++ b/saleor/graphql/account/filters.py@@ -1,11 +1,12 @@import django_filtersfrom django.db.models import Count, Exists, OuterRef-from ...account.models import User+from ...account.models import Address, Userfrom ...account.search import search_usersfrom ...order.models import Orderfrom ..core.doc_category import DOC_CATEGORY_USERSfrom ..core.filters import (+ BooleanWhereFilter,EnumFilter,GlobalIDMultipleChoiceFilter,GlobalIDMultipleChoiceWhereFilter,@@ -15,14 +16,21 @@ from ..core.filters import ()from ..core.filters.where_filters import MetadataWhereBasefrom ..core.filters.where_input import (+ StringFilterInput,WhereInputObjectType,)-from ..core.types import DateRangeInput, DateTimeRangeInput, IntRangeInput+from ..core.types import (+ BaseInputObjectType,+ DateRangeInput,+ DateTimeRangeInput,+ IntRangeInput,+)from ..utils.filters import (filter_by_id,filter_by_ids,filter_range_field,filter_where_by_range_field,+ filter_where_by_value_field,)from . import types as account_typesfrom .enums import StaffMemberStatus@@ -89,8 +97,27 @@ class CustomerFilter(MetadataFilterBase):]+class AddressFilterInput(BaseInputObjectType):+ phone_number = StringFilterInput(+ help_text="Filter by phone number.",+ )++ class Meta:+ doc_category = DOC_CATEGORY_USERS+ description = "Filtering options for addresses."++class CustomerWhereFilterInput(MetadataWhereBase):ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("User"))+ email = ObjectTypeWhereFilter(+ input_class=StringFilterInput,+ method="filter_email",+ help_text="Filter by email address.",+ )+ is_active = BooleanWhereFilter(+ field_name="is_active",+ help_text="Filter by whether the user is active.",+ )date_joined = ObjectTypeWhereFilter(input_class=DateTimeRangeInput,method="filter_date_joined",@@ -106,6 +133,21 @@ class CustomerWhereFilterInput(MetadataWhereBase):method="filter_placed_orders_at",help_text="Filter by date when orders were placed.",)+ addresses = ObjectTypeWhereFilter(+ input_class=AddressFilterInput,+ method="filter_addresses",+ help_text="Filter by addresses data associated with user.",+ )++ def filter_email(self, qs, _, value):+ if not value:+ return qs.none()+ return filter_where_by_value_field(qs, "email", value)++ def filter_is_active(self, qs, _, value):+ if value is None:+ return qs.none()+ return qs.filter(is_active=value)def filter_date_joined(self, qs, _, value):return filter_where_by_range_field(qs, "date_joined", value)@@ -121,6 +163,20 @@ class CustomerWhereFilterInput(MetadataWhereBase):)return qs.filter(Exists(orders.filter(user_id=OuterRef("id"))))+ def filter_addresses(self, qs, _, value):+ if not value:+ return qs.none()+ UserAddress = User.addresses.through+ if (phone_number := value.get("phone_number")) is not None:+ address_qs = filter_where_by_value_field(+ Address.objects.using(qs.db), "phone", phone_number+ )+ user_address_qs = UserAddress.objects.using(qs.db).filter(+ Exists(address_qs.filter(id=OuterRef("address_id"))),+ )+ return qs.filter(Exists(user_address_qs.filter(user_id=OuterRef("id"))))+ return qs.none()+class CustomerWhereInput(WhereInputObjectType):class Meta:diff --git a/saleor/graphql/account/tests/queries/test_customers_where_filtering.py b/saleor/graphql/account/tests/queries/test_customers_where_filtering.pyindex 6ed27c6abf..a2fc2e05d2 100644--- a/saleor/graphql/account/tests/queries/test_customers_where_filtering.py+++ b/saleor/graphql/account/tests/queries/test_customers_where_filtering.py@@ -5,7 +5,7 @@ import pytestfrom django.utils import timezonefrom freezegun import freeze_time-from .....account.models import User+from .....account.models import Address, Userfrom .....order import OrderOriginfrom ....tests.utils import get_graphql_content@@ -314,3 +314,136 @@ def test_customers_filter_by_placed_orders_at(assert len(customers) == len(indexes)emails = {node["node"]["email"] for node in customers}assert emails == {customer_users[index].email for index in indexes}+++ ("email_filter", "expected_indexes"),+ [+ ({"eq": "[email protected]"}, [0]),+ ({"eq": "[email protected]"}, [1]),+ ({"eq": "[email protected]"}, []),+ ({"oneOf": ["[email protected]", "[email protected]"]}, [0, 2]),+ ({"oneOf": ["[email protected]"]}, []),+ (None, []),+ ({"eq": None}, []),+ ({"oneOf": []}, []),+ ],+)+def test_customers_filter_by_email(+ email_filter,+ expected_indexes,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+):+ # given+ customer_emails = [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]+ for user, email in zip(customer_users, customer_emails, strict=True):+ user.email = email+ user.save(update_fields=["email"])++ permission_group_manage_users.user_set.add(staff_api_client.user)+ variables = {"where": {"email": email_filter}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == len(expected_indexes)+ emails = {node["node"]["email"] for node in customers}+ assert emails == {customer_users[i].email for i in expected_indexes}+++ ("is_active_filter", "expected_indexes"),+ [+ (True, [0, 1]),+ (False, [2]),+ (None, []),+ ],+)+def test_customers_filter_by_is_active(+ is_active_filter,+ expected_indexes,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+):+ # given+ is_active_values = [True, True, False]+ for user, is_active in zip(customer_users, is_active_values, strict=True):+ user.is_active = is_active+ user.save(update_fields=["is_active"])++ permission_group_manage_users.user_set.add(staff_api_client.user)+ variables = {"where": {"isActive": is_active_filter}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == len(expected_indexes)+ emails = {node["node"]["email"] for node in customers}+ assert emails == {customer_users[i].email for i in expected_indexes}+++ ("address_filter", "expected_indexes"),+ [+ ({"phoneNumber": {"eq": "+48123456789"}}, [0]),+ ({"phoneNumber": {"eq": "+1987654321"}}, [1]),+ ({"phoneNumber": {"eq": "notfound"}}, []),+ ({"phoneNumber": {"oneOf": ["+48123456789", "+86555555555"]}}, [0, 2]),+ ({"phoneNumber": {"oneOf": ["notfound"]}}, []),+ (None, []),+ ({"phoneNumber": {"eq": None}}, []),+ ({"phoneNumber": {"oneOf": []}}, []),+ ],+)+def test_customers_filter_by_addresses(+ address_filter,+ expected_indexes,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+):+ # given+ phones = [+ "+48123456789",+ "+1987654321",+ "+86555555555",+ ]+ for user, phone in zip(customer_users, phones, strict=True):+ user.addresses.add(+ Address.objects.create(+ first_name="John",+ last_name="Doe",+ company_name="Mirumee Software",+ street_address_1="Tęczowa 7",+ city="WROCŁAW",+ postal_code="53-601",+ country="PL",+ phone=phone,+ )+ )++ permission_group_manage_users.user_set.add(staff_api_client.user)+ variables = {"where": {"addresses": address_filter}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == len(expected_indexes)+ emails = {node["node"]["email"] for node in customers}+ assert emails == {customer_users[i].email for i in expected_indexes}diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 67a07f0645..8b06c9d6f5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -14418,6 +14418,12 @@ input CustomerWhereInput @doc(category: "Users") {metadata: MetadataFilterInputids: [ID!]+ """Filter by email address."""+ email: StringFilterInput++ """Filter by whether the user is active."""+ isActive: Boolean+"""Filter by date joined."""dateJoined: DateTimeRangeInput@@ -14427,6 +14433,9 @@ input CustomerWhereInput @doc(category: "Users") {"""Filter by date when orders were placed."""placedOrdersAt: DateTimeRangeInput+ """Filter by addresses data associated with user."""+ addresses: AddressFilterInput+"""List of conditions that must be met."""AND: [CustomerWhereInput!]@@ -14434,6 +14443,11 @@ input CustomerWhereInput @doc(category: "Users") {OR: [CustomerWhereInput!]}+"""Filtering options for addresses."""+input AddressFilterInput @doc(category: "Users") {+ phoneNumber: StringFilterInput+}+input UserSortingInput @doc(category: "Users") {"""Specifies the direction in which to sort users."""direction: OrderDirection!