Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow filtering orders by total gross and net amount (#17804)
Iga Karbowiakf623ab428821
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5717f07e9e..d30455be23 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,7 @@ All notable, unreleased changes to this project will be documented in this file.- Filter by fulfillment existence.- Filter by associated fulfillment status.- Filter by number of lines in the order.+ - Filter by order total gross and net price amount.- 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.### Webhooksdiff --git a/saleor/graphql/core/types/filter_input.py b/saleor/graphql/core/types/filter_input.pyindex b38c7c4e7a..d5d2a3bf3e 100644--- a/saleor/graphql/core/types/filter_input.py+++ b/saleor/graphql/core/types/filter_input.py@@ -235,3 +235,12 @@ class UUIDFilterInput(graphene.InputObjectType):class Meta:description = "Define the filtering options for string fields."+++class PriceFilterInput(graphene.InputObjectType):+ currency = graphene.String(+ required=False, description="The currency of the price to filter by."+ )+ amount = DecimalFilterInput(+ required=True, description="The amount of the price to filter by."+ )diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex ad0e510a13..597df2f332 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -40,6 +40,7 @@ from ..core.types.filter_input import (FilterInputDescriptions,GlobalIDFilterInput,IntFilterInput,+ PriceFilterInput,StringFilterInput,UUIDFilterInput,WhereInputObjectType,@@ -53,6 +54,7 @@ from ..utils.filters import (filter_range_field,filter_where_by_id_field,filter_where_by_numeric_field,+ filter_where_by_price_field,filter_where_by_range_field,filter_where_by_value_field,)@@ -504,6 +506,16 @@ class OrderWhere(WhereFilterSet):method="filter_lines_count",help_text="Filter by number of lines in the order.",)+ total_gross = ObjectTypeWhereFilter(+ input_class=PriceFilterInput,+ method="filter_total_gross",+ help_text="Filter by total gross amount of the order.",+ )+ total_net = ObjectTypeWhereFilter(+ input_class=PriceFilterInput,+ method="filter_total_net",+ help_text="Filter by total net amount of the order.",+ )@staticmethoddef filter_number(qs, _, value):@@ -613,6 +625,14 @@ class OrderWhere(WhereFilterSet):def filter_lines_count(qs, _, value):return filter_where_by_numeric_field(qs, "lines_count", value)+ @staticmethod+ def filter_total_gross(qs, _, value):+ return filter_where_by_price_field(qs, "total_gross_amount", value)++ @staticmethod+ def filter_total_net(qs, _, value):+ return filter_where_by_price_field(qs, "total_net_amount", value)+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 46b206631b..aea19cb213 100644--- a/saleor/graphql/order/tests/queries/test_order_with_where.py+++ b/saleor/graphql/order/tests/queries/test_order_with_where.py@@ -21,6 +21,47 @@ from .....order.search import ()from ....tests.utils import get_graphql_content, get_graphql_content_from_response++def test_order_query_with_filter_and_where(+ staff_api_client,+ permission_group_manage_orders,+ orders,+):+ # given+ query = """+ query ($where: OrderWhereInput!, $filter: OrderFilterInput!) {+ orders(first: 10, where: $where, filter: $filter) {+ totalCount+ edges {+ node {+ id+ }+ }+ }+ }+ """+ variables = {+ "where": {+ "status": {+ "eq": OrderStatus.UNFULFILLED.upper(),+ },+ },+ "filter": {+ "search": "test",+ },+ }+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ error_message = "Only one filtering argument (filter or where) can be specified."++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content_from_response(response)+ assert content["errors"][0]["message"] == error_message+ assert not content["data"]["orders"]++ORDERS_WHERE_QUERY = """query($where: OrderWhereInput!, $search: String) {orders(first: 10, search: $search, where: $where) {@@ -1620,41 +1661,113 @@ def test_orders_filter_by_lines_count(assert numbers == {str(order_list[index].number) for index in indexes}-def test_order_query_with_filter_and_where(+ ("currency", "where", "indexes"),+ [+ ("USD", {"range": {"gte": "100.00", "lte": "200.00"}}, [0, 1]),+ ("USD", {"range": {"gte": "150.00"}}, [1]),+ ("PLN", {"range": {"gte": "150.00"}}, [2]),+ (None, {"range": {"gte": "150.00"}}, [1, 2]),+ ("USD", {"range": {"lte": "120.00"}}, [0]),+ ("USD", {"eq": "150.00"}, [1]),+ ("PLN", {"eq": "150.00"}, []),+ ("USD", {"oneOf": ["100.00", "110.00"]}, [0]),+ ("USD", {}, []),+ (None, {"range": {"gte": None}}, []),+ ("USD", {"range": {"lte": None}}, []),+ ("USD", {"eq": None}, []),+ (None, {"eq": None}, []),+ ],+)+def test_orders_filter_by_total_gross(+ currency,+ where,+ indexes,+ order_list,staff_api_client,permission_group_manage_orders,- orders,):# given- query = """- query ($where: OrderWhereInput!, $filter: OrderFilterInput!) {- orders(first: 10, where: $where, filter: $filter) {- totalCount- edges {- node {- id- }- }+ order_list[0].total_gross_amount = "110.00"+ order_list[0].currency = "USD"+ order_list[1].total_gross_amount = "150.00"+ order_list[1].currency = "USD"+ order_list[2].total_gross_amount = "200.00"+ order_list[2].currency = "PLN"+ Order.objects.bulk_update(order_list, ["total_gross_amount", "currency"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {+ "where": {+ "totalGross": {+ "currency": currency,+ "amount": 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}+++ ("currency", "where", "indexes"),+ [+ ("USD", {"range": {"gte": "100.00", "lte": "200.00"}}, [0, 1]),+ ("USD", {"range": {"gte": "150.00"}}, [1]),+ ("PLN", {"range": {"gte": "150.00"}}, [2]),+ (None, {"range": {"gte": "150.00"}}, [1, 2]),+ ("USD", {"range": {"lte": "120.00"}}, [0]),+ ("USD", {"eq": "150.00"}, [1]),+ ("PLN", {"eq": "150.00"}, []),+ ("USD", {"oneOf": ["100.00", "110.00"]}, [0]),+ ("USD", {}, []),+ (None, {"range": {"gte": None}}, []),+ ("USD", {"range": {"lte": None}}, []),+ ("USD", {"eq": None}, []),+ (None, {"eq": None}, []),+ ],+)+def test_orders_filter_by_total_net(+ currency,+ where,+ indexes,+ order_list,+ staff_api_client,+ permission_group_manage_orders,+):+ # given+ order_list[0].total_net_amount = "110.00"+ order_list[0].currency = "USD"+ order_list[1].total_net_amount = "150.00"+ order_list[1].currency = "USD"+ order_list[2].total_net_amount = "200.00"+ order_list[2].currency = "PLN"+ Order.objects.bulk_update(order_list, ["total_net_amount", "currency"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)variables = {"where": {- "status": {- "eq": OrderStatus.UNFULFILLED.upper(),- },- },- "filter": {- "search": "test",- },+ "totalNet": {+ "currency": currency,+ "amount": where,+ }+ }}- permission_group_manage_orders.user_set.add(staff_api_client.user)- error_message = "Only one filtering argument (filter or where) can be specified."# when- response = staff_api_client.post_graphql(query, variables)+ response = staff_api_client.post_graphql(ORDERS_WHERE_QUERY, variables)# then- content = get_graphql_content_from_response(response)- assert content["errors"][0]["message"] == error_message- assert not content["data"]["orders"]+ 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/schema.graphql b/saleor/graphql/schema.graphqlindex 223718624f..8410200fad 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -12883,6 +12883,12 @@ input OrderWhereInput @doc(category: "Orders") {"""Filter by number of lines in the order."""linesCount: IntFilterInput+ """Filter by total gross amount of the order."""+ totalGross: PriceFilterInput++ """Filter by total net amount of the order."""+ totalNet: PriceFilterInput+"""List of conditions that must be met."""AND: [OrderWhereInput!]@@ -12959,6 +12965,14 @@ input FulfillmentStatusEnumFilterInput @doc(category: "Orders") {oneOf: [FulfillmentStatus!]}+input PriceFilterInput {+ """The currency of the price to filter by."""+ currency: String++ """The amount of the price to filter by."""+ amount: DecimalFilterInput!+}+input OrderDraftFilterInput @doc(category: "Orders") {customer: Stringcreated: DateRangeInputdiff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.pyindex c5f5df1dfb..8bb5077c9b 100644--- a/saleor/graphql/utils/filters.py+++ b/saleor/graphql/utils/filters.py@@ -154,3 +154,11 @@ def filter_where_by_numeric_field(qs = qs.filter(**{f"{field}__gte": gte})return qsreturn qs.none()+++def filter_where_by_price_field(qs: "QuerySet", field: str, value: dict) -> "QuerySet":+ if value is None:+ return qs.none()+ if currency := value.get("currency"):+ qs = qs.filter(currency=currency)+ return filter_where_range_field(qs, field, value.get("amount", {}))diff --git a/saleor/order/migrations/0211_order_totalamount_indexes.py b/saleor/order/migrations/0211_order_totalamount_indexes.pynew file mode 100644index 0000000000..a048b2e385--- /dev/null+++ b/saleor/order/migrations/0211_order_totalamount_indexes.py@@ -0,0 +1,35 @@+# Generated by Django 5.2.1 on 2025-06-11 10:14++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"),+ ("channel", "0022_merge_20250527_1210"),+ ("discount", "0086_merge_20250527_1210"),+ ("giftcard", "0022_merge_20250527_1210"),+ ("order", "0210_populated_order_line_product_type_id"),+ ("shipping", "0036_merge_20250527_1210"),+ ("tax", "0011_merge_20250530_0929"),+ ("warehouse", "0035_alter_warehouse_metadata_and_more"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="order",+ index=BTreeIndex(+ fields=["total_gross_amount"], name="order_totalgrossamount_idx"+ ),+ ),+ AddIndexConcurrently(+ model_name="order",+ index=BTreeIndex(+ fields=["total_net_amount"], name="order_totalnetamount_idx"+ ),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 354ce57510..0e24d557dd 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -396,6 +396,14 @@ class Order(ModelWithMetadata, ModelWithExternalReference):),BTreeIndex(fields=["checkout_token"], name="checkout_token_btree_idx"),BTreeIndex(fields=["lines_count"], name="lines_count_idx"),+ BTreeIndex(+ fields=["total_gross_amount"],+ name="order_totalgrossamount_idx",+ ),+ BTreeIndex(+ fields=["total_net_amount"],+ name="order_totalnetamount_idx",+ ),]def is_fully_paid(self):