Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow filtering orders by shipping and billing address data (#17867)
Iga Karbowiak5144ee6bd55f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 29e316f8ce..4ecba64752 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,8 +26,9 @@ All notable, unreleased changes to this project will be documented in this file.- Filter by order metadata.- 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+ - Filter by associated event type and date.+ - Filter by associated payment method name and type.+ - Filter by associated billing and shipping address phone number and country code.- 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 ID@@ -43,10 +44,9 @@ All notable, unreleased changes to this project will be documented in this file.- Introduced new filtering options for customers:- Filter by email address.- Filter by active status (`isActive`).- - Filter by phone numbers associated with user addresses.+ - Filter by phone numbers and country of associated user addresses.- Deprecated the `filter` argument in favor of the new `where` and `search` arguments.The `where` argument introduces more flexible filtering, allowing complex conditions using `AND`/`OR` logic and operators such as `eq`, `oneOf`, and `range`.-The `filter` argument has been deprecated in the following queries:- `attributes`- `customers`diff --git a/saleor/account/migrations/0092_address_address_country_idx.py b/saleor/account/migrations/0092_address_address_country_idx.pynew file mode 100644index 0000000000..63f663a108--- /dev/null+++ b/saleor/account/migrations/0092_address_address_country_idx.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.1 on 2025-06-25 09:45++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", "0091_populate_user_number_of_orders"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="address",+ index=BTreeIndex(fields=["country"], name="address_country_idx"),+ ),+ ]diff --git a/saleor/account/models.py b/saleor/account/models.pyindex a68bbb38b6..9cf5847279 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -93,6 +93,10 @@ class Address(ModelWithMetadata):],opclasses=["gin_trgm_ops"] * 6,),+ BTreeIndex(+ fields=["country"],+ name="address_country_idx",+ ),]def __eq__(self, other):diff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.pyindex d00455b3c6..6108e03137 100644--- a/saleor/graphql/account/filters.py+++ b/saleor/graphql/account/filters.py@@ -16,6 +16,7 @@ from ..core.filters import ()from ..core.filters.where_filters import MetadataWhereBasefrom ..core.filters.where_input import (+ FilterInputDescriptions,StringFilterInput,WhereInputObjectType,)@@ -24,6 +25,7 @@ from ..core.types import (DateRangeInput,DateTimeRangeInput,IntRangeInput,+ NonNullList,)from ..utils.filters import (filter_by_id,@@ -33,7 +35,7 @@ from ..utils.filters import (filter_where_by_value_field,)from . import types as account_types-from .enums import StaffMemberStatus+from .enums import CountryCodeEnum, StaffMemberStatusdef filter_date_joined(qs, _, value):@@ -71,6 +73,17 @@ def filter_search(qs, _, value):return qs+def filter_address(value):+ if not value:+ return Address.objects.none()+ address_qs = Address.objects.all()+ if (phone_number := value.get("phone_number")) is not None:+ address_qs = filter_where_by_value_field(address_qs, "phone", phone_number)+ if (country := value.get("country")) is not None:+ address_qs = filter_where_by_value_field(address_qs, "country", country)+ return address_qs++class CustomerFilter(MetadataFilterBase):ids = GlobalIDMultipleChoiceFilter(field_name="id", help_text="Filter by ids.")date_joined = ObjectTypeFilter(@@ -97,10 +110,31 @@ class CustomerFilter(MetadataFilterBase):]+class CountryCodeEnumFilterInput(BaseInputObjectType):+ eq = CountryCodeEnum(description=FilterInputDescriptions.EQ, required=False)+ one_of = NonNullList(+ CountryCodeEnum,+ description=FilterInputDescriptions.ONE_OF,+ required=False,+ )+ not_one_of = NonNullList(+ CountryCodeEnum,+ description=FilterInputDescriptions.NOT_ONE_OF,+ required=False,+ )++ class Meta:+ doc_category = DOC_CATEGORY_USERS+ description = "Filter by country code."++class AddressFilterInput(BaseInputObjectType):phone_number = StringFilterInput(help_text="Filter by phone number.",)+ country = CountryCodeEnumFilterInput(+ help_text="Filter by country code.",+ )class Meta:doc_category = DOC_CATEGORY_USERS@@ -167,15 +201,11 @@ class CustomerWhereFilterInput(MetadataWhereBase):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()+ address_qs = filter_address(value)+ 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"))))class CustomerWhereInput(WhereInputObjectType):diff --git a/saleor/graphql/account/tests/queries/test_customers_where_filtering.py b/saleor/graphql/account/tests/queries/test_customers_where_filtering.pyindex a2fc2e05d2..0e2454d9f2 100644--- a/saleor/graphql/account/tests/queries/test_customers_where_filtering.py+++ b/saleor/graphql/account/tests/queries/test_customers_where_filtering.py@@ -403,9 +403,27 @@ def test_customers_filter_by_is_active(({"phoneNumber": {"eq": "notfound"}}, []),({"phoneNumber": {"oneOf": ["+48123456789", "+86555555555"]}}, [0, 2]),({"phoneNumber": {"oneOf": ["notfound"]}}, []),+ ({"country": {"eq": "GE"}}, [0]),+ ({"country": {"eq": "US"}}, [1]),+ ({"country": {"eq": "CN"}}, [2]),+ ({"country": {"eq": "JP"}}, []),+ ({"country": {"oneOf": ["GE", "CN"]}}, [0, 2]),+ ({"country": {"oneOf": ["JP"]}}, []),+ ({"country": {"notOneOf": ["GE", "CN", "PL"]}}, [1]),+ ({"phoneNumber": {"eq": "+48123456789"}, "country": {"eq": "GE"}}, [0]),+ ({"phoneNumber": {"eq": "+48123456789"}, "country": {"eq": "US"}}, []),+ (+ {+ "phoneNumber": {"oneOf": ["+48123456789", "+86555555555"]},+ "country": {"notOneOf": ["GE"]},+ },+ [2],+ ),(None, []),({"phoneNumber": {"eq": None}}, []),({"phoneNumber": {"oneOf": []}}, []),+ ({"country": {"eq": None}}, []),+ ({"country": {"oneOf": []}}, []),],)def test_customers_filter_by_addresses(@@ -421,19 +439,22 @@ def test_customers_filter_by_addresses("+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,- )+ countries = ["GE", "US", "CN"]+ addresses = [+ 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=country,+ phone=phone,)+ for phone, country in zip(phones, countries, strict=True)+ ]+ for user, address in zip(customer_users, addresses, strict=True):+ user.addresses.add(address)permission_group_manage_users.user_set.add(staff_api_client.user)variables = {"where": {"addresses": address_filter}}diff --git a/saleor/graphql/core/filters/where_input.py b/saleor/graphql/core/filters/where_input.pyindex 1406801484..5767da8827 100644--- a/saleor/graphql/core/filters/where_input.py+++ b/saleor/graphql/core/filters/where_input.py@@ -54,6 +54,7 @@ class WhereInputObjectType(FilterInputObjectType):class FilterInputDescriptions:EQ = "The value equal to."ONE_OF = "The value included in."+ NOT_ONE_OF = "The value not included in."RANGE = "The value in range."diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex 3f11ee7363..b20e106d77 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -17,6 +17,7 @@ from ...order.search import search_ordersfrom ...payment import ChargeStatus, PaymentMethodTypefrom ...payment.models import TransactionItemfrom ...product.models import ProductVariant+from ..account.filters import AddressFilterInput, filter_addressfrom ..channel.filters import get_currency_from_filter_datafrom ..core.doc_category import DOC_CATEGORY_ORDERSfrom ..core.filters import (@@ -657,6 +658,16 @@ class OrderWhere(MetadataWhereBase):method="filter_events",help_text="Filter by order events.",)+ billing_address = ObjectTypeWhereFilter(+ input_class=AddressFilterInput,+ method="filter_billing_address",+ help_text="Filter by billing address of the order.",+ )+ shipping_address = ObjectTypeWhereFilter(+ input_class=AddressFilterInput,+ method="filter_shipping_address",+ help_text="Filter by shipping address of the order.",+ )@staticmethoddef filter_number(qs, _, value):@@ -816,6 +827,20 @@ class OrderWhere(MetadataWhereBase):qs = qs.filter(Exists(events.filter(order_id=OuterRef("id"))))return qs+ @staticmethod+ def filter_billing_address(qs, _, value):+ if not value:+ return qs.none()+ address_qs = filter_address(value)+ return qs.filter(Exists(address_qs.filter(id=OuterRef("billing_address_id"))))++ @staticmethod+ def filter_shipping_address(qs, _, value):+ if not value:+ return qs.none()+ address_qs = filter_address(value)+ return qs.filter(Exists(address_qs.filter(id=OuterRef("shipping_address_id"))))+class OrderWhereInput(WhereInputObjectType):class Meta:diff --git a/saleor/graphql/order/tests/queries/test_order_with_where.py b/saleor/graphql/order/tests/queries/test_order_with_where.pyindex 54faddb9c2..2b5c76d671 100644--- a/saleor/graphql/order/tests/queries/test_order_with_where.py+++ b/saleor/graphql/order/tests/queries/test_order_with_where.py@@ -6,6 +6,7 @@ import pytestfrom django.utils import timezonefrom freezegun import freeze_time+from .....account.models import Addressfrom .....core.postgres import FlatConcatSearchVectorfrom .....giftcard.events import gift_cards_bought_event, gift_cards_used_in_order_eventfrom .....invoice.models import Invoice@@ -2512,3 +2513,155 @@ def test_orders_filter_by_transaction_payment_details(assert len(orders) == len(indexes)numbers = {node["node"]["number"] for node in orders}assert numbers == {str(order_list[index].number) for index in 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"]}}, []),+ ({"country": {"eq": "GE"}}, [0]),+ ({"country": {"eq": "US"}}, [1]),+ ({"country": {"eq": "CN"}}, [2]),+ ({"country": {"eq": "JP"}}, []),+ ({"country": {"oneOf": ["GE", "CN"]}}, [0, 2]),+ ({"country": {"oneOf": ["JP"]}}, []),+ ({"country": {"notOneOf": ["GE", "CN", "PL"]}}, [1]),+ ({"phoneNumber": {"eq": "+48123456789"}, "country": {"eq": "GE"}}, [0]),+ ({"phoneNumber": {"eq": "+48123456789"}, "country": {"eq": "US"}}, []),+ (+ {+ "phoneNumber": {"oneOf": ["+48123456789", "+86555555555"]},+ "country": {"notOneOf": ["GE"]},+ },+ [2],+ ),+ (None, []),+ ({"phoneNumber": {"eq": None}}, []),+ ({"phoneNumber": {"oneOf": []}}, []),+ ({"country": {"eq": None}}, []),+ ({"country": {"oneOf": []}}, []),+ ],+)+def test_orders_filter_by_billing_address(+ address_filter,+ expected_indexes,+ order_list,+ staff_api_client,+ permission_group_manage_orders,+):+ # given+ phones = [+ "+48123456789",+ "+1987654321",+ "+86555555555",+ ]+ countries = ["GE", "US", "CN"]+ addresses = [+ 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=country,+ phone=phone,+ )+ for phone, country in zip(phones, countries, strict=True)+ ]+ for order, address in zip(order_list, addresses, strict=True):+ order.billing_address = address+ Order.objects.bulk_update(order_list, ["billing_address"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"where": {"billingAddress": address_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}+++ ("address_filter", "expected_indexes"),+ [+ ({"phoneNumber": {"eq": "+48123456789"}}, [0]),+ ({"phoneNumber": {"eq": "+1987654321"}}, [1]),+ ({"phoneNumber": {"eq": "notfound"}}, []),+ ({"phoneNumber": {"oneOf": ["+48123456789", "+86555555555"]}}, [0, 2]),+ ({"phoneNumber": {"oneOf": ["notfound"]}}, []),+ ({"country": {"eq": "GE"}}, [0]),+ ({"country": {"eq": "US"}}, [1]),+ ({"country": {"eq": "CN"}}, [2]),+ ({"country": {"eq": "JP"}}, []),+ ({"country": {"oneOf": ["GE", "CN"]}}, [0, 2]),+ ({"country": {"oneOf": ["JP"]}}, []),+ ({"country": {"notOneOf": ["GE", "CN", "PL"]}}, [1]),+ ({"phoneNumber": {"eq": "+48123456789"}, "country": {"eq": "GE"}}, [0]),+ ({"phoneNumber": {"eq": "+48123456789"}, "country": {"eq": "US"}}, []),+ (+ {+ "phoneNumber": {"oneOf": ["+48123456789", "+86555555555"]},+ "country": {"notOneOf": ["GE"]},+ },+ [2],+ ),+ (None, []),+ ({"phoneNumber": {"eq": None}}, []),+ ({"phoneNumber": {"oneOf": []}}, []),+ ({"country": {"eq": None}}, []),+ ({"country": {"oneOf": []}}, []),+ ],+)+def test_orders_filter_by_shipping_address(+ address_filter,+ expected_indexes,+ order_list,+ staff_api_client,+ permission_group_manage_orders,+):+ # given+ phones = [+ "+48123456789",+ "+1987654321",+ "+86555555555",+ ]+ countries = ["GE", "US", "CN"]+ addresses = [+ 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=country,+ phone=phone,+ )+ for phone, country in zip(phones, countries, strict=True)+ ]+ for order, address in zip(order_list, addresses, strict=True):+ order.shipping_address = address+ Order.objects.bulk_update(order_list, ["shipping_address"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"where": {"shippingAddress": address_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}diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3abcdb5331..663e98b345 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -13106,6 +13106,12 @@ input OrderWhereInput @doc(category: "Orders") {"""Filter by order events."""events: OrderEventFilterInput+ """Filter by billing address of the order."""+ billingAddress: AddressFilterInput++ """Filter by shipping address of the order."""+ shippingAddress: AddressFilterInput+"""List of conditions that must be met."""AND: [OrderWhereInput!]@@ -13257,6 +13263,24 @@ input OrderEventTypeEnumFilterInput {oneOf: [OrderEventsEnum!]}+"""Filtering options for addresses."""+input AddressFilterInput @doc(category: "Users") {+ phoneNumber: StringFilterInput+ country: CountryCodeEnumFilterInput+}++"""Filter by country code."""+input CountryCodeEnumFilterInput @doc(category: "Users") {+ """The value equal to."""+ eq: CountryCode++ """The value included in."""+ oneOf: [CountryCode!]++ """The value not included in."""+ notOneOf: [CountryCode!]+}+input OrderDraftFilterInput @doc(category: "Orders") {customer: Stringcreated: DateRangeInput@@ -14507,11 +14531,6 @@ 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!diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.pyindex f89a97c2f4..c2b4c4be51 100644--- a/saleor/graphql/utils/filters.py+++ b/saleor/graphql/utils/filters.py@@ -2,6 +2,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKINGfrom uuid import UUID+from django.db.models import Qfrom django.utils import timezonefrom ..core.enums import ReportingPeriod@@ -108,6 +109,8 @@ def filter_where_by_value_field(return qs.filter(**{field: value["eq"]})if one_of := value.get("one_of"):return qs.filter(**{f"{field}__in": one_of})+ if not_one_of := value.get("not_one_of"):+ return qs.filter(~Q(**{f"{field}__in": not_one_of}))return qs.none()